📦
13786 /agent.js
1428 /node_modules/@frida/base64-js/index.js
↻ base64-js
25206 /node_modules/@frida/buffer/index.js
↻ buffer
1001 /node_modules/@frida/ieee754/index.js
↻ ieee754
8289 /node_modules/frida-java-bridge/index.js
↻ frida-java-bridge
903 /node_modules/frida-java-bridge/lib/alloc.js
82544 /node_modules/frida-java-bridge/lib/android.js
141 /node_modules/frida-java-bridge/lib/api.js
27255 /node_modules/frida-java-bridge/lib/class-factory.js
36340 /node_modules/frida-java-bridge/lib/class-model.js
19095 /node_modules/frida-java-bridge/lib/env.js
17792 /node_modules/frida-java-bridge/lib/jvm.js
1278 /node_modules/frida-java-bridge/lib/jvmti.js
451 /node_modules/frida-java-bridge/lib/lru.js
173 /node_modules/frida-java-bridge/lib/machine-code.js
97 /node_modules/frida-java-bridge/lib/memoize.js
9137 /node_modules/frida-java-bridge/lib/mkdex.js
100 /node_modules/frida-java-bridge/lib/result.js
8168 /node_modules/frida-java-bridge/lib/types.js
2180 /node_modules/frida-java-bridge/lib/vm.js
✄
async function e(e){const s=[],{type:n,flavor:a,baseId:r}=e,o=e.scopes.slice().map((({name:e,members:t,addresses:s})=>({name:e,members:t.slice(),addresses:s?.slice()})));let i=r;do{const e=[],r={type:n,flavor:a,baseId:i,scopes:e};let c=0;for(const{name:t,members:s,addresses:n}of o){const a=Math.min(s.length,1e3-c);if(0===a)break;e.push({name:t,members:s.splice(0,a),addresses:n?.splice(0,a)}),c+=a}for(;0!==o.length&&0===o[0].members.length;)o.splice(0,1);send(r);const l=await t(`reply:${i}`);s.push(...l.scripts),i+=c}while(0!==o.length);return{scripts:s}}function t(e){return new Promise((t=>{recv(e,(e=>{t(e)}))}))}function s(e){const[t,s]=e.name.split("!").slice(-2);return["c",t,s]}function n(e){const{name:t}=e,[s,n]=t.substr(2,t.length-3).split(" ",2);return["objc",s,[n,t]]}function a(e){const{name:t}=e,[s,n]=t.split("!",2);return["swift",s,n]}function r(e){const t=DebugSymbol.fromAddress(e);return["c",t.moduleName??"",t.name]}function o(e){const t=e.split("!",2);let s,n;return 1===t.length?(s="*",n=t[0]):(s=""===t[0]?"*":t[0],n=""===t[1]?"*":t[1]),{module:s,function:n}}function i(e){return{loader:e.loader,classes:new Map(e.classes.map((e=>[e.name,c(e)])))}}function c(e){return{methods:new Map(e.methods.map((e=>[l(e),e])))}}function l(e){const t=e.indexOf("(");return-1===t?e:e.substr(0,t)}function d(e,t){for(const s of e)if(t(s))return s}function u(){}function h(e){Object.defineProperty(globalThis,e,{enumerable:!0,configurable:!0,get:()=>function(e){let t;return send({type:"frida:load-bridge",name:e}),recv("frida:bridge-loaded",(s=>{t=Script.evaluate(`/frida/bridges/${s.filename}`,"(function () { "+[s.source,`Object.defineProperty(globalThis, '${e}', { value: bridge });`,"return bridge;"].join("\n")+" })();")})).wait(),t}(e)})}class f{native=new Map;java=[];#e=null;get modules(){let e=this.#e;return null===e&&(e=new ModuleMap,this.#e=e),e}}const m=new class{handlers=new Map;nativeTargets=new Set;stagedPlanRequest=null;stackDepth=new Map;traceState={};nextId=1;started=Date.now();pendingEvents=[];flushTimer=null;cachedModuleResolver=null;cachedObjcResolver=null;cachedSwiftResolver=null;init(e,t,s,n){globalThis.stage=e,globalThis.parameters=t,globalThis.state=this.traceState,globalThis.defineHandler=e=>e,h("ObjC"),h("Swift"),h("Java");for(const e of s)Script.evaluate(e.filename,e.source);return this.start(n).catch((e=>{send({type:"agent:error",message:e.message})})),{id:Process.id,platform:Process.platform,arch:Process.arch,pointer_size:Process.pointerSize,page_size:Process.pageSize,main_module:Process.mainModule}}dispose(){this.flush()}updateHandlerCode(e,t,s){const n=this.handlers.get(e);if(void 0===n)throw new Error("invalid target ID");if(3===n.length){const a=this.parseFunctionHandler(s,e,t,this.onTraceError);n[0]=a[0],n[1]=a[1]}else{const a=this.parseInstructionHandler(s,e,t,this.onTraceError);n[0]=a[0]}}updateHandlerConfig(e,t){const s=this.handlers.get(e);if(void 0===s)throw new Error("invalid target ID");s[2]=t}async stageTargets(e){const t=await this.createPlan(e);this.stagedPlanRequest=t,await t.ready;const{plan:s}=t,n=[];let a=1;for(const[e,t,r]of s.native.values())n.push([a,t,r]),a++;a=-1;for(const e of s.java)for(const[t,s]of e.classes.entries())for(const e of s.methods.values())n.push([a,t,e]),a--;return n}async commitTargets(e){const t=this.stagedPlanRequest;this.stagedPlanRequest=null;let{plan:s}=t;null!==e&&(s=this.cropStagedPlan(s,e));const n=[],a=e=>{n.push(e)},r=await this.traceNativeTargets(s.native,a);let o=[];return 0!==s.java.length&&(o=await new Promise(((e,t)=>{globalThis.Java.perform((()=>{this.traceJavaTargets(s.java,a).then(e,t)}))}))),{ids:[...r,...o],errors:n}}readMemory(e,t){try{return ptr(e).readVolatile(t)}catch(e){return null}}resolveAddresses(e){let t=null;return e.map(ptr).map(DebugSymbol.fromAddress).map((e=>{if(null===e.name){null===t&&(t=new ModuleMap);const s=t.find(e.address);if(null!==s)return`${s.name}!${e.address.sub(s.base)}`}return e})).map((e=>e.toString()))}cropStagedPlan(e,t){let s;if(t<0){s=-1;for(const n of e.java)for(const[e,a]of n.classes.entries())for(const[r,o]of a.methods.entries()){if(s===t){const t={methods:new Map([[r,o]])},s={loader:n.loader,classes:new Map([[e,t]])},a=new f;return a.java.push(s),a}s--}}else{s=1;for(const[n,a]of e.native.entries()){if(s===t){const e=new f;return e.native.set(n,a),e}s++}}throw new Error("invalid staged item ID")}async start(e){const t=await this.createPlan(e,(async e=>{await this.traceJavaTargets(e.java,this.onTraceError)}));await this.traceNativeTargets(t.plan.native,this.onTraceError),send({type:"agent:initialized"}),t.ready.then((()=>{send({type:"agent:started",count:this.handlers.size})}))}onTraceError=({id:e,name:t,message:s})=>{send({type:"agent:warning",id:e,message:`Skipping "${t}": ${s}`})};async createPlan(e,t=(async()=>{})){const s=new f,n=[];for(const[t,a,r]of e)switch(a){case"module":"include"===t?this.includeModule(r,s):this.excludeModule(r,s);break;case"function":"include"===t?this.includeFunction(r,s):this.excludeFunction(r,s);break;case"relative-function":"include"===t&&this.includeRelativeFunction(r,s);break;case"absolute-instruction":"include"===t&&this.includeAbsoluteInstruction(ptr(r),s);break;case"imports":"include"===t&&this.includeImports(r,s);break;case"objc-method":"include"===t?this.includeObjCMethod(r,s):this.excludeObjCMethod(r,s);break;case"swift-func":"include"===t?this.includeSwiftFunc(r,s):this.excludeSwiftFunc(r,s);break;case"java-method":n.push([t,r]);break;case"debug-symbol":"include"===t&&this.includeDebugSymbol(r,s)}for(const e of s.native.keys())this.nativeTargets.has(e)&&s.native.delete(e);let a,r=!0;if(n.length>0){const e=globalThis.Java;if(!e.available)throw new Error("Java runtime is not available");a=new Promise(((a,o)=>{e.perform((async()=>{r=!1;try{for(const[e,t]of n)"include"===e?this.includeJavaMethod(t,s):this.excludeJavaMethod(t,s);await t(s),a()}catch(e){o(e)}}))}))}else a=Promise.resolve();return r||await a,{plan:s,ready:a}}async traceNativeTargets(e,t){const s=new Map,n=new Map,a=new Map,r=new Map;for(const[t,[o,i,c]]of e.entries()){let e;switch(o){case"insn":e=s;break;case"c":e=n;break;case"objc":e=a;break;case"swift":e=r}let l=e.get(i);void 0===l&&(l=[],e.set(i,l)),l.push([c,ptr(t)])}const[o,i,c]=await Promise.all([this.traceNativeEntries("insn",s,t),this.traceNativeEntries("c",n,t),this.traceNativeEntries("objc",a,t),this.traceNativeEntries("swift",r,t)]);return[...o,...i,...c]}async traceNativeEntries(t,s,n){if(0===s.size)return[];const a=this.nextId,r=[],o={type:"handlers:get",flavor:t,baseId:a,scopes:r};for(const[e,t]of s.entries())r.push({name:e,members:t.map((e=>e[0])),addresses:t.map((e=>e[1].toString()))}),this.nextId+=t.length;const{scripts:i}=await e(o),c=[];let l=0;const d="insn"===t;for(const e of s.values())for(const[t,s]of e){const e=a+l,r="string"==typeof t?t:t[1],o=d?this.parseInstructionHandler(i[l],e,r,n):this.parseFunctionHandler(i[l],e,r,n);this.handlers.set(e,o),this.nativeTargets.add(s.toString());try{Interceptor.attach(s,d?this.makeNativeInstructionListener(e,o):this.makeNativeFunctionListener(e,o))}catch(t){n({id:e,name:r,message:t.message})}c.push(e),l++}return c}async traceJavaTargets(t,s){const n=this.nextId,a=[],r={type:"handlers:get",flavor:"java",baseId:n,scopes:a};for(const e of t)for(const[t,{methods:s}]of e.classes.entries()){const e=t.split("."),n=e[e.length-1],r=Array.from(s.keys()).map((e=>[e,`${n}.${e}`]));a.push({name:t,members:r}),this.nextId+=r.length}const{scripts:o}=await e(r);return new Promise((e=>{const a=globalThis.Java;a.perform((()=>{const r=[];let i=0;for(const e of t){const t=a.ClassFactory.get(e.loader);for(const[a,{methods:c}]of e.classes.entries()){const e=t.use(a);for(const[t,a]of c.entries()){const c=n+i,l=this.parseFunctionHandler(o[i],c,a,s);this.handlers.set(c,l);const d=e[t];for(const e of d.overloads)e.implementation=this.makeJavaMethodWrapper(c,e,l);r.push(c),i++}}}e(r)}))}))}makeNativeFunctionListener(e,t){const s=this;return{onEnter(n){const[a,r,o]=t;s.invokeNativeHandler(e,a,o,this,n,">")},onLeave(n){const[a,r,o]=t;s.invokeNativeHandler(e,r,o,this,n,"<")}}}makeNativeInstructionListener(e,t){const s=this;return function(n){const[a,r]=t;s.invokeNativeHandler(e,a,r,this,n,"|")}}makeJavaMethodWrapper(e,t,s){const n=this;return function(...a){return n.handleJavaInvocation(e,t,s,this,a)}}handleJavaInvocation(e,t,s,n,a){const[r,o,i]=s;this.invokeJavaHandler(e,r,i,n,a,">");const c=t.apply(n,a),l=this.invokeJavaHandler(e,o,i,n,c,"<");return void 0!==l?l:c}invokeNativeHandler(e,t,s,n,a,r){const o=n.threadId,i=this.updateDepth(o,r);if(s.muted)return;const c=Date.now()-this.started,l=n.returnAddress.toString(),d=s.capture_backtraces?Thread.backtrace(n.context).map((e=>e.toString())):null;t.call(n,((...t)=>{this.emit([e,c,o,i,l,d,t.join(" ")])}),a,this.traceState)}invokeJavaHandler(e,t,s,n,a,r){const o=Process.getCurrentThreadId(),i=this.updateDepth(o,r);if(s.muted)return;const c=Date.now()-this.started,l=(...t)=>{this.emit([e,c,o,i,null,null,t.join(" ")])};try{return t.call(n,l,a,this.traceState)}catch(e){if(void 0!==e.$h)throw e;Script.nextTick((()=>{throw e}))}}updateDepth(e,t){const s=this.stackDepth;let n=s.get(e)??0;return">"===t?s.set(e,n+1):"<"===t&&(n--,0!==n?s.set(e,n):s.delete(e)),n}parseFunctionHandler(e,t,s,n){try{const t=this.parseHandlerScript(s,e);return[t.onEnter??u,t.onLeave??u,{muted:!1,capture_backtraces:!1}]}catch(e){return n({id:t,name:s,message:e.message}),[u,u,{muted:!1,capture_backtraces:!1}]}}parseInstructionHandler(e,t,s,n){try{return[this.parseHandlerScript(s,e),{muted:!1,capture_backtraces:!1}]}catch(e){return n({id:t,name:s,message:e.message}),[u,{muted:!1,capture_backtraces:!1}]}}parseHandlerScript(e,t){const s=`/handlers/${e}.js`;return Script.evaluate(s,t)}includeModule(e,t){const{native:n}=t;for(const t of this.getModuleResolver().enumerateMatches(`exports:${e}!*`))n.set(t.address.toString(),s(t))}excludeModule(e,t){const{native:s}=t;for(const t of this.getModuleResolver().enumerateMatches(`exports:${e}!*`))s.delete(t.address.toString())}includeFunction(e,t){const n=o(e),{native:a}=t;for(const e of this.getModuleResolver().enumerateMatches(`exports:${n.module}!${n.function}`))a.set(e.address.toString(),s(e))}excludeFunction(e,t){const s=o(e),{native:n}=t;for(const e of this.getModuleResolver().enumerateMatches(`exports:${s.module}!${s.function}`))n.delete(e.address.toString())}includeRelativeFunction(e,t){const s=function(e){const t=e.split("!",2);return{module:t[0],offset:parseInt(t[1],16)}}(e),n=Process.getModuleByName(s.module).base.add(s.offset);t.native.set(n.toString(),["c",s.module,`sub_${s.offset.toString(16)}`])}includeAbsoluteInstruction(e,t){const s=t.modules.find(e);null!==s?t.native.set(e.toString(),["insn",s.path,`insn_${e.sub(s.base).toString(16)}`]):t.native.set(e.toString(),["insn","",`insn_${e.toString(16)}`])}includeImports(e,t){let n;if(null===e){const e=Process.enumerateModules()[0].path;n=this.getModuleResolver().enumerateMatches(`imports:${e}!*`)}else n=this.getModuleResolver().enumerateMatches(`imports:${e}!*`);const{native:a}=t;for(const e of n)a.set(e.address.toString(),s(e))}includeObjCMethod(e,t){const{native:s}=t;for(const t of this.getObjcResolver().enumerateMatches(e))s.set(t.address.toString(),n(t))}excludeObjCMethod(e,t){const{native:s}=t;for(const t of this.getObjcResolver().enumerateMatches(e))s.delete(t.address.toString())}includeSwiftFunc(e,t){const{native:s}=t;for(const t of this.getSwiftResolver().enumerateMatches(`functions:${e}`))s.set(t.address.toString(),a(t))}excludeSwiftFunc(e,t){const{native:s}=t;for(const t of this.getSwiftResolver().enumerateMatches(`functions:${e}`))s.delete(t.address.toString())}includeJavaMethod(e,t){const s=t.java,n=Java.enumerateMethods(e);for(const e of n){const{loader:t}=e,n=d(s,(e=>{const{loader:s}=e;return null!==s&&null!==t?s.equals(t):s===t}));if(void 0===n){s.push(i(e));continue}const{classes:a}=n;for(const t of e.classes){const{name:e}=t,s=a.get(e);if(void 0===s){a.set(e,c(t));continue}const{methods:n}=s;for(const e of t.methods){const t=l(e),s=n.get(t);void 0===s?n.set(t,e):n.set(t,e.length>s.length?e:s)}}}}excludeJavaMethod(e,t){const s=t.java,n=globalThis.Java.enumerateMethods(e);for(const e of n){const{loader:t}=e,n=d(s,(e=>{const{loader:s}=e;return null!==s&&null!==t?s.equals(t):s===t}));if(void 0===n)continue;const{classes:a}=n;for(const t of e.classes){const{name:e}=t,s=a.get(e);if(void 0===s)continue;const{methods:n}=s;for(const e of t.methods){const t=l(e);n.delete(t)}}}}includeDebugSymbol(e,t){const{native:s}=t;for(const t of DebugSymbol.findFunctionsMatching(e))s.set(t.toString(),r(t))}emit(e){this.pendingEvents.push(e),null===this.flushTimer&&(this.flushTimer=setTimeout(this.flush,50))}flush=()=>{if(null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),0===this.pendingEvents.length)return;const e=this.pendingEvents;this.pendingEvents=[],send({type:"events:add",events:e})};getModuleResolver(){let e=this.cachedModuleResolver;return null===e&&(e=new ApiResolver("module"),this.cachedModuleResolver=e),e}getObjcResolver(){let e=this.cachedObjcResolver;if(null===e){try{e=new ApiResolver("objc")}catch(e){throw new Error("Objective-C runtime is not available")}this.cachedObjcResolver=e}return e}getSwiftResolver(){let e=this.cachedSwiftResolver;if(null===e){try{e=new ApiResolver("swift")}catch(e){throw new Error("Swift runtime is not available")}this.cachedSwiftResolver=e}return e}};rpc.exports={init:m.init.bind(m),dispose:m.dispose.bind(m),updateHandlerCode:m.updateHandlerCode.bind(m),updateHandlerConfig:m.updateHandlerConfig.bind(m),stageTargets:m.stageTargets.bind(m),commitTargets:m.commitTargets.bind(m),readMemory:m.readMemory.bind(m),resolveAddresses:m.resolveAddresses.bind(m)};export{};
✄
const t=[],o=[],n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let c=0,h=n.length;c<h;++c)t[c]=n[c],o[n.charCodeAt(c)]=c;function r(t){const o=t.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");let n=t.indexOf("=");-1===n&&(n=o);return[n,n===o?0:4-n%4]}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63;export function byteLength(t){const o=r(t),n=o[0],e=o[1];return 3*(n+e)/4-e}export function toByteArray(t){const n=r(t),e=n[0],c=n[1],h=new Uint8Array(function(t,o,n){return 3*(o+n)/4-n}(0,e,c));let s=0;const a=c>0?e-4:e;let f;for(f=0;f<a;f+=4){const n=o[t.charCodeAt(f)]<<18|o[t.charCodeAt(f+1)]<<12|o[t.charCodeAt(f+2)]<<6|o[t.charCodeAt(f+3)];h[s++]=n>>16&255,h[s++]=n>>8&255,h[s++]=255&n}if(2===c){const n=o[t.charCodeAt(f)]<<2|o[t.charCodeAt(f+1)]>>4;h[s++]=255&n}if(1===c){const n=o[t.charCodeAt(f)]<<10|o[t.charCodeAt(f+1)]<<4|o[t.charCodeAt(f+2)]>>2;h[s++]=n>>8&255,h[s++]=255&n}return h}function e(o,n,r){const e=[];for(let h=n;h<r;h+=3){const n=(o[h]<<16&16711680)+(o[h+1]<<8&65280)+(255&o[h+2]);e.push(t[(c=n)>>18&63]+t[c>>12&63]+t[c>>6&63]+t[63&c])}var c;return e.join("")}export function fromByteArray(o){const n=o.length,r=n%3,c=[],h=16383;for(let t=0,s=n-r;t<s;t+=h)c.push(e(o,t,t+h>s?s:t+h));if(1===r){const r=o[n-1];c.push(t[r>>2]+t[r<<4&63]+"==")}else if(2===r){const r=(o[n-2]<<8)+o[n-1];c.push(t[r>>10]+t[r>>4&63]+t[r<<2&63]+"=")}return c.join("")}
✄
/*!
 * The buffer module from node.js, for Frida.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
import*as t from"base64-js";import*as e from"ieee754";export const config={INSPECT_MAX_BYTES:50};const r=2147483647;export{r as kMaxLength};function n(t){if(t>2147483647)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,Buffer.prototype),e}Buffer.TYPED_ARRAY_SUPPORT=!0,Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.buffer}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.byteOffset}});export function Buffer(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return o(t)}return f(t,e,r)}function f(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!Buffer.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|a(t,e);let f=n(r);const i=f.write(t,e);i!==r&&(f=f.slice(0,i));return f}(t,e);if(ArrayBuffer.isView(t))return function(t){if(t instanceof Uint8Array){const e=new Uint8Array(t);return s(e.buffer,e.byteOffset,e.byteLength)}return u(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(t instanceof ArrayBuffer||t&&t.buffer instanceof ArrayBuffer)return s(t,e,r);if(t instanceof SharedArrayBuffer||t&&t.buffer instanceof SharedArrayBuffer)return s(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const f=t.valueOf&&t.valueOf();if(null!=f&&f!==t)return Buffer.from(f,e,r);const i=function(t){if(Buffer.isBuffer(t)){const e=0|h(t.length),r=n(e);return 0===r.length||t.copy(r,0,0,e),r}if(void 0!==t.length)return"number"!=typeof t.length||Number.isNaN(t.length)?n(0):u(t);if("Buffer"===t.type&&Array.isArray(t.data))return u(t.data)}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return Buffer.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function i(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function o(t){return i(t),n(t<0?0:0|h(t))}function u(t){const e=t.length<0?0:0|h(t.length),r=n(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function s(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,Buffer.prototype),n}function h(t){if(t>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|t}Buffer.poolSize=8192,Buffer.from=function(t,e,r){return f(t,e,r)},Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype),Object.setPrototypeOf(Buffer,Uint8Array),Buffer.alloc=function(t,e,r){return function(t,e,r){return i(t),t<=0?n(t):void 0!==e?"string"==typeof r?n(t).fill(e,r):n(t).fill(e):n(t)}(t,e,r)},Buffer.allocUnsafe=function(t){return o(t)},Buffer.allocUnsafeSlow=function(t){return o(t)};export function SlowBuffer(t){return+t!=t&&(t=0),Buffer.alloc(+t)}function a(t,e){if(Buffer.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let f=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return j(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return z(t).length;default:if(f)return n?-1:j(t).length;e=(""+e).toLowerCase(),f=!0}}function c(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return A(this,e,r);case"utf8":case"utf-8":return m(this,e,r);case"ascii":return I(this,e,r);case"latin1":case"binary":return U(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return v(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function l(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function p(t,e,r,n,f){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Number.isNaN(r)&&(r=f?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(f)return-1;r=t.length-1}else if(r<0){if(!f)return-1;r=0}if("string"==typeof e&&(e=Buffer.from(e,n)),Buffer.isBuffer(e))return 0===e.length?-1:g(t,e,r,n,f);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?f?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):g(t,[e],r,n,f);throw new TypeError("val must be string, number or Buffer")}function g(t,e,r,n,f){let i,o=1,u=t.length,s=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,u/=2,s/=2,r/=2}function h(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(f){let n=-1;for(i=r;i<u;i++)if(h(t,i)===h(e,-1===n?0:i-n)){if(-1===n&&(n=i),i-n+1===s)return n*o}else-1!==n&&(i-=i-n),n=-1}else for(r+s>u&&(r=u-s),i=r;i>=0;i--){let r=!0;for(let n=0;n<s;n++)if(h(t,i+n)!==h(e,n)){r=!1;break}if(r)return i}return-1}function y(t,e,r,n){r=Number(r)||0;const f=t.length-r;n?(n=Number(n))>f&&(n=f):n=f;const i=e.length;let o;for(n>i/2&&(n=i/2),o=0;o<n;++o){const n=parseInt(e.substr(2*o,2),16);if(Number.isNaN(n))return o;t[r+o]=n}return o}function B(t,e,r,n){return D(j(e,t.length-r),t,r,n)}function w(t,e,r,n){return D(function(t){const e=[];for(let r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function d(t,e,r,n){return D(z(e),t,r,n)}function b(t,e,r,n){return D(function(t,e){let r,n,f;const i=[];for(let o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,f=r%256,i.push(f),i.push(n);return i}(e,t.length-r),t,r,n)}function E(e,r,n){return 0===r&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,n))}function m(t,e,r){r=Math.min(t.length,r);const n=[];let f=e;for(;f<r;){const e=t[f];let i=null,o=e>239?4:e>223?3:e>191?2:1;if(f+o<=r){let r,n,u,s;switch(o){case 1:e<128&&(i=e);break;case 2:r=t[f+1],128==(192&r)&&(s=(31&e)<<6|63&r,s>127&&(i=s));break;case 3:r=t[f+1],n=t[f+2],128==(192&r)&&128==(192&n)&&(s=(15&e)<<12|(63&r)<<6|63&n,s>2047&&(s<55296||s>57343)&&(i=s));break;case 4:r=t[f+1],n=t[f+2],u=t[f+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(s=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&u,s>65535&&s<1114112&&(i=s))}}null===i?(i=65533,o=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),f+=o}return function(t){const e=t.length;if(e<=4096)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=4096));return r}(n)}Buffer.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==Buffer.prototype},Buffer.compare=function(t,e){if(t instanceof Uint8Array&&(t=Buffer.from(t,t.offset,t.byteLength)),e instanceof Uint8Array&&(e=Buffer.from(e,e.offset,e.byteLength)),!Buffer.isBuffer(t)||!Buffer.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let r=t.length,n=e.length;for(let f=0,i=Math.min(r,n);f<i;++f)if(t[f]!==e[f]){r=t[f],n=e[f];break}return r<n?-1:n<r?1:0},Buffer.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Buffer.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return Buffer.alloc(0);let r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;const n=Buffer.allocUnsafe(e);let f=0;for(r=0;r<t.length;++r){let e=t[r];if(e instanceof Uint8Array)f+e.length>n.length?(Buffer.isBuffer(e)||(e=Buffer.from(e.buffer,e.byteOffset,e.byteLength)),e.copy(n,f)):Uint8Array.prototype.set.call(n,e,f);else{if(!Buffer.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,f)}f+=e.length}return n},Buffer.byteLength=a,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)l(this,e,e+1);return this},Buffer.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)l(this,e,e+3),l(this,e+1,e+2);return this},Buffer.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)l(this,e,e+7),l(this,e+1,e+6),l(this,e+2,e+5),l(this,e+3,e+4);return this},Buffer.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?m(this,0,t):c.apply(this,arguments)},Buffer.prototype.toLocaleString=Buffer.prototype.toString,Buffer.prototype.equals=function(t){if(!Buffer.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Buffer.compare(this,t)},Buffer.prototype.inspect=function(){let t="";const e=config.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),"<Buffer "+t+">"},Buffer.prototype[Symbol.for("nodejs.util.inspect.custom")]=Buffer.prototype.inspect,Buffer.prototype.compare=function(t,e,r,n,f){if(t instanceof Uint8Array&&(t=Buffer.from(t,t.offset,t.byteLength)),!Buffer.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===f&&(f=this.length),e<0||r>t.length||n<0||f>this.length)throw new RangeError("out of range index");if(n>=f&&e>=r)return 0;if(n>=f)return-1;if(e>=r)return 1;if(this===t)return 0;let i=(f>>>=0)-(n>>>=0),o=(r>>>=0)-(e>>>=0);const u=Math.min(i,o),s=this.slice(n,f),h=t.slice(e,r);for(let t=0;t<u;++t)if(s[t]!==h[t]){i=s[t],o=h[t];break}return i<o?-1:o<i?1:0},Buffer.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},Buffer.prototype.indexOf=function(t,e,r){return p(this,t,e,r,!0)},Buffer.prototype.lastIndexOf=function(t,e,r){return p(this,t,e,r,!1)},Buffer.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const f=this.length-e;if((void 0===r||r>f)&&(r=f),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return y(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":case"latin1":case"binary":return w(this,t,e,r);case"base64":return d(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function I(t,e,r){let n="";r=Math.min(t.length,r);for(let f=e;f<r;++f)n+=String.fromCharCode(127&t[f]);return n}function U(t,e,r){let n="";r=Math.min(t.length,r);for(let f=e;f<r;++f)n+=String.fromCharCode(t[f]);return n}function A(t,e,r){const n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let f="";for(let n=e;n<r;++n)f+=G[t[n]];return f}function v(t,e,r){const n=t.slice(e,r);let f="";for(let t=0;t<n.length-1;t+=2)f+=String.fromCharCode(n[t]+256*n[t+1]);return f}function R(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function T(t,e,r,n,f,i){if(!Buffer.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>f||e<i)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function L(t,e,r,n,f){k(e,n,f,t,r,7);let i=Number(e&BigInt(4294967295));t[r++]=i,i>>=8,t[r++]=i,i>>=8,t[r++]=i,i>>=8,t[r++]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,r}function O(t,e,r,n,f){k(e,n,f,t,r,7);let i=Number(e&BigInt(4294967295));t[r+7]=i,i>>=8,t[r+6]=i,i>>=8,t[r+5]=i,i>>=8,t[r+4]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o>>=8,t[r+2]=o,o>>=8,t[r+1]=o,o>>=8,t[r]=o,r+8}function S(t,e,r,n,f,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function _(t,r,n,f,i){return r=+r,n>>>=0,i||S(t,0,n,4),e.write(t,r,n,f,23,4),n+4}function x(t,r,n,f,i){return r=+r,n>>>=0,i||S(t,0,n,8),e.write(t,r,n,f,52,8),n+8}Buffer.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);const n=this.subarray(t,e);return Object.setPrototypeOf(n,Buffer.prototype),n},Buffer.prototype.readUintLE=Buffer.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],f=1,i=0;for(;++i<e&&(f*=256);)n+=this[t+i]*f;return n},Buffer.prototype.readUintBE=Buffer.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t+--e],f=1;for(;e>0&&(f*=256);)n+=this[t+--e]*f;return n},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),this[t]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]|this[t+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]<<8|this[t+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Buffer.prototype.readBigUInt64LE=function(t){P(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||M(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,f=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(f)<<BigInt(32))},Buffer.prototype.readBigUInt64BE=function(t){P(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||M(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],f=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<<BigInt(32))+BigInt(f)},Buffer.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],f=1,i=0;for(;++i<e&&(f*=256);)n+=this[t+i]*f;return f*=128,n>=f&&(n-=Math.pow(2,8*e)),n},Buffer.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=e,f=1,i=this[t+--n];for(;n>0&&(f*=256);)i+=this[t+--n]*f;return f*=128,i>=f&&(i-=Math.pow(2,8*e)),i},Buffer.prototype.readInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Buffer.prototype.readInt16LE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Buffer.prototype.readInt16BE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Buffer.prototype.readInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Buffer.prototype.readInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Buffer.prototype.readBigInt64LE=function(t){P(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||M(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)},Buffer.prototype.readBigInt64BE=function(t){P(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||M(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+r)},Buffer.prototype.readFloatLE=function(t,r){return t>>>=0,r||R(t,4,this.length),e.read(this,t,!0,23,4)},Buffer.prototype.readFloatBE=function(t,r){return t>>>=0,r||R(t,4,this.length),e.read(this,t,!1,23,4)},Buffer.prototype.readDoubleLE=function(t,r){return t>>>=0,r||R(t,8,this.length),e.read(this,t,!0,52,8)},Buffer.prototype.readDoubleBE=function(t,r){return t>>>=0,r||R(t,8,this.length),e.read(this,t,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e>>>=0,r>>>=0,!n){T(this,t,e,r,Math.pow(2,8*r)-1,0)}let f=1,i=0;for(this[e]=255&t;++i<r&&(f*=256);)this[e+i]=t/f&255;return e+r},Buffer.prototype.writeUintBE=Buffer.prototype.writeUIntBE=function(t,e,r,n){if(t=+t,e>>>=0,r>>>=0,!n){T(this,t,e,r,Math.pow(2,8*r)-1,0)}let f=r-1,i=1;for(this[e+f]=255&t;--f>=0&&(i*=256);)this[e+f]=t/i&255;return e+r},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,1,255,0),this[e]=255&t,e+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Buffer.prototype.writeBigUInt64LE=function(t,e=0){return L(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))},Buffer.prototype.writeBigUInt64BE=function(t,e=0){return O(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))},Buffer.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);T(this,t,e,r,n-1,-n)}let f=0,i=1,o=0;for(this[e]=255&t;++f<r&&(i*=256);)t<0&&0===o&&0!==this[e+f-1]&&(o=1),this[e+f]=(t/i>>0)-o&255;return e+r},Buffer.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);T(this,t,e,r,n-1,-n)}let f=r-1,i=1,o=0;for(this[e+f]=255&t;--f>=0&&(i*=256);)t<0&&0===o&&0!==this[e+f+1]&&(o=1),this[e+f]=(t/i>>0)-o&255;return e+r},Buffer.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},Buffer.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},Buffer.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},Buffer.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},Buffer.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Buffer.prototype.writeBigInt64LE=function(t,e=0){return L(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},Buffer.prototype.writeBigInt64BE=function(t,e=0){return O(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},Buffer.prototype.writeFloatLE=function(t,e,r){return _(this,t,e,!0,r)},Buffer.prototype.writeFloatBE=function(t,e,r){return _(this,t,e,!1,r)},Buffer.prototype.writeDoubleLE=function(t,e,r){return x(this,t,e,!0,r)},Buffer.prototype.writeDoubleBE=function(t,e,r){return x(this,t,e,!1,r)},Buffer.prototype.copy=function(t,e,r,n){if(!Buffer.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);const f=n-r;return this===t?this.copyWithin(e,r,n):Uint8Array.prototype.set.call(t,this.subarray(r,n),e),f},Buffer.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!Buffer.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){const e=t.charCodeAt(0);("utf8"===n&&e<128||"latin1"===n)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;let f;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(f=e;f<r;++f)this[f]=t;else{const i=Buffer.isBuffer(t)?t:Buffer.from(t,n),o=i.length;if(0===o)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(f=0;f<r-e;++f)this[f+e]=i[f%o]}return this};const $={};function N(t,e,r){$[t]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function C(t){let e="",r=t.length;const n="-"===t[0]?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function k(t,e,r,n,f,i){if(t>r||t<e){const n="bigint"==typeof e?"n":"";let f;throw f=i>3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new $.ERR_OUT_OF_RANGE("value",f,t)}!function(t,e,r){P(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||M(e,t.length-(r+1))}(n,f,i)}function P(t,e){if("number"!=typeof t)throw new $.ERR_INVALID_ARG_TYPE(e,"number",t)}function M(t,e,r){if(Math.floor(t)!==t)throw P(t,r),new $.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new $.ERR_BUFFER_OUT_OF_BOUNDS;throw new $.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}N("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),N("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),N("ERR_OUT_OF_RANGE",(function(t,e,r){let n=`The value of "${t}" is out of range.`,f=r;return Number.isInteger(r)&&Math.abs(r)>2**32?f=C(String(r)):"bigint"==typeof r&&(f=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(f=C(f)),f+="n"),n+=` It must be ${e}. Received ${f}`,n}),RangeError);const F=/[^+/0-9A-Za-z-_]/g;function j(t,e){let r;e=e||1/0;const n=t.length;let f=null;const i=[];for(let o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!f){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&i.push(239,191,189);continue}f=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),f=r;continue}r=65536+(f-55296<<10|r-56320)}else f&&(e-=3)>-1&&i.push(239,191,189);if(f=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function z(e){return t.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(F,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(e))}function D(t,e,r,n){let f;for(f=0;f<n&&!(f+r>=e.length||f>=t.length);++f)e[f+r]=t[f];return f}const G=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let f=0;f<16;++f)e[n+f]=t[r]+t[f]}return e}();export default{config,kMaxLength:2147483647,Buffer,SlowBuffer};
✄
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
export function read(t,o,a,e,h){let r,M;const p=8*h-e-1,n=(1<<p)-1,w=n>>1;let f=-7,l=a?h-1:0;const s=a?-1:1;let i=t[o+l];for(l+=s,r=i&(1<<-f)-1,i>>=-f,f+=p;f>0;)r=256*r+t[o+l],l+=s,f-=8;for(M=r&(1<<-f)-1,r>>=-f,f+=e;f>0;)M=256*M+t[o+l],l+=s,f-=8;if(0===r)r=1-w;else{if(r===n)return M?NaN:1/0*(i?-1:1);M+=Math.pow(2,e),r-=w}return(i?-1:1)*M*Math.pow(2,r-e)}export function write(t,o,a,e,h,r){let M,p,n,w=8*r-h-1;const f=(1<<w)-1,l=f>>1,s=23===h?Math.pow(2,-24)-Math.pow(2,-77):0;let i=e?0:r-1;const N=e?1:-1,c=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(p=isNaN(o)?1:0,M=f):(M=Math.floor(Math.log(o)/Math.LN2),o*(n=Math.pow(2,-M))<1&&(M--,n*=2),(o+=M+l>=1?s/n:s*Math.pow(2,1-l))*n>=2&&(M++,n/=2),M+l>=f?(p=0,M=f):M+l>=1?(p=(o*n-1)*Math.pow(2,h),M+=l):(p=o*Math.pow(2,l-1)*Math.pow(2,h),M=0));h>=8;)t[a+i]=255&p,i+=N,p/=256,h-=8;for(M=M<<h|p,w+=h;w>0;)t[a+i]=255&M,i+=N,M/=256,w-=8;t[a+i-N]|=128*c}
✄
import e from"./lib/api.js";import{getAndroidVersion as t,withAllArtThreadsSuspended as s,withRunnableArtThread as a,makeArtClassVisitor as r,makeArtClassLoaderVisitor as i,backtrace as o,deoptimizeEverything as n,deoptimizeBootImage as l,deoptimizeMethod as c}from"./lib/android.js";import h from"./lib/class-factory.js";import d from"./lib/class-model.js";import p from"./lib/env.js";import{initialize as m}from"./lib/types.js";import u from"./lib/vm.js";import{checkJniResult as C}from"./lib/result.js";const f=Process.pointerSize;function v(e,t){const s=e.use("android.os.Process");e.loader=t.getClassLoader(),s.myUid()===s.SYSTEM_UID.value?(e.cacheDir="/data/system",e.codeCacheDir="/data/dalvik-cache"):"getCodeCacheDir"in t?(e.cacheDir=t.getCacheDir().getCanonicalPath(),e.codeCacheDir=t.getCodeCacheDir().getCanonicalPath()):(e.cacheDir=t.getFilesDir().getCanonicalPath(),e.codeCacheDir=t.getCacheDir().getCanonicalPath())}function _(e,t){const s=e.use("java.io.File");e.loader=t.getClassLoader();const a=s.$new(t.getDataDir()).getCanonicalPath();e.cacheDir=a,e.codeCacheDir=a+"/cache"}const g=new class{ACC_PUBLIC=1;ACC_PRIVATE=2;ACC_PROTECTED=4;ACC_STATIC=8;ACC_FINAL=16;ACC_SYNCHRONIZED=32;ACC_BRIDGE=64;ACC_VARARGS=128;ACC_NATIVE=256;ACC_ABSTRACT=1024;ACC_STRICT=2048;ACC_SYNTHETIC=4096;constructor(){this.classFactory=null,this.ClassFactory=h,this.vm=null,this.api=null,this._initialized=!1,this._apiError=null,this._wakeupHandler=null,this._pollListener=null,this._pendingMainOps=[],this._pendingVmOps=[],this._cachedIsAppProcess=null;try{this._tryInitialize()}catch(e){}}_tryInitialize(){if(this._initialized)return!0;if(null!==this._apiError)throw this._apiError;let t;try{t=e(),this.api=t}catch(e){throw this._apiError=e,e}if(null===t)return!1;const s=new u(t);return this.vm=s,m(s),h._initialize(s,t),this.classFactory=new h,this._initialized=!0,!0}_dispose(){if(null===this.api)return;const{vm:e}=this;e.perform((e=>{h._disposeAll(e),p.dispose(e)})),Script.nextTick((()=>{u.dispose(e)}))}get available(){return this._tryInitialize()}get androidVersion(){return t()}synchronized(e,t){const{$h:s=e}=e;if(!(s instanceof NativePointer))throw new Error("Java.synchronized: the first argument `obj` must be either a pointer or a Java instance");const a=this.vm.getEnv();C("VM::MonitorEnter",a.monitorEnter(s));try{t()}finally{a.monitorExit(s)}}enumerateLoadedClasses(e){this._checkAvailable();const{flavor:t}=this.api;"jvm"===t?this._enumerateLoadedClassesJvm(e):"art"===t?this._enumerateLoadedClassesArt(e):this._enumerateLoadedClassesDalvik(e)}enumerateLoadedClassesSync(){const e=[];return this.enumerateLoadedClasses({onMatch(t){e.push(t)},onComplete(){}}),e}enumerateClassLoaders(e){this._checkAvailable();const{flavor:t}=this.api;if("jvm"===t)this._enumerateClassLoadersJvm(e);else{if("art"!==t)throw new Error("Enumerating class loaders is not supported on Dalvik");this._enumerateClassLoadersArt(e)}}enumerateClassLoadersSync(){const e=[];return this.enumerateClassLoaders({onMatch(t){e.push(t)},onComplete(){}}),e}_enumerateLoadedClassesJvm(e){const{api:t,vm:s}=this,{jvmti:a}=t,r=s.getEnv(),i=Memory.alloc(4),o=Memory.alloc(f);a.getLoadedClasses(i,o);const n=i.readS32(),l=o.readPointer(),c=[];for(let e=0;e!==n;e++)c.push(l.add(e*f).readPointer());a.deallocate(l);try{for(const t of c){const s=r.getClassName(t);e.onMatch(s,t)}e.onComplete()}finally{c.forEach((e=>{r.deleteLocalRef(e)}))}}_enumerateClassLoadersJvm(e){this.choose("java.lang.ClassLoader",e)}_enumerateLoadedClassesArt(e){const{vm:t,api:s}=this,i=t.getEnv(),o=s["art::JavaVMExt::AddGlobalRef"],{vm:n}=s;a(t,i,(t=>{const a=r((s=>{const a=o(n,t,s);try{const t=i.getClassName(a);e.onMatch(t,a)}finally{i.deleteGlobalRef(a)}return!0}));s["art::ClassLinker::VisitClasses"](s.artClassLinker.address,a)})),e.onComplete()}_enumerateClassLoadersArt(e){const{classFactory:t,vm:r,api:o}=this,n=r.getEnv(),l=o["art::ClassLinker::VisitClassLoaders"];if(void 0===l)throw new Error("This API is only available on Android >= 7.0");const c=t.use("java.lang.ClassLoader"),h=[],d=o["art::JavaVMExt::AddGlobalRef"],{vm:p}=o;a(r,n,(e=>{const t=i((t=>(h.push(d(p,e,t)),!0)));s((()=>{l(o.artClassLinker.address,t)}))}));try{h.forEach((s=>{const a=t.cast(s,c);e.onMatch(a)}))}finally{h.forEach((e=>{n.deleteGlobalRef(e)}))}e.onComplete()}_enumerateLoadedClassesDalvik(e){const{api:t}=this,s=ptr("0xcbcacccd"),a=t.gDvm.add(172).readPointer(),r=a.readS32(),i=a.add(12).readPointer(),o=8*r;for(let t=0;t<o;t+=8){const a=i.add(t).add(4).readPointer();if(a.isNull()||a.equals(s))continue;const r=a.add(24).readPointer().readUtf8String();if(r.startsWith("L")){const t=r.substring(1,r.length-1).replace(/\//g,".");e.onMatch(t)}}e.onComplete()}enumerateMethods(e){const{classFactory:t}=this,s=this.vm.getEnv(),a=t.use("java.lang.ClassLoader");return d.enumerateMethods(e,this.api,s).map((e=>{const r=e.loader;return e.loader=null!==r?t.wrap(r,a,s):null,e}))}scheduleOnMainThread(e){this.performNow((()=>{this._pendingMainOps.push(e);let{_wakeupHandler:t}=this;if(null===t){const{classFactory:e}=this,s=e.use("android.os.Handler"),a=e.use("android.os.Looper");t=s.$new(a.getMainLooper()),this._wakeupHandler=t}null===this._pollListener&&(this._pollListener=Interceptor.attach(Process.getModuleByName("libc.so").getExportByName("epoll_wait"),this._makePollHook()),Interceptor.flush()),t.sendEmptyMessage(1)}))}_makePollHook(){const e=Process.id,{_pendingMainOps:t}=this;return function(){if(this.threadId!==e)return;let s;for(;void 0!==(s=t.shift());)try{s()}catch(e){Script.nextTick((()=>{throw e}))}}}perform(e){if(this._checkAvailable(),this._isAppProcess()&&null===this.classFactory.loader)this._pendingVmOps.push(e),1===this._pendingVmOps.length&&this._performPendingVmOpsWhenReady();else try{this.vm.perform(e)}catch(e){Script.nextTick((()=>{throw e}))}}performNow(e){return this._checkAvailable(),this.vm.perform((()=>{const{classFactory:t}=this;if(this._isAppProcess()&&null===t.loader){const e=t.use("android.app.ActivityThread").currentApplication();null!==e&&v(t,e)}return e()}))}_performPendingVmOpsWhenReady(){this.vm.perform((()=>{const{classFactory:e}=this,t=e.use("android.app.ActivityThread"),s=t.currentApplication();if(null!==s)return v(e,s),void this._performPendingVmOps();const a=this;let r=!1,i="early";const o=t.handleBindApplication;o.implementation=function(t){if(null!==t.instrumentationName.value){i="late";const t=e.use("android.app.LoadedApk").makeApplication;t.implementation=function(s,i){return r||(r=!0,_(e,this),a._performPendingVmOps()),t.apply(this,arguments)}}o.apply(this,arguments)};const n=t.getPackageInfo.overloads.map((e=>[e.argumentTypes.length,e])).sort((([e],[t])=>t-e)).map((([e,t])=>t))[0];n.implementation=function(...t){const s=n.call(this,...t);return r||"early"!==i||(r=!0,_(e,s),a._performPendingVmOps()),s}}))}_performPendingVmOps(){const{vm:e,_pendingVmOps:t}=this;let s;for(;void 0!==(s=t.shift());)try{e.perform(s)}catch(e){Script.nextTick((()=>{throw e}))}}use(e,t){return this.classFactory.use(e,t)}openClassFile(e){return this.classFactory.openClassFile(e)}choose(e,t){this.classFactory.choose(e,t)}retain(e){return this.classFactory.retain(e)}cast(e,t){return this.classFactory.cast(e,t)}array(e,t){return this.classFactory.array(e,t)}backtrace(e){return o(this.vm,e)}isMainThread(){const e=this.classFactory.use("android.os.Looper"),t=e.getMainLooper(),s=e.myLooper();return null!==s&&t.$isSameObject(s)}registerClass(e){return this.classFactory.registerClass(e)}deoptimizeEverything(){const{vm:e}=this;return n(e,e.getEnv())}deoptimizeBootImage(){const{vm:e}=this;return l(e,e.getEnv())}deoptimizeMethod(e){const{vm:t}=this;return c(t,t.getEnv(),e)}_checkAvailable(){if(!this.available)throw new Error("Java API not available")}_isAppProcess(){let e=this._cachedIsAppProcess;if(null===e){if("jvm"===this.api.flavor)return e=!1,this._cachedIsAppProcess=e,e;const t=new NativeFunction(Module.getGlobalExportByName("readlink"),"pointer",["pointer","pointer","pointer"],{exceptions:"propagate"}),s=Memory.allocUtf8String("/proc/self/exe"),a=1024,r=Memory.alloc(a),i=t(s,r,ptr(a)).toInt32();if(-1!==i){const t=r.readUtf8String(i);e=/^\/system\/bin\/app_process/.test(t)}else e=!0;this._cachedIsAppProcess=e}return e}};Script.bindWeak(g,(()=>{g._dispose()}));export default g;
✄
const{pageSize:e,pointerSize:s}=Process;class t{constructor(s){this.sliceSize=s,this.slicesPerPage=e/s,this.pages=[],this.free=[]}allocateSlice(s,t){const i=void 0===s.near,r=1===t;if(i&&r){const e=this.free.pop();if(void 0!==e)return e}else if(t<e){const{free:e}=this,c=e.length,n=r?null:ptr(t-1);for(let t=0;t!==c;t++){const c=e[t],l=i||this._isSliceNear(c,s),o=r||c.and(n).isNull();if(l&&o)return e.splice(t,1)[0]}}return this._allocatePage(s)}_allocatePage(s){const t=Memory.alloc(e,s),{sliceSize:i,slicesPerPage:r}=this;for(let e=1;e!==r;e++){const s=t.add(e*i);this.free.push(s)}return this.pages.push(t),t}_isSliceNear(e,s){const t=e.add(this.sliceSize),{near:r,maxDistance:c}=s,n=i(r.sub(e)),l=i(r.sub(t));return n.compare(c)<=0&&l.compare(c)<=0}freeSlice(e){this.free.push(e)}}function i(e){const t=4===s?31:63,i=ptr(1).shl(t).not();return e.and(i)}export default function r(e){return new t(e)}
✄
import e from"./alloc.js";import{jvmtiVersion as t,jvmtiCapabilities as n,EnvJvmti as r}from"./jvmti.js";import{parseInstructionsAt as o}from"./machine-code.js";import a from"./memoize.js";import{checkJniResult as i,JNI_OK as s}from"./result.js";import c from"./vm.js";const d=Process.pointerSize,{readU32:l,readPointer:u,writeU32:p,writePointer:_}=NativePointer.prototype,m=ptr(1).not(),h=17*d,g=18*d;export const DVM_JNI_ENV_OFFSET_SELF=12;const f=3*d,b=3*d,v=a((function(e){const t=e.vm,n=e.artRuntime,r=4===d?200:384,a=r+100*d,i=getAndroidApiLevel(),s=N(),{isApiLevel34OrApexEquivalent:c}=e;let l=null;for(let e=r;e!==a;e+=d){if(n.add(e).readPointer().equals(t)){let t,r=null;i>=33||"Tiramisu"===s||c?(t=[e-4*d],r=e-d):i>=30||"R"===s?(t=[e-3*d,e-4*d],r=e-d):t=i>=29?[e-2*d]:i>=27?[e-f-3*d]:[e-f-2*d];for(const e of t){const t=e-d,o=t-d;let a;a=c?o-9*d:i>=24?o-8*d:i>=23?o-7*d:o-4*d;const s={offset:{heap:a,threadList:o,internTable:t,classLinker:e,jniIdManager:r}};if(null!==Q(n,s)){l=s;break}}break}}if(null===l)throw new Error("Unable to determine Runtime field offsets");const u=getArtApexVersion()>=36e7;return l.offset.instrumentation=u?function(e){const t=e["art::Runtime::DeoptimizeBootImage"];if(void 0===t)return null;return o(t,q[Process.arch],{limit:30})}(e):function(e){const t=e["art::Runtime::DeoptimizeBootImage"];if(void 0===t)return null;return o(t,G[Process.arch],{limit:30})}(e),l.offset.jniIdsIndirection=function(e){const t=e.find("_ZN3art7Runtime12SetJniIdTypeENS_9JniIdTypeE");if(null===t)return null;const n=o(t,H[Process.arch],{limit:20});if(null===n)throw new Error("Unable to determine Runtime.jni_ids_indirection_ offset");return n}(e),l})),k=a((function(){const e={"4-21":136,"4-22":136,"4-23":172,"4-24":196,"4-25":196,"4-26":196,"4-27":196,"4-28":212,"4-29":172,"4-30":180,"4-31":180,"8-21":224,"8-22":224,"8-23":296,"8-24":344,"8-25":344,"8-26":352,"8-27":352,"8-28":392,"8-29":328,"8-30":336,"8-31":336}[`${d}-${getAndroidApiLevel()}`];if(void 0===e)throw new Error("Unable to determine Instrumentation field offsets");return{offset:{forcedInterpretOnly:4,deoptimizationEnabled:e}}}));export const getArtMethodSpec=a((function(e){const t=getApi();let n;return e.perform((e=>{const r=e.findClass("android/os/Process"),o=fe(e.getStaticMethodId(r,"getElapsedCpuTime","()J"));e.deleteLocalRef(r);const a=Process.getModuleByName("libandroid_runtime.so"),i=a.base,s=i.add(a.size),c=getAndroidApiLevel(),l=c<=21?8:d;let u=null,p=null,_=2;for(let e=0;64!==e&&0!==_;e+=4){const t=o.add(e);if(null===u){const n=t.readPointer();n.compare(i)>=0&&n.compare(s)<0&&(u=e,_--)}if(null===p){281==(2950692863&t.readU32())&&(p=e,_--)}}if(0!==_)throw new Error("Unable to determine ArtMethod field offsets");const m=u+l;n={size:c<=21?m+32:m+d,offset:{jniCode:u,quickCode:m,accessFlags:p}},"artInterpreterToCompiledCodeBridge"in t&&(n.offset.interpreterCode=u-l)})),n}));export const getArtThreadSpec=a((function(e){const t=getAndroidApiLevel();let n;return e.perform((e=>{const r=getArtThreadFromEnv(e),o=e.handle;let a=null,i=null,s=null,c=null,l=null,u=null;for(let e=144;256!==e;e+=d){if(r.add(e).readPointer().equals(o)){i=e-6*d,l=e-4*d,u=e+2*d,t<=22&&(i-=d,a=i-d-72-12,s=e+6*d,l-=d,u-=d),c=e+9*d,t<=22&&(c+=2*d+4,8===d&&(c+=4)),t>=23&&(c+=d);break}}if(null===c)throw new Error("Unable to determine ArtThread field offsets");n={offset:{isExceptionReportedToInstrumentation:a,exception:i,throwLocation:s,topHandleScope:c,managedStack:l,self:u}}})),n}));const S=a((function(){return getAndroidApiLevel()>=23?{offset:{topQuickFrame:0,link:d}}:{offset:{topQuickFrame:2*d,link:0}}})),E=a((function(e,t){const n=new NativeCallback(re,"void",["pointer"]);return Le(e,t,n)}));export const getAndroidVersion=a((function(){return ne("ro.build.version.release")}));const N=a((function(){return ne("ro.build.version.codename")}));export const getAndroidApiLevel=a((function(){return parseInt(ne("ro.build.version.sdk"),10)}));export const getArtApexVersion=a((function(){try{const e=File.readAllText("/proc/self/mountinfo");let t=null;const n=new Map;for(const r of e.trimEnd().split("\n")){const e=r.split(" "),o=e[4];if(!o.startsWith("/apex/com.android.art"))continue;const a=e[10];o.includes("@")?n.set(a,o.split("@")[1]):t=a}const r=n.get(t);return void 0!==r?parseInt(r):ee()}catch{return ee()}}));const A=a((function(e){let t=NULL;switch(Process.arch){case"ia32":t=de(32,(t=>{t.putMovRegRegOffsetPtr("ecx","esp",4),t.putMovRegRegOffsetPtr("edx","esp",8),t.putCallAddressWithArguments(e,["ecx","edx"]),t.putMovRegReg("esp","ebp"),t.putPopReg("ebp"),t.putRet()}));break;case"x64":t=de(32,(t=>{t.putPushReg("rdi"),t.putCallAddressWithArguments(e,["rsi"]),t.putPopReg("rdi"),t.putMovRegPtrReg("rdi","rax"),t.putMovRegOffsetPtrReg("rdi",8,"edx"),t.putRet()}));break;case"arm":t=de(16,(t=>{t.putCallAddressWithArguments(e,["r0","r1"]),t.putPopRegs(["r0","lr"]),t.putMovRegReg("pc","lr")}));break;case"arm64":t=de(64,(t=>{t.putPushRegReg("x0","lr"),t.putCallAddressWithArguments(e,["x1"]),t.putPopRegReg("x2","lr"),t.putStrRegRegOffset("x0","x2",0),t.putStrRegRegOffset("w1","x2",8),t.putRet()}))}return new NativeFunction(t,"void",["pointer","pointer"],x)})),R="ia32"===Process.arch?function(e,t){const n=new NativeFunction(e,"void",["pointer"].concat(t),x);return function(){const e=Memory.alloc(d);return n(e,...arguments),e.readPointer()}}:function(e,t){return new NativeFunction(e,"pointer",t,x)},x={exceptions:"propagate"},w={};let P=null,M=null,y=null,C=null;const I=[],L=new Map,T=[];let j=null,z=0,O=!1,F=!1,D=null;const Z=[];let V=null,J=null;export function getApi(){return null===P&&(P=function(){const e=Process.enumerateModules().filter((e=>/^lib(art|dvm).so$/.test(e.name))).filter((e=>!/\/system\/fake-libs/.test(e.path)));if(0===e.length)return null;const t=e[0],n=-1!==t.name.indexOf("art")?"art":"dalvik",r="art"===n,o={module:t,find(e){const{module:t}=this;let n=t.findExportByName(e);return null===n&&(n=t.findSymbolByName(e)),n},flavor:n,addLocalReference:null};o.isApiLevel34OrApexEquivalent=r&&(null!==o.find("_ZN3art7AppInfo29GetPrimaryApkReferenceProfileEv")||null!==o.find("_ZN3art6Thread15RunFlipFunctionEPS0_"));const a=r?{functions:{JNI_GetCreatedJavaVMs:["JNI_GetCreatedJavaVMs","int",["pointer","int","pointer"]],artInterpreterToCompiledCodeBridge:function(e){this.artInterpreterToCompiledCodeBridge=e},_ZN3art9JavaVMExt12AddGlobalRefEPNS_6ThreadENS_6ObjPtrINS_6mirror6ObjectEEE:["art::JavaVMExt::AddGlobalRef","pointer",["pointer","pointer","pointer"]],_ZN3art9JavaVMExt12AddGlobalRefEPNS_6ThreadEPNS_6mirror6ObjectE:["art::JavaVMExt::AddGlobalRef","pointer",["pointer","pointer","pointer"]],_ZN3art17ReaderWriterMutex13ExclusiveLockEPNS_6ThreadE:["art::ReaderWriterMutex::ExclusiveLock","void",["pointer","pointer"]],_ZN3art17ReaderWriterMutex15ExclusiveUnlockEPNS_6ThreadE:["art::ReaderWriterMutex::ExclusiveUnlock","void",["pointer","pointer"]],_ZN3art22IndirectReferenceTable3AddEjPNS_6mirror6ObjectE:function(e){this["art::IndirectReferenceTable::Add"]=new NativeFunction(e,"pointer",["pointer","uint","pointer"],x)},_ZN3art22IndirectReferenceTable3AddENS_15IRTSegmentStateENS_6ObjPtrINS_6mirror6ObjectEEE:function(e){this["art::IndirectReferenceTable::Add"]=new NativeFunction(e,"pointer",["pointer","uint","pointer"],x)},_ZN3art9JavaVMExt12DecodeGlobalEPv:function(e){let t;t=getAndroidApiLevel()>=26?R(e,["pointer","pointer"]):new NativeFunction(e,"pointer",["pointer","pointer"],x),this["art::JavaVMExt::DecodeGlobal"]=function(e,n,r){return t(e,r)}},_ZN3art9JavaVMExt12DecodeGlobalEPNS_6ThreadEPv:["art::JavaVMExt::DecodeGlobal","pointer",["pointer","pointer","pointer"]],_ZNK3art6Thread19DecodeGlobalJObjectEP8_jobject:["art::Thread::DecodeJObject","pointer",["pointer","pointer"]],_ZNK3art6Thread13DecodeJObjectEP8_jobject:["art::Thread::DecodeJObject","pointer",["pointer","pointer"]],_ZN3art10ThreadList10SuspendAllEPKcb:["art::ThreadList::SuspendAll","void",["pointer","pointer","bool"]],_ZN3art10ThreadList10SuspendAllEv:function(e){const t=new NativeFunction(e,"void",["pointer"],x);this["art::ThreadList::SuspendAll"]=function(e,n,r){return t(e)}},_ZN3art10ThreadList9ResumeAllEv:["art::ThreadList::ResumeAll","void",["pointer"]],_ZN3art11ClassLinker12VisitClassesEPNS_12ClassVisitorE:["art::ClassLinker::VisitClasses","void",["pointer","pointer"]],_ZN3art11ClassLinker12VisitClassesEPFbPNS_6mirror5ClassEPvES4_:function(e){const t=new NativeFunction(e,"void",["pointer","pointer","pointer"],x);this["art::ClassLinker::VisitClasses"]=function(e,n){t(e,n,NULL)}},_ZNK3art11ClassLinker17VisitClassLoadersEPNS_18ClassLoaderVisitorE:["art::ClassLinker::VisitClassLoaders","void",["pointer","pointer"]],_ZN3art2gc4Heap12VisitObjectsEPFvPNS_6mirror6ObjectEPvES5_:["art::gc::Heap::VisitObjects","void",["pointer","pointer","pointer"]],_ZN3art2gc4Heap12GetInstancesERNS_24VariableSizedHandleScopeENS_6HandleINS_6mirror5ClassEEEiRNSt3__16vectorINS4_INS5_6ObjectEEENS8_9allocatorISB_EEEE:["art::gc::Heap::GetInstances","void",["pointer","pointer","pointer","int","pointer"]],_ZN3art2gc4Heap12GetInstancesERNS_24VariableSizedHandleScopeENS_6HandleINS_6mirror5ClassEEEbiRNSt3__16vectorINS4_INS5_6ObjectEEENS8_9allocatorISB_EEEE:function(e){const t=new NativeFunction(e,"void",["pointer","pointer","pointer","bool","int","pointer"],x);this["art::gc::Heap::GetInstances"]=function(e,n,r,o,a){t(e,n,r,0,o,a)}},_ZN3art12StackVisitorC2EPNS_6ThreadEPNS_7ContextENS0_13StackWalkKindEjb:["art::StackVisitor::StackVisitor","void",["pointer","pointer","pointer","uint","uint","bool"]],_ZN3art12StackVisitorC2EPNS_6ThreadEPNS_7ContextENS0_13StackWalkKindEmb:["art::StackVisitor::StackVisitor","void",["pointer","pointer","pointer","uint","size_t","bool"]],_ZN3art12StackVisitor9WalkStackILNS0_16CountTransitionsE0EEEvb:["art::StackVisitor::WalkStack","void",["pointer","bool"]],_ZNK3art12StackVisitor9GetMethodEv:["art::StackVisitor::GetMethod","pointer",["pointer"]],_ZNK3art12StackVisitor16DescribeLocationEv:function(e){this["art::StackVisitor::DescribeLocation"]=Oe(e,["pointer"])},_ZNK3art12StackVisitor24GetCurrentQuickFrameInfoEv:function(e){var t;this["art::StackVisitor::GetCurrentQuickFrameInfo"]=(t=e,function(e){const n=Memory.alloc(12);return A(t)(n,e),{frameSizeInBytes:n.readU32(),coreSpillMask:n.add(4).readU32(),fpSpillMask:n.add(8).readU32()}})},_ZN3art7Context6CreateEv:["art::Context::Create","pointer",[]],_ZN3art6Thread18GetLongJumpContextEv:["art::Thread::GetLongJumpContext","pointer",["pointer"]],_ZN3art6mirror5Class13GetDescriptorEPNSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEE:function(e){this["art::mirror::Class::GetDescriptor"]=e},_ZN3art6mirror5Class11GetLocationEv:function(e){this["art::mirror::Class::GetLocation"]=Oe(e,["pointer"])},_ZN3art9ArtMethod12PrettyMethodEb:function(e){this["art::ArtMethod::PrettyMethod"]=Oe(e,["pointer","bool"])},_ZN3art12PrettyMethodEPNS_9ArtMethodEb:function(e){this["art::ArtMethod::PrettyMethodNullSafe"]=Oe(e,["pointer","bool"])},_ZN3art6Thread14CurrentFromGdbEv:["art::Thread::CurrentFromGdb","pointer",[]],_ZN3art6mirror6Object5CloneEPNS_6ThreadE:function(e){this["art::mirror::Object::Clone"]=new NativeFunction(e,"pointer",["pointer","pointer"],x)},_ZN3art6mirror6Object5CloneEPNS_6ThreadEm:function(e){const t=new NativeFunction(e,"pointer",["pointer","pointer","pointer"],x);this["art::mirror::Object::Clone"]=function(e,n){const r=NULL;return t(e,n,r)}},_ZN3art6mirror6Object5CloneEPNS_6ThreadEj:function(e){const t=new NativeFunction(e,"pointer",["pointer","pointer","uint"],x);this["art::mirror::Object::Clone"]=function(e,n){return t(e,n,0)}},_ZN3art3Dbg14SetJdwpAllowedEb:["art::Dbg::SetJdwpAllowed","void",["bool"]],_ZN3art3Dbg13ConfigureJdwpERKNS_4JDWP11JdwpOptionsE:["art::Dbg::ConfigureJdwp","void",["pointer"]],_ZN3art31InternalDebuggerControlCallback13StartDebuggerEv:["art::InternalDebuggerControlCallback::StartDebugger","void",["pointer"]],_ZN3art3Dbg9StartJdwpEv:["art::Dbg::StartJdwp","void",[]],_ZN3art3Dbg8GoActiveEv:["art::Dbg::GoActive","void",[]],_ZN3art3Dbg21RequestDeoptimizationERKNS_21DeoptimizationRequestE:["art::Dbg::RequestDeoptimization","void",["pointer"]],_ZN3art3Dbg20ManageDeoptimizationEv:["art::Dbg::ManageDeoptimization","void",[]],_ZN3art15instrumentation15Instrumentation20EnableDeoptimizationEv:["art::Instrumentation::EnableDeoptimization","void",["pointer"]],_ZN3art15instrumentation15Instrumentation20DeoptimizeEverythingEPKc:["art::Instrumentation::DeoptimizeEverything","void",["pointer","pointer"]],_ZN3art15instrumentation15Instrumentation20DeoptimizeEverythingEv:function(e){const t=new NativeFunction(e,"void",["pointer"],x);this["art::Instrumentation::DeoptimizeEverything"]=function(e,n){t(e)}},_ZN3art7Runtime19DeoptimizeBootImageEv:["art::Runtime::DeoptimizeBootImage","void",["pointer"]],_ZN3art15instrumentation15Instrumentation10DeoptimizeEPNS_9ArtMethodE:["art::Instrumentation::Deoptimize","void",["pointer","pointer"]],_ZN3art3jni12JniIdManager14DecodeMethodIdEP10_jmethodID:["art::jni::JniIdManager::DecodeMethodId","pointer",["pointer","pointer"]],_ZN3art3jni12JniIdManager13DecodeFieldIdEP9_jfieldID:["art::jni::JniIdManager::DecodeFieldId","pointer",["pointer","pointer"]],_ZN3art11interpreter18GetNterpEntryPointEv:["art::interpreter::GetNterpEntryPoint","pointer",[]],_ZN3art7Monitor17TranslateLocationEPNS_9ArtMethodEjPPKcPi:["art::Monitor::TranslateLocation","void",["pointer","uint32","pointer","pointer"]]},variables:{_ZN3art3Dbg9gRegistryE:function(e){this.isJdwpStarted=()=>!e.readPointer().isNull()},_ZN3art3Dbg15gDebuggerActiveE:function(e){this.isDebuggerActive=()=>!!e.readU8()}},optionals:new Set(["artInterpreterToCompiledCodeBridge","_ZN3art9JavaVMExt12AddGlobalRefEPNS_6ThreadENS_6ObjPtrINS_6mirror6ObjectEEE","_ZN3art9JavaVMExt12AddGlobalRefEPNS_6ThreadEPNS_6mirror6ObjectE","_ZN3art9JavaVMExt12DecodeGlobalEPv","_ZN3art9JavaVMExt12DecodeGlobalEPNS_6ThreadEPv","_ZNK3art6Thread19DecodeGlobalJObjectEP8_jobject","_ZNK3art6Thread13DecodeJObjectEP8_jobject","_ZN3art10ThreadList10SuspendAllEPKcb","_ZN3art10ThreadList10SuspendAllEv","_ZN3art11ClassLinker12VisitClassesEPNS_12ClassVisitorE","_ZN3art11ClassLinker12VisitClassesEPFbPNS_6mirror5ClassEPvES4_","_ZNK3art11ClassLinker17VisitClassLoadersEPNS_18ClassLoaderVisitorE","_ZN3art6mirror6Object5CloneEPNS_6ThreadE","_ZN3art6mirror6Object5CloneEPNS_6ThreadEm","_ZN3art6mirror6Object5CloneEPNS_6ThreadEj","_ZN3art22IndirectReferenceTable3AddEjPNS_6mirror6ObjectE","_ZN3art22IndirectReferenceTable3AddENS_15IRTSegmentStateENS_6ObjPtrINS_6mirror6ObjectEEE","_ZN3art2gc4Heap12VisitObjectsEPFvPNS_6mirror6ObjectEPvES5_","_ZN3art2gc4Heap12GetInstancesERNS_24VariableSizedHandleScopeENS_6HandleINS_6mirror5ClassEEEiRNSt3__16vectorINS4_INS5_6ObjectEEENS8_9allocatorISB_EEEE","_ZN3art2gc4Heap12GetInstancesERNS_24VariableSizedHandleScopeENS_6HandleINS_6mirror5ClassEEEbiRNSt3__16vectorINS4_INS5_6ObjectEEENS8_9allocatorISB_EEEE","_ZN3art12StackVisitorC2EPNS_6ThreadEPNS_7ContextENS0_13StackWalkKindEjb","_ZN3art12StackVisitorC2EPNS_6ThreadEPNS_7ContextENS0_13StackWalkKindEmb","_ZN3art12StackVisitor9WalkStackILNS0_16CountTransitionsE0EEEvb","_ZNK3art12StackVisitor9GetMethodEv","_ZNK3art12StackVisitor16DescribeLocationEv","_ZNK3art12StackVisitor24GetCurrentQuickFrameInfoEv","_ZN3art7Context6CreateEv","_ZN3art6Thread18GetLongJumpContextEv","_ZN3art6mirror5Class13GetDescriptorEPNSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEE","_ZN3art6mirror5Class11GetLocationEv","_ZN3art9ArtMethod12PrettyMethodEb","_ZN3art12PrettyMethodEPNS_9ArtMethodEb","_ZN3art3Dbg13ConfigureJdwpERKNS_4JDWP11JdwpOptionsE","_ZN3art31InternalDebuggerControlCallback13StartDebuggerEv","_ZN3art3Dbg15gDebuggerActiveE","_ZN3art15instrumentation15Instrumentation20EnableDeoptimizationEv","_ZN3art15instrumentation15Instrumentation20DeoptimizeEverythingEPKc","_ZN3art15instrumentation15Instrumentation20DeoptimizeEverythingEv","_ZN3art7Runtime19DeoptimizeBootImageEv","_ZN3art15instrumentation15Instrumentation10DeoptimizeEPNS_9ArtMethodE","_ZN3art3Dbg9StartJdwpEv","_ZN3art3Dbg8GoActiveEv","_ZN3art3Dbg21RequestDeoptimizationERKNS_21DeoptimizationRequestE","_ZN3art3Dbg20ManageDeoptimizationEv","_ZN3art3Dbg9gRegistryE","_ZN3art3jni12JniIdManager14DecodeMethodIdEP10_jmethodID","_ZN3art3jni12JniIdManager13DecodeFieldIdEP9_jfieldID","_ZN3art11interpreter18GetNterpEntryPointEv","_ZN3art7Monitor17TranslateLocationEPNS_9ArtMethodEjPPKcPi"])}:{functions:{_Z20dvmDecodeIndirectRefP6ThreadP8_jobject:["dvmDecodeIndirectRef","pointer",["pointer","pointer"]],_Z15dvmUseJNIBridgeP6MethodPv:["dvmUseJNIBridge","void",["pointer","pointer"]],_Z20dvmHeapSourceGetBasev:["dvmHeapSourceGetBase","pointer",[]],_Z21dvmHeapSourceGetLimitv:["dvmHeapSourceGetLimit","pointer",[]],_Z16dvmIsValidObjectPK6Object:["dvmIsValidObject","uint8",["pointer"]],JNI_GetCreatedJavaVMs:["JNI_GetCreatedJavaVMs","int",["pointer","int","pointer"]]},variables:{gDvmJni:function(e){this.gDvmJni=e},gDvm:function(e){this.gDvm=e}}},{functions:s={},variables:l={},optionals:u=new Set}=a,p=[];for(const[e,t]of Object.entries(s)){const n=o.find(e);null!==n?"function"==typeof t?t.call(o,n):o[t[0]]=new NativeFunction(n,t[1],t[2],x):u.has(e)||p.push(e)}for(const[e,t]of Object.entries(l)){const n=o.find(e);null!==n?t.call(o,n):u.has(e)||p.push(e)}if(p.length>0)throw new Error("Java API only partially available; please file a bug. Missing: "+p.join(", "));const _=Memory.alloc(d),m=Memory.alloc(4);if(i("JNI_GetCreatedJavaVMs",o.JNI_GetCreatedJavaVMs(_,1,m)),0===m.readInt())return null;if(o.vm=_.readPointer(),r){const e=getAndroidApiLevel();let t;t=e>=27?33554432:e>=24?16777216:0,o.kAccCompileDontBother=t;const n=o.vm.add(d).readPointer();o.artRuntime=n;const r=v(o),a=r.offset,i=a.instrumentation;o.artInstrumentation=null!==i?n.add(i):null;getArtApexVersion()>=36e7&&null!=o.artInstrumentation&&(o.artInstrumentation=o.artInstrumentation.readPointer()),o.artHeap=n.add(a.heap).readPointer(),o.artThreadList=n.add(a.threadList).readPointer();const s=n.add(a.classLinker).readPointer(),l=function(e,t){const n=Q(e,t);if(null===n)throw new Error("Unable to determine ClassLinker field offsets");return n}(n,r).offset,u=s.add(l.quickResolutionTrampoline).readPointer(),p=s.add(l.quickImtConflictTrampoline).readPointer(),_=s.add(l.quickGenericJniTrampoline).readPointer(),m=s.add(l.quickToInterpreterBridgeTrampoline).readPointer();o.artClassLinker={address:s,quickResolutionTrampoline:u,quickImtConflictTrampoline:p,quickGenericJniTrampoline:_,quickToInterpreterBridgeTrampoline:m};const h=new c(o);o.artQuickGenericJniTrampoline=X(_,h),o.artQuickToInterpreterBridge=X(m,h),o.artQuickResolutionTrampoline=X(u,h),void 0===o["art::JavaVMExt::AddGlobalRef"]&&(o["art::JavaVMExt::AddGlobalRef"]=function(e){const t=4===d?{globalsLock:32,globals:72}:{globalsLock:64,globals:112},n=e.vm.add(t.globalsLock),r=e.vm.add(t.globals),o=e["art::IndirectReferenceTable::Add"],a=e["art::ReaderWriterMutex::ExclusiveLock"],i=e["art::ReaderWriterMutex::ExclusiveUnlock"],s=0;return function(e,t,c){a(n,t);try{return o(r,s,c)}finally{i(n,t)}}}(o)),void 0===o["art::JavaVMExt::DecodeGlobal"]&&(o["art::JavaVMExt::DecodeGlobal"]=function(e){const t=e["art::Thread::DecodeJObject"];if(void 0===t)throw new Error("art::Thread::DecodeJObject is not available; please file a bug");return function(e,n,r){return t(n,r)}}(o)),void 0===o["art::ArtMethod::PrettyMethod"]&&(o["art::ArtMethod::PrettyMethod"]=o["art::ArtMethod::PrettyMethodNullSafe"]),void 0!==o["art::interpreter::GetNterpEntryPoint"]?o.artNterpEntryPoint=o["art::interpreter::GetNterpEntryPoint"]():o.artNterpEntryPoint=o.find("ExecuteNterpImpl"),C=function(e,t){const n=getArtThreadSpec(t).offset,r=S().offset,o=`\n#include <gum/guminterceptor.h>\n\nextern GMutex lock;\nextern GHashTable * methods;\nextern GHashTable * replacements;\nextern gpointer last_seen_art_method;\n\nextern gpointer get_oat_quick_method_header_impl (gpointer method, gpointer pc);\n\nvoid\ninit (void)\n{\n  g_mutex_init (&lock);\n  methods = g_hash_table_new_full (NULL, NULL, NULL, NULL);\n  replacements = g_hash_table_new_full (NULL, NULL, NULL, NULL);\n}\n\nvoid\nfinalize (void)\n{\n  g_hash_table_unref (replacements);\n  g_hash_table_unref (methods);\n  g_mutex_clear (&lock);\n}\n\ngboolean\nis_replacement_method (gpointer method)\n{\n  gboolean is_replacement;\n\n  g_mutex_lock (&lock);\n\n  is_replacement = g_hash_table_contains (replacements, method);\n\n  g_mutex_unlock (&lock);\n\n  return is_replacement;\n}\n\ngpointer\nget_replacement_method (gpointer original_method)\n{\n  gpointer replacement_method;\n\n  g_mutex_lock (&lock);\n\n  replacement_method = g_hash_table_lookup (methods, original_method);\n\n  g_mutex_unlock (&lock);\n\n  return replacement_method;\n}\n\nvoid\nset_replacement_method (gpointer original_method,\n                        gpointer replacement_method)\n{\n  g_mutex_lock (&lock);\n\n  g_hash_table_insert (methods, original_method, replacement_method);\n  g_hash_table_insert (replacements, replacement_method, original_method);\n\n  g_mutex_unlock (&lock);\n}\n\nvoid\nsynchronize_replacement_methods (guint quick_code_offset,\n                                 void * nterp_entrypoint,\n                                 void * quick_to_interpreter_bridge)\n{\n  GHashTableIter iter;\n  gpointer hooked_method, replacement_method;\n\n  g_mutex_lock (&lock);\n\n  g_hash_table_iter_init (&iter, methods);\n  while (g_hash_table_iter_next (&iter, &hooked_method, &replacement_method))\n  {\n    void ** quick_code;\n\n    *((uint32_t *) replacement_method) = *((uint32_t *) hooked_method);\n\n    quick_code = hooked_method + quick_code_offset;\n    if (*quick_code == nterp_entrypoint)\n      *quick_code = quick_to_interpreter_bridge;\n  }\n\n  g_mutex_unlock (&lock);\n}\n\nvoid\ndelete_replacement_method (gpointer original_method)\n{\n  gpointer replacement_method;\n\n  g_mutex_lock (&lock);\n\n  replacement_method = g_hash_table_lookup (methods, original_method);\n  if (replacement_method != NULL)\n  {\n    g_hash_table_remove (methods, original_method);\n    g_hash_table_remove (replacements, replacement_method);\n  }\n\n  g_mutex_unlock (&lock);\n}\n\ngpointer\ntranslate_method (gpointer method)\n{\n  gpointer translated_method;\n\n  g_mutex_lock (&lock);\n\n  translated_method = g_hash_table_lookup (replacements, method);\n\n  g_mutex_unlock (&lock);\n\n  return (translated_method != NULL) ? translated_method : method;\n}\n\ngpointer\nfind_replacement_method_from_quick_code (gpointer method,\n                                         gpointer thread)\n{\n  gpointer replacement_method;\n  gpointer managed_stack;\n  gpointer top_quick_frame;\n  gpointer link_managed_stack;\n  gpointer * link_top_quick_frame;\n\n  replacement_method = get_replacement_method (method);\n  if (replacement_method == NULL)\n    return NULL;\n\n  /*\n   * Stack check.\n   *\n   * Return NULL to indicate that the original method should be invoked, otherwise\n   * return a pointer to the replacement ArtMethod.\n   *\n   * If the caller is our own JNI replacement stub, then a stack transition must\n   * have been pushed onto the current thread's linked list.\n   *\n   * Therefore, we invoke the original method if the following conditions are met:\n   *   1- The current managed stack is empty.\n   *   2- The ArtMethod * inside the linked managed stack's top quick frame is the\n   *      same as our replacement.\n   */\n  managed_stack = thread + ${n.managedStack};\n  top_quick_frame = *((gpointer *) (managed_stack + ${r.topQuickFrame}));\n  if (top_quick_frame != NULL)\n    return replacement_method;\n\n  link_managed_stack = *((gpointer *) (managed_stack + ${r.link}));\n  if (link_managed_stack == NULL)\n    return replacement_method;\n\n  link_top_quick_frame = GSIZE_TO_POINTER (*((gsize *) (link_managed_stack + ${r.topQuickFrame})) & ~((gsize) 1));\n  if (link_top_quick_frame == NULL || *link_top_quick_frame != replacement_method)\n    return replacement_method;\n\n  return NULL;\n}\n\nvoid\non_interpreter_do_call (GumInvocationContext * ic)\n{\n  gpointer method, replacement_method;\n\n  method = gum_invocation_context_get_nth_argument (ic, 0);\n\n  replacement_method = get_replacement_method (method);\n  if (replacement_method != NULL)\n    gum_invocation_context_replace_nth_argument (ic, 0, replacement_method);\n}\n\ngpointer\non_art_method_get_oat_quick_method_header (gpointer method,\n                                           gpointer pc)\n{\n  if (is_replacement_method (method))\n    return NULL;\n\n  return get_oat_quick_method_header_impl (method, pc);\n}\n\nvoid\non_art_method_pretty_method (GumInvocationContext * ic)\n{\n  const guint this_arg_index = ${"arm64"===Process.arch?0:1};\n  gpointer method;\n\n  method = gum_invocation_context_get_nth_argument (ic, this_arg_index);\n  if (method == NULL)\n    gum_invocation_context_replace_nth_argument (ic, this_arg_index, last_seen_art_method);\n  else\n    last_seen_art_method = method;\n}\n\nvoid\non_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic)\n{\n  GHashTableIter iter;\n  gpointer hooked_method, replacement_method;\n\n  g_mutex_lock (&lock);\n\n  g_hash_table_iter_init (&iter, methods);\n  while (g_hash_table_iter_next (&iter, &hooked_method, &replacement_method))\n    *((uint32_t *) replacement_method) = *((uint32_t *) hooked_method);\n\n  g_mutex_unlock (&lock);\n}\n`,a=8,i=d,s=d,c=d,l=Memory.alloc(a+i+s+c),u=l.add(a),p=u.add(i),_=p.add(s),m=e.find(4===d?"_ZN3art9ArtMethod23GetOatQuickMethodHeaderEj":"_ZN3art9ArtMethod23GetOatQuickMethodHeaderEm"),h=new CModule(o,{lock:l,methods:u,replacements:p,last_seen_art_method:_,get_oat_quick_method_header_impl:m??ptr("0xdeadbeef")}),g={exceptions:"propagate",scheduling:"exclusive"};return{handle:h,replacedMethods:{isReplacement:new NativeFunction(h.is_replacement_method,"bool",["pointer"],g),get:new NativeFunction(h.get_replacement_method,"pointer",["pointer"],g),set:new NativeFunction(h.set_replacement_method,"void",["pointer","pointer"],g),synchronize:new NativeFunction(h.synchronize_replacement_methods,"void",["uint","pointer","pointer"],g),delete:new NativeFunction(h.delete_replacement_method,"void",["pointer"],g),translate:new NativeFunction(h.translate_method,"pointer",["pointer"],g),findReplacementFromQuickCode:h.find_replacement_method_from_quick_code},getOatQuickMethodHeaderImpl:m,hooks:{Interpreter:{doCall:h.on_interpreter_do_call},ArtMethod:{getOatQuickMethodHeader:h.on_art_method_get_oat_quick_method_header,prettyMethod:h.on_art_method_pretty_method},Gc:{copyingPhase:{onLeave:h.on_leave_gc_concurrent_copying_copying_phase},runFlip:{onEnter:h.on_leave_gc_concurrent_copying_copying_phase}}}}}(o,h),function(e){const t=e["art::ArtMethod::PrettyMethod"];if(void 0===t)return;Interceptor.attach(t.impl,C.hooks.ArtMethod.prettyMethod),Interceptor.flush()}(o);let g=null;Object.defineProperty(o,"jvmti",{get(){return null===g&&(g=[U(h,this.artRuntime)]),g[0]}})}const h=t.enumerateImports().filter((e=>0===e.name.indexOf("_Z"))).reduce(((e,t)=>(e[t.name]=t.address,e)),{});return o.$new=new NativeFunction(h._Znwm||h._Znwj,"pointer",["ulong"],x),o.$delete=new NativeFunction(h._ZdlPv,"void",["pointer"],x),y=r?Re:Pe,o}()),P}function U(e,o){let a=null;return e.perform((()=>{const i=getApi().find("_ZN3art7Runtime18EnsurePluginLoadedEPKcPNSt3__112basic_stringIcNS3_11char_traitsIcEENS3_9allocatorIcEEEE");if(null===i)return;const c=new NativeFunction(i,"bool",["pointer","pointer","pointer"]),l=Memory.alloc(d);if(!c(o,Memory.allocUtf8String("libopenjdkjvmti.so"),l))return;const u=1073741824|t.v1_2,p=e.tryGetEnvHandle(u);if(null===p)return;a=new r(p,e);const _=Memory.alloc(8);_.writeU64(n.canTagObjects);a.addCapabilities(_)!==s&&(a=null)})),a}export function ensureClassInitialized(e,t){"art"===getApi().flavor&&e.getClassName(t)}const G={ia32:B,x64:B,arm:function(e){if("add.w"!==e.mnemonic)return null;const t=e.operands;if(3!==t.length)return null;const n=t[2];if("imm"!==n.type)return null;return n.value},arm64:function(e){if("add"!==e.mnemonic)return null;const t=e.operands;if(3!==t.length)return null;if("sp"===t[0].value||"sp"===t[1].value)return null;const n=t[2];if("imm"!==n.type)return null;const r=n.value.valueOf();if(r<256||r>1024)return null;return r}};function B(e){if("lea"!==e.mnemonic)return null;const t=e.operands[1].value.disp;return t<256||t>1024?null:t}const q={ia32:W,x64:W,arm:function(e){return null},arm64:function(e){if("ldr"!==e.mnemonic)return null;const t=e.operands;if("x0"===t[0].value)return null;const n=t[1].value;if("x0"!==n.base)return null;const r=n.disp;if(r<256||r>1024)return null;return r}};function W(e){if("mov"!==e.mnemonic)return null;const t=e.operands;if("rax"!==t[0].value)return null;const n=t[1];if("mem"!==n.type)return null;const r=n.value;if("rdi"!==r.base)return null;const o=r.disp;return o<256||o>1024?null:o}const H={ia32:K,x64:K,arm:function(e){if("ldr.w"===e.mnemonic)return e.operands[1].value.disp;return null},arm64:function(e,t){if(null===t)return null;const{mnemonic:n}=e,{mnemonic:r}=t;if("cmp"===n&&"ldr"===r||"bl"===n&&"str"===r)return t.operands[1].value.disp;return null}};function K(e){return"cmp"===e.mnemonic?e.operands[0].value.disp:null}function Q(e,t){if(null!==M)return M;const{classLinker:n,internTable:r}=t.offset,o=e.add(n).readPointer(),a=e.add(r).readPointer(),i=4===d?100:200,s=i+100*d,c=getAndroidApiLevel();let l=null;for(let e=i;e!==s;e+=d){if(o.add(e).readPointer().equals(a)){let t;t=c>=30||"R"===N()?6:c>=29?4:c>=23?3:5;const n=e+t*d;let r;r=c>=23?n-2*d:n-3*d,l={offset:{quickResolutionTrampoline:r,quickImtConflictTrampoline:n-d,quickGenericJniTrampoline:n,quickToInterpreterBridgeTrampoline:n+d}};break}}return null!==l&&(M=l),l}export function getArtClassSpec(e){let t=null;return e.perform((n=>{const r=getArtFieldSpec(e),o=getArtMethodSpec(e),a={artArrayLengthSize:4,artArrayEntrySize:r.size,artArrayMax:50},i={artArrayLengthSize:d,artArrayEntrySize:o.size,artArrayMax:100},s=(e,t,n)=>{const r=e.add(t).readPointer();if(r.isNull())return null;const o=4===n?r.readU32():r.readU64().valueOf();return o<=0?null:{length:o,data:r.add(n)}},c=(e,t,n,r)=>{try{const o=s(e,t,r.artArrayLengthSize);if(null===o)return!1;const a=Math.min(o.length,r.artArrayMax);for(let e=0;e!==a;e++){if(o.data.add(e*r.artArrayEntrySize).equals(n))return!0}}catch{}return!1},l=n.findClass("java/lang/Thread"),u=n.newGlobalRef(l);try{let r;withRunnableArtThread(e,n,(t=>{r=getApi()["art::JavaVMExt::DecodeGlobal"](e,t,u)}));const o=be(n.getFieldId(u,"name","Ljava/lang/String;")),d=be(n.getStaticFieldId(u,"MAX_PRIORITY","I"));let p=-1,_=-1;for(let e=0;256!==e;e+=4)-1===p&&c(r,e,d,a)&&(p=e),-1===_&&c(r,e,o,a)&&(_=e);if(-1===_||-1===p)throw new Error("Unable to find fields in java/lang/Thread; please file a bug");const m=_!==p?p:0,h=_;let g=-1;const f=fe(n.getMethodId(u,"getName","()Ljava/lang/String;"));for(let e=0;256!==e;e+=4)-1===g&&c(r,e,f,i)&&(g=e);if(-1===g)throw new Error("Unable to find methods in java/lang/Thread; please file a bug");let b=-1;const v=s(r,g,i.artArrayLengthSize).length;for(let e=g;256!==e;e+=4)if(r.add(e).readU16()===v){b=e;break}if(-1===b)throw new Error("Unable to find copied methods in java/lang/Thread; please file a bug");t={offset:{ifields:h,methods:g,sfields:m,copiedMethodsOffset:b}}}finally{n.deleteLocalRef(l),n.deleteGlobalRef(u)}})),t}export function getArtFieldSpec(e){const t=getAndroidApiLevel();return t>=23?{size:16,offset:{accessFlags:4}}:t>=21?{size:24,offset:{accessFlags:12}}:null}const $={ia32:Y,x64:Y,arm:function(e){if("ldr.w"===e.mnemonic)return e.operands[1].value.disp;return null},arm64:function(e){if("ldr"===e.mnemonic)return e.operands[1].value.disp;return null}};function X(e,t){let n;return t.perform((t=>{const r=getArtThreadFromEnv(t),o=(0,$[Process.arch])(Instruction.parse(e));n=null!==o?r.add(o).readPointer():e})),n}function Y(e){return"jmp"===e.mnemonic?e.operands[0].value.disp:null}export function getArtThreadFromEnv(e){return e.handle.add(d).readPointer()}function ee(){return 1e7*getAndroidApiLevel()}let te=null;function ne(e){null===te&&(te=new NativeFunction(Process.getModuleByName("libc.so").getExportByName("__system_property_get"),"int",["pointer","pointer"],x));const t=Memory.alloc(92);return te(Memory.allocUtf8String(e),t),t.readUtf8String()}export function withRunnableArtThread(e,t,n){const r=E(e,t),o=getArtThreadFromEnv(t).toString();if(w[o]=n,r(t.handle),void 0!==w[o])throw delete w[o],new Error("Unable to perform state transition; please file a bug")}function re(e){const t=e.toString(),n=w[t];delete w[t],n(e)}export function withAllArtThreadsSuspended(e){const t=getApi(),n=t.artThreadList;t["art::ThreadList::SuspendAll"](n,Memory.allocUtf8String("frida"),0);try{e()}finally{t["art::ThreadList::ResumeAll"](n)}}class oe{constructor(e){const t=Memory.alloc(4*d),n=t.add(d);t.writePointer(n);const r=new NativeCallback(((t,n)=>!0===e(n)?1:0),"bool",["pointer","pointer"]);n.add(2*d).writePointer(r),this.handle=t,this._onVisit=r}}export function makeArtClassVisitor(e){return getApi()["art::ClassLinker::VisitClasses"]instanceof NativeFunction?new oe(e):new NativeCallback((t=>!0===e(t)?1:0),"bool",["pointer","pointer"])}class ae{constructor(e){const t=Memory.alloc(4*d),n=t.add(d);t.writePointer(n);const r=new NativeCallback(((t,n)=>{e(n)}),"void",["pointer","pointer"]);n.add(2*d).writePointer(r),this.handle=t,this._onVisit=r}}export function makeArtClassLoaderVisitor(e){return new ae(e)}const ie={"include-inlined-frames":0,"skip-inlined-frames":1};export class ArtStackVisitor{constructor(e,t,n,r=0,o=!0){const a=getApi(),i=3*d,s=Memory.alloc(512+i);a["art::StackVisitor::StackVisitor"](s,e,t,ie[n],r,o?1:0);const c=s.add(512);s.writePointer(c);const l=new NativeCallback(this._visitFrame.bind(this),"bool",["pointer"]);c.add(2*d).writePointer(l),this.handle=s,this._onVisitFrame=l;const u=s.add(4===d?12:24);this._curShadowFrame=u,this._curQuickFrame=u.add(d),this._curQuickFramePc=u.add(2*d),this._curOatQuickMethodHeader=u.add(3*d),this._getMethodImpl=a["art::StackVisitor::GetMethod"],this._descLocImpl=a["art::StackVisitor::DescribeLocation"],this._getCQFIImpl=a["art::StackVisitor::GetCurrentQuickFrameInfo"]}walkStack(e=!1){getApi()["art::StackVisitor::WalkStack"](this.handle,e?1:0)}_visitFrame(){return this.visitFrame()?1:0}visitFrame(){throw new Error("Subclass must implement visitFrame")}getMethod(){const e=this._getMethodImpl(this.handle);return e.isNull()?null:new ArtMethod(e)}getCurrentQuickFramePc(){return this._curQuickFramePc.readPointer()}getCurrentQuickFrame(){return this._curQuickFrame.readPointer()}getCurrentShadowFrame(){return this._curShadowFrame.readPointer()}describeLocation(){const e=new Fe;return this._descLocImpl(e,this.handle),e.disposeToString()}getCurrentOatQuickMethodHeader(){return this._curOatQuickMethodHeader.readPointer()}getCurrentQuickFrameInfo(){return this._getCQFIImpl(this.handle)}}export class ArtMethod{constructor(e){this.handle=e}prettyMethod(e=!0){const t=new Fe;return getApi()["art::ArtMethod::PrettyMethod"](t,this.handle,e?1:0),t.disposeToString()}toString(){return`ArtMethod(handle=${this.handle})`}}const se={ia32:globalThis.X86Relocator,x64:globalThis.X86Relocator,arm:globalThis.ThumbRelocator,arm64:globalThis.Arm64Relocator},ce={ia32:globalThis.X86Writer,x64:globalThis.X86Writer,arm:globalThis.ThumbWriter,arm64:globalThis.Arm64Writer};function de(e,t){null===j&&(j=Memory.alloc(Process.pageSize));const n=j.add(z),r=Process.arch,o=ce[r];return Memory.patchCode(n,e,(r=>{const a=new o(r,{pc:n});if(t(a),a.flush(),a.offset>e)throw new Error(`Wrote ${a.offset}, exceeding maximum of ${e}`)})),z+=e,"arm"===r?n.or(1):n}function le(e,t){!function(e){if(F)return;F=!0,function(e){const t=getApi();[t.artQuickGenericJniTrampoline,t.artQuickToInterpreterBridge,t.artQuickResolutionTrampoline].forEach((t=>{Memory.protect(t,32,"rwx");const n=new Ae(t);n.activate(e),T.push(n)}))}(e),function(){const e=getApi(),t=getAndroidApiLevel(),{isApiLevel34OrApexEquivalent:n}=e;let r;if(t<=22)r=/^_ZN3art11interpreter6DoCallILb[0-1]ELb[0-1]EEEbPNS_6mirror9ArtMethodEPNS_6ThreadERNS_11ShadowFrameEPKNS_11InstructionEtPNS_6JValueE$/;else if(t<=33&&!n)r=/^_ZN3art11interpreter6DoCallILb[0-1]ELb[0-1]EEEbPNS_9ArtMethodEPNS_6ThreadERNS_11ShadowFrameEPKNS_11InstructionEtPNS_6JValueE$/;else{if(!n)throw new Error("Unable to find method invocation in ART; please file a bug");r=/^_ZN3art11interpreter6DoCallILb[0-1]EEEbPNS_9ArtMethodEPNS_6ThreadERNS_11ShadowFrameEPKNS_11InstructionEtbPNS_6JValueE$/}const o=e.module,a=[...o.enumerateExports(),...o.enumerateSymbols()].filter((e=>r.test(e.name)));if(0===a.length)throw new Error("Unable to find method invocation in ART; please file a bug");for(const e of a)Interceptor.attach(e.address,C.hooks.Interpreter.doCall)}(),function(){const e=getApi(),t=e.module.findSymbolByName("_ZN3art2gc4Heap22CollectGarbageInternalENS0_9collector6GcTypeENS0_7GcCauseEbj");if(null===t)return;const{artNterpEntryPoint:n,artQuickToInterpreterBridge:r}=e,o=getArtMethodSpec(e.vm).offset.quickCode;Interceptor.attach(t,{onLeave(){C.replacedMethods.synchronize(o,n,r)}})}(),function(){const e=[["_ZN3art11ClassLinker26VisiblyInitializedCallback22MarkVisiblyInitializedEPNS_6ThreadE","e90340f8 : ff0ff0ff"],["_ZN3art11ClassLinker26VisiblyInitializedCallback29AdjustThreadVisibilityCounterEPNS_6ThreadEl","7f0f00f9 : 1ffcffff"]],t=getApi(),n=t.module;for(const[r,o]of e){const e=n.findSymbolByName(r);if(null===e)continue;const a=Memory.scanSync(e,8192,o);if(0===a.length)return;const{artNterpEntryPoint:i,artQuickToInterpreterBridge:s}=t,c=getArtMethodSpec(t.vm).offset.quickCode;return void Interceptor.attach(a[0].address,(function(){C.replacedMethods.synchronize(c,i,s)}))}}()}(t),function(e){if(O)return;if(O=!0,!function(){if(getAndroidApiLevel()<31)return!1;const e=ue[Process.arch];if(void 0===e)return!1;const t=e.signatures.map((({pattern:e,offset:t=0,validateMatch:n=me})=>({pattern:new MatchPattern(e.join("")),offset:t,validateMatch:n}))),n=[];for(const{base:e,size:r}of getApi().module.enumerateRanges("--x"))for(const{pattern:o,offset:a,validateMatch:i}of t){const t=Memory.scanSync(e,r,o).map((({address:e,size:t})=>({address:e.sub(a),size:t+a}))).filter((e=>{const t=i(e);return null!==t&&(e.validationResult=t,!0)}));n.push(...t)}if(0===n.length)return!1;return n.forEach(e.instrument),!0}()){const{getOatQuickMethodHeaderImpl:e}=C;if(null===e)return;try{Interceptor.replace(e,C.hooks.ArtMethod.getOatQuickMethodHeader)}catch(e){}}const t=getAndroidApiLevel();let n=null;const r=getApi();t>28?n=r.find("_ZN3art2gc9collector17ConcurrentCopying12CopyingPhaseEv"):t>22&&(n=r.find("_ZN3art2gc9collector17ConcurrentCopying12MarkingPhaseEv"));null!==n&&Interceptor.attach(n,C.hooks.Gc.copyingPhase);let o=null;o=r.find("_ZN3art6Thread15RunFlipFunctionEPS0_"),null===o&&(o=r.find("_ZN3art6Thread15RunFlipFunctionEPS0_b"));null!==o&&Interceptor.attach(o,C.hooks.Gc.runFlip)}()}const ue={arm:{signatures:[{pattern:["b0 68","01 30","0c d0","1b 98",":","c0 ff","c0 ff","00 ff","00 2f"],validateMatch:pe},{pattern:["d8 f8 08 00","01 30","0c d0","1b 98",":","f0 ff ff 0f","ff ff","00 ff","00 2f"],validateMatch:pe},{pattern:["b0 68","01 30","40 f0 c3 80","00 25",":","c0 ff","c0 ff","c0 fb 00 d0","ff f8"],validateMatch:pe}],instrument:function({address:e,size:t,validationResult:n}){const{methodReg:r,target:o}=n,a=Memory.alloc(Process.pageSize);let i=t;Memory.patchCode(a,256,(t=>{const n=new ThumbWriter(t,{pc:a}),s=new ThumbRelocator(e,n);for(let e=0;2!==e;e++)s.readOne();s.writeAll(),s.readOne(),s.skipOne(),n.putBCondLabel("eq","runtime_or_replacement_method");n.putBytes([45,237,16,10]);const c=["r0","r1","r2","r3"];n.putPushRegs(c),n.putCallAddressWithArguments(C.replacedMethods.isReplacement,[r]),n.putCmpRegImm("r0",0),n.putPopRegs(c);n.putBytes([189,236,16,10]),n.putBCondLabel("ne","runtime_or_replacement_method"),n.putBLabel("regular_method"),s.readOne();const d=s.input.address.equals(o.whenRegularMethod);for(n.putLabel(d?"regular_method":"runtime_or_replacement_method"),s.writeOne();i<10;){const e=s.readOne();if(0===e){i=10;break}i=e}s.writeAll(),n.putBranchAddress(e.add(i+1)),n.putLabel(d?"runtime_or_replacement_method":"regular_method"),n.putBranchAddress(o.whenTrue),n.flush()})),I.push(new he(e,i,a)),Memory.patchCode(e,i,(t=>{const n=new ThumbWriter(t,{pc:e});n.putLdrRegAddress("pc",a.or(1)),n.flush()}))}},arm64:{signatures:[{pattern:["0a 40 b9","1f 05 00 31","40 01 00 54","88 39 00 f0",":","fc ff ff","1f fc ff ff","1f 00 00 ff","00 00 00 9f"],offset:1,validateMatch:_e},{pattern:["0a 40 b9","1f 05 00 31","40 01 00 54","00 0e 40 f9",":","fc ff ff","1f fc ff ff","1f 00 00 ff","00 fc ff ff"],offset:1,validateMatch:_e},{pattern:["0a 40 b9","1f 05 00 31","01 34 00 54","e0 03 1f aa",":","fc ff ff","1f fc ff ff","1f 00 00 ff","e0 ff ff ff"],offset:1,validateMatch:_e}],instrument:function({address:e,size:t,validationResult:n}){const{methodReg:r,scratchReg:o,target:a}=n,i=Memory.alloc(Process.pageSize);Memory.patchCode(i,256,(t=>{const n=new Arm64Writer(t,{pc:i}),o=new Arm64Relocator(e,n);for(let e=0;2!==e;e++)o.readOne();o.writeAll(),o.readOne(),o.skipOne(),n.putBCondLabel("eq","runtime_or_replacement_method");const s=["d0","d1","d2","d3","d4","d5","d6","d7","x0","x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13","x14","x15","x16","x17"],c=s.length;for(let e=0;e!==c;e+=2)n.putPushRegReg(s[e],s[e+1]);n.putCallAddressWithArguments(C.replacedMethods.isReplacement,[r]),n.putCmpRegReg("x0","xzr");for(let e=c-2;e>=0;e-=2)n.putPopRegReg(s[e],s[e+1]);n.putBCondLabel("ne","runtime_or_replacement_method"),n.putBLabel("regular_method"),o.readOne();const d=o.input,l=d.address.equals(a.whenRegularMethod);n.putLabel(l?"regular_method":"runtime_or_replacement_method"),o.writeOne(),n.putBranchAddress(d.next),n.putLabel(l?"runtime_or_replacement_method":"regular_method"),n.putBranchAddress(a.whenTrue),n.flush()})),I.push(new he(e,t,i)),Memory.patchCode(e,t,(t=>{const n=new Arm64Writer(t,{pc:e});n.putLdrRegAddress(o,i),n.putBrReg(o),n.flush()}))}}};function pe({address:e,size:t}){const n=Instruction.parse(e.or(1)),[r,a]=n.operands,i=a.value.base,s=r.value,c=Instruction.parse(n.next.add(2)),d=ptr(c.operands[0].value),l=c.address.add(c.size);let u,p;return"beq"===c.mnemonic?(u=l,p=d):(u=d,p=l),o(u.or(1),(function(e){const{mnemonic:t}=e;if("ldr"!==t&&"ldr.w"!==t)return null;const{base:n,disp:r}=e.operands[1].value;if(n!==i||20!==r)return null;return{methodReg:i,scratchReg:s,target:{whenTrue:d,whenRegularMethod:u,whenRuntimeMethod:p}}}),{limit:3})}function _e({address:e,size:t}){const[n,r]=Instruction.parse(e).operands,a=r.value.base,i="x"+n.value.substring(1),s=Instruction.parse(e.add(8)),c=ptr(s.operands[0].value),d=e.add(12);let l,u;return"b.eq"===s.mnemonic?(l=d,u=c):(l=c,u=d),o(l,(function(e){if("ldr"!==e.mnemonic)return null;const{base:t,disp:n}=e.operands[1].value;if(t!==a||24!==n)return null;return{methodReg:a,scratchReg:i,target:{whenTrue:c,whenRegularMethod:l,whenRuntimeMethod:u}}}),{limit:3})}function me(){return{}}class he{constructor(e,t,n){this.address=e,this.size=t,this.originalCode=e.readByteArray(t),this.trampoline=n}revert(){Memory.patchCode(this.address,this.size,(e=>{e.writeByteArray(this.originalCode)}))}}export function makeMethodMangler(e){return new y(e)}export function translateMethod(e){return C.replacedMethods.translate(e)}export function backtrace(e,t={}){const{limit:n=16}=t,r=e.getEnv();return null===D&&(D=function(e,t){const n=getApi(),r=Memory.alloc(Process.pointerSize),o=new CModule("\n#include <glib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <gum/gumtls.h>\n#include <json-glib/json-glib.h>\n\ntypedef struct _ArtBacktrace ArtBacktrace;\ntypedef struct _ArtStackFrame ArtStackFrame;\n\ntypedef struct _ArtStackVisitor ArtStackVisitor;\ntypedef struct _ArtStackVisitorVTable ArtStackVisitorVTable;\n\ntypedef struct _ArtClass ArtClass;\ntypedef struct _ArtMethod ArtMethod;\ntypedef struct _ArtThread ArtThread;\ntypedef struct _ArtContext ArtContext;\n\ntypedef struct _JNIEnv JNIEnv;\n\ntypedef struct _StdString StdString;\ntypedef struct _StdTinyString StdTinyString;\ntypedef struct _StdLargeString StdLargeString;\n\ntypedef enum {\n  STACK_WALK_INCLUDE_INLINED_FRAMES,\n  STACK_WALK_SKIP_INLINED_FRAMES,\n} StackWalkKind;\n\nstruct _StdTinyString\n{\n  guint8 unused;\n  gchar data[(3 * sizeof (gpointer)) - 1];\n};\n\nstruct _StdLargeString\n{\n  gsize capacity;\n  gsize size;\n  gchar * data;\n};\n\nstruct _StdString\n{\n  union\n  {\n    guint8 flags;\n    StdTinyString tiny;\n    StdLargeString large;\n  };\n};\n\nstruct _ArtBacktrace\n{\n  GChecksum * id;\n  GArray * frames;\n  gchar * frames_json;\n};\n\nstruct _ArtStackFrame\n{\n  ArtMethod * method;\n  gsize dexpc;\n  StdString description;\n};\n\nstruct _ArtStackVisitorVTable\n{\n  void (* unused1) (void);\n  void (* unused2) (void);\n  bool (* visit) (ArtStackVisitor * visitor);\n};\n\nstruct _ArtStackVisitor\n{\n  ArtStackVisitorVTable * vtable;\n\n  guint8 padding[512];\n\n  ArtStackVisitorVTable vtable_storage;\n\n  ArtBacktrace * backtrace;\n};\n\nstruct _ArtMethod\n{\n  guint32 declaring_class;\n  guint32 access_flags;\n};\n\nextern GumTlsKey current_backtrace;\n\nextern void (* perform_art_thread_state_transition) (JNIEnv * env);\n\nextern ArtContext * art_make_context (ArtThread * thread);\n\nextern void art_stack_visitor_init (ArtStackVisitor * visitor, ArtThread * thread, void * context, StackWalkKind walk_kind,\n    size_t num_frames, bool check_suspended);\nextern void art_stack_visitor_walk_stack (ArtStackVisitor * visitor, bool include_transitions);\nextern ArtMethod * art_stack_visitor_get_method (ArtStackVisitor * visitor);\nextern void art_stack_visitor_describe_location (StdString * description, ArtStackVisitor * visitor);\nextern ArtMethod * translate_method (ArtMethod * method);\nextern void translate_location (ArtMethod * method, guint32 pc, const gchar ** source_file, gint32 * line_number);\nextern void get_class_location (StdString * result, ArtClass * klass);\nextern void cxx_delete (void * mem);\nextern unsigned long strtoul (const char * str, char ** endptr, int base);\n\nstatic bool visit_frame (ArtStackVisitor * visitor);\nstatic void art_stack_frame_destroy (ArtStackFrame * frame);\n\nstatic void append_jni_type_name (GString * s, const gchar * name, gsize length);\n\nstatic void std_string_destroy (StdString * str);\nstatic gchar * std_string_get_data (StdString * str);\n\nvoid\ninit (void)\n{\n  current_backtrace = gum_tls_key_new ();\n}\n\nvoid\nfinalize (void)\n{\n  gum_tls_key_free (current_backtrace);\n}\n\nArtBacktrace *\n_create (JNIEnv * env,\n         guint limit)\n{\n  ArtBacktrace * bt;\n\n  bt = g_new (ArtBacktrace, 1);\n  bt->id = g_checksum_new (G_CHECKSUM_SHA1);\n  bt->frames = (limit != 0)\n      ? g_array_sized_new (FALSE, FALSE, sizeof (ArtStackFrame), limit)\n      : g_array_new (FALSE, FALSE, sizeof (ArtStackFrame));\n  g_array_set_clear_func (bt->frames, (GDestroyNotify) art_stack_frame_destroy);\n  bt->frames_json = NULL;\n\n  gum_tls_key_set_value (current_backtrace, bt);\n\n  perform_art_thread_state_transition (env);\n\n  gum_tls_key_set_value (current_backtrace, NULL);\n\n  return bt;\n}\n\nvoid\n_on_thread_state_transition_complete (ArtThread * thread)\n{\n  ArtContext * context;\n  ArtStackVisitor visitor = {\n    .vtable_storage = {\n      .visit = visit_frame,\n    },\n  };\n\n  context = art_make_context (thread);\n\n  art_stack_visitor_init (&visitor, thread, context, STACK_WALK_SKIP_INLINED_FRAMES, 0, true);\n  visitor.vtable = &visitor.vtable_storage;\n  visitor.backtrace = gum_tls_key_get_value (current_backtrace);\n\n  art_stack_visitor_walk_stack (&visitor, false);\n\n  cxx_delete (context);\n}\n\nstatic bool\nvisit_frame (ArtStackVisitor * visitor)\n{\n  ArtBacktrace * bt = visitor->backtrace;\n  ArtStackFrame frame;\n  const gchar * description, * dexpc_part;\n\n  frame.method = art_stack_visitor_get_method (visitor);\n\n  art_stack_visitor_describe_location (&frame.description, visitor);\n\n  description = std_string_get_data (&frame.description);\n  if (strstr (description, \" '<\") != NULL)\n    goto skip;\n\n  dexpc_part = strstr (description, \" at dex PC 0x\");\n  if (dexpc_part == NULL)\n    goto skip;\n  frame.dexpc = strtoul (dexpc_part + 13, NULL, 16);\n\n  g_array_append_val (bt->frames, frame);\n\n  g_checksum_update (bt->id, (guchar *) &frame.method, sizeof (frame.method));\n  g_checksum_update (bt->id, (guchar *) &frame.dexpc, sizeof (frame.dexpc));\n\n  return true;\n\nskip:\n  std_string_destroy (&frame.description);\n  return true;\n}\n\nstatic void\nart_stack_frame_destroy (ArtStackFrame * frame)\n{\n  std_string_destroy (&frame->description);\n}\n\nvoid\n_destroy (ArtBacktrace * backtrace)\n{\n  g_free (backtrace->frames_json);\n  g_array_free (backtrace->frames, TRUE);\n  g_checksum_free (backtrace->id);\n  g_free (backtrace);\n}\n\nconst gchar *\n_get_id (ArtBacktrace * backtrace)\n{\n  return g_checksum_get_string (backtrace->id);\n}\n\nconst gchar *\n_get_frames (ArtBacktrace * backtrace)\n{\n  GArray * frames = backtrace->frames;\n  JsonBuilder * b;\n  guint i;\n  JsonNode * root;\n\n  if (backtrace->frames_json != NULL)\n    return backtrace->frames_json;\n\n  b = json_builder_new_immutable ();\n\n  json_builder_begin_array (b);\n\n  for (i = 0; i != frames->len; i++)\n  {\n    ArtStackFrame * frame = &g_array_index (frames, ArtStackFrame, i);\n    gchar * description, * ret_type, * paren_open, * paren_close, * arg_types, * token, * method_name, * class_name;\n    GString * signature;\n    gchar * cursor;\n    ArtMethod * translated_method;\n    StdString location;\n    gsize dexpc;\n    const gchar * source_file;\n    gint32 line_number;\n\n    description = std_string_get_data (&frame->description);\n\n    ret_type = strchr (description, '\\'') + 1;\n\n    paren_open = strchr (ret_type, '(');\n    paren_close = strchr (paren_open, ')');\n    *paren_open = '\\0';\n    *paren_close = '\\0';\n\n    arg_types = paren_open + 1;\n\n    token = strrchr (ret_type, '.');\n    *token = '\\0';\n\n    method_name = token + 1;\n\n    token = strrchr (ret_type, ' ');\n    *token = '\\0';\n\n    class_name = token + 1;\n\n    signature = g_string_sized_new (128);\n\n    append_jni_type_name (signature, class_name, method_name - class_name - 1);\n    g_string_append_c (signature, ',');\n    g_string_append (signature, method_name);\n    g_string_append (signature, \",(\");\n\n    if (arg_types != paren_close)\n    {\n      for (cursor = arg_types; cursor != NULL;)\n      {\n        gsize length;\n        gchar * next;\n\n        token = strstr (cursor, \", \");\n        if (token != NULL)\n        {\n          length = token - cursor;\n          next = token + 2;\n        }\n        else\n        {\n          length = paren_close - cursor;\n          next = NULL;\n        }\n\n        append_jni_type_name (signature, cursor, length);\n\n        cursor = next;\n      }\n    }\n\n    g_string_append_c (signature, ')');\n\n    append_jni_type_name (signature, ret_type, class_name - ret_type - 1);\n\n    translated_method = translate_method (frame->method);\n    dexpc = (translated_method == frame->method) ? frame->dexpc : 0;\n\n    get_class_location (&location, GSIZE_TO_POINTER (translated_method->declaring_class));\n\n    translate_location (translated_method, dexpc, &source_file, &line_number);\n\n    json_builder_begin_object (b);\n\n    json_builder_set_member_name (b, \"signature\");\n    json_builder_add_string_value (b, signature->str);\n\n    json_builder_set_member_name (b, \"origin\");\n    json_builder_add_string_value (b, std_string_get_data (&location));\n\n    json_builder_set_member_name (b, \"className\");\n    json_builder_add_string_value (b, class_name);\n\n    json_builder_set_member_name (b, \"methodName\");\n    json_builder_add_string_value (b, method_name);\n\n    json_builder_set_member_name (b, \"methodFlags\");\n    json_builder_add_int_value (b, translated_method->access_flags);\n\n    json_builder_set_member_name (b, \"fileName\");\n    json_builder_add_string_value (b, source_file);\n\n    json_builder_set_member_name (b, \"lineNumber\");\n    json_builder_add_int_value (b, line_number);\n\n    json_builder_end_object (b);\n\n    std_string_destroy (&location);\n    g_string_free (signature, TRUE);\n  }\n\n  json_builder_end_array (b);\n\n  root = json_builder_get_root (b);\n  backtrace->frames_json = json_to_string (root, FALSE);\n  json_node_unref (root);\n\n  return backtrace->frames_json;\n}\n\nstatic void\nappend_jni_type_name (GString * s,\n                      const gchar * name,\n                      gsize length)\n{\n  gchar shorty = '\\0';\n  gsize i;\n\n  switch (name[0])\n  {\n    case 'b':\n      if (strncmp (name, \"boolean\", length) == 0)\n        shorty = 'Z';\n      else if (strncmp (name, \"byte\", length) == 0)\n        shorty = 'B';\n      break;\n    case 'c':\n      if (strncmp (name, \"char\", length) == 0)\n        shorty = 'C';\n      break;\n    case 'd':\n      if (strncmp (name, \"double\", length) == 0)\n        shorty = 'D';\n      break;\n    case 'f':\n      if (strncmp (name, \"float\", length) == 0)\n        shorty = 'F';\n      break;\n    case 'i':\n      if (strncmp (name, \"int\", length) == 0)\n        shorty = 'I';\n      break;\n    case 'l':\n      if (strncmp (name, \"long\", length) == 0)\n        shorty = 'J';\n      break;\n    case 's':\n      if (strncmp (name, \"short\", length) == 0)\n        shorty = 'S';\n      break;\n    case 'v':\n      if (strncmp (name, \"void\", length) == 0)\n        shorty = 'V';\n      break;\n  }\n\n  if (shorty != '\\0')\n  {\n    g_string_append_c (s, shorty);\n\n    return;\n  }\n\n  if (length > 2 && name[length - 2] == '[' && name[length - 1] == ']')\n  {\n    g_string_append_c (s, '[');\n    append_jni_type_name (s, name, length - 2);\n\n    return;\n  }\n\n  g_string_append_c (s, 'L');\n\n  for (i = 0; i != length; i++)\n  {\n    gchar ch = name[i];\n    if (ch != '.')\n      g_string_append_c (s, ch);\n    else\n      g_string_append_c (s, '/');\n  }\n\n  g_string_append_c (s, ';');\n}\n\nstatic void\nstd_string_destroy (StdString * str)\n{\n  bool is_large = (str->flags & 1) != 0;\n  if (is_large)\n    cxx_delete (str->large.data);\n}\n\nstatic gchar *\nstd_string_get_data (StdString * str)\n{\n  bool is_large = (str->flags & 1) != 0;\n  return is_large ? str->large.data : str->tiny.data;\n}\n",{current_backtrace:Memory.alloc(Process.pointerSize),perform_art_thread_state_transition:r,art_make_context:n["art::Thread::GetLongJumpContext"]??n["art::Context::Create"],art_stack_visitor_init:n["art::StackVisitor::StackVisitor"],art_stack_visitor_walk_stack:n["art::StackVisitor::WalkStack"],art_stack_visitor_get_method:n["art::StackVisitor::GetMethod"],art_stack_visitor_describe_location:n["art::StackVisitor::DescribeLocation"],translate_method:C.replacedMethods.translate,translate_location:n["art::Monitor::TranslateLocation"],get_class_location:n["art::mirror::Class::GetLocation"],cxx_delete:n.$delete,strtoul:Process.getModuleByName("libc.so").getExportByName("strtoul")}),a=new NativeFunction(o._create,"pointer",["pointer","uint"],x),i=new NativeFunction(o._destroy,"void",["pointer"],x),s={exceptions:"propagate",scheduling:"exclusive"},c=new NativeFunction(o._get_id,"pointer",["pointer"],s),d=new NativeFunction(o._get_frames,"pointer",["pointer"],s),l=Le(e,t,o._on_thread_state_transition_complete);function u(e){i(e)}return o._performData=l,r.writePointer(l),o.backtrace=(e,t)=>{const n=a(e,t),r=new ge(n);return Script.bindWeak(r,u.bind(null,n)),r},o.getId=e=>c(e).readUtf8String(),o.getFrames=e=>JSON.parse(d(e).readUtf8String()),o}(e,r)),D.backtrace(r,n)}class ge{constructor(e){this.handle=e}get id(){return D.getId(this.handle)}get frames(){return D.getFrames(this.handle)}}export function revertGlobalPatches(){L.forEach((e=>{e.vtablePtr.writePointer(e.vtable),e.vtableCountPtr.writeS32(e.vtableCount)})),L.clear();for(const e of T.splice(0))e.deactivate();for(const e of I.splice(0))e.revert()}function fe(e){return ve(e,"art::jni::JniIdManager::DecodeMethodId")}function be(e){return ve(e,"art::jni::JniIdManager::DecodeFieldId")}function ve(e,t){const n=getApi(),r=v(n).offset,o=r.jniIdManager,a=r.jniIdsIndirection;if(null!==o&&null!==a){const r=n.artRuntime;if(0!==r.add(a).readInt()){const a=r.add(o).readPointer();return n[t](a,e)}}return e}const ke={ia32:function(e,t,n,r,o){const a=getArtThreadSpec(o).offset,i=getArtMethodSpec(o).offset;let s;return Memory.patchCode(e,128,(r=>{const o=new X86Writer(r,{pc:e}),c=new X86Relocator(t,o);o.putPushax(),o.putMovRegReg("ebp","esp"),o.putAndRegU32("esp",4294967280),o.putSubRegImm("esp",512),o.putBytes([15,174,4,36]),o.putMovRegFsU32Ptr("ebx",a.self),o.putCallAddressWithAlignedArguments(C.replacedMethods.findReplacementFromQuickCode,["eax","ebx"]),o.putTestRegReg("eax","eax"),o.putJccShortLabel("je","restore_registers","no-hint"),o.putMovRegOffsetPtrReg("ebp",28,"eax"),o.putLabel("restore_registers"),o.putBytes([15,174,12,36]),o.putMovRegReg("esp","ebp"),o.putPopax(),o.putJccShortLabel("jne","invoke_replacement","no-hint");do{s=c.readOne()}while(s<n&&!c.eoi);c.writeAll(),c.eoi||o.putJmpAddress(t.add(s)),o.putLabel("invoke_replacement"),o.putJmpRegOffsetPtr("eax",i.quickCode),o.flush()})),s},x64:function(e,t,n,r,o){const a=getArtThreadSpec(o).offset,i=getArtMethodSpec(o).offset;let s;return Memory.patchCode(e,256,(r=>{const o=new X86Writer(r,{pc:e}),c=new X86Relocator(t,o);o.putPushax(),o.putMovRegReg("rbp","rsp"),o.putAndRegU32("rsp",4294967280),o.putSubRegImm("rsp",512),o.putBytes([15,174,4,36]),o.putMovRegGsU32Ptr("rbx",a.self),o.putCallAddressWithAlignedArguments(C.replacedMethods.findReplacementFromQuickCode,["rdi","rbx"]),o.putTestRegReg("rax","rax"),o.putJccShortLabel("je","restore_registers","no-hint"),o.putMovRegOffsetPtrReg("rbp",64,"rax"),o.putLabel("restore_registers"),o.putBytes([15,174,12,36]),o.putMovRegReg("rsp","rbp"),o.putPopax(),o.putJccShortLabel("jne","invoke_replacement","no-hint");do{s=c.readOne()}while(s<n&&!c.eoi);c.writeAll(),c.eoi||o.putJmpAddress(t.add(s)),o.putLabel("invoke_replacement"),o.putJmpRegOffsetPtr("rdi",i.quickCode),o.flush()})),s},arm:function(e,t,n,r,o){const a=getArtMethodSpec(o).offset,i=t.and(m);let s;return Memory.patchCode(e,128,(r=>{const o=new ThumbWriter(r,{pc:e}),c=new ThumbRelocator(i,o);o.putPushRegs(["r1","r2","r3","r5","r6","r7","r8","r10","r11","lr"]),o.putBytes([45,237,16,10]),o.putSubRegRegImm("sp","sp",8),o.putStrRegRegOffset("r0","sp",0),o.putCallAddressWithArguments(C.replacedMethods.findReplacementFromQuickCode,["r0","r9"]),o.putCmpRegImm("r0",0),o.putBCondLabel("eq","restore_registers"),o.putStrRegRegOffset("r0","sp",0),o.putLabel("restore_registers"),o.putLdrRegRegOffset("r0","sp",0),o.putAddRegRegImm("sp","sp",8),o.putBytes([189,236,16,10]),o.putPopRegs(["lr","r11","r10","r8","r7","r6","r5","r3","r2","r1"]),o.putBCondLabel("ne","invoke_replacement");do{s=c.readOne()}while(s<n&&!c.eoi);c.writeAll(),c.eoi||o.putLdrRegAddress("pc",t.add(s)),o.putLabel("invoke_replacement"),o.putLdrRegRegOffset("pc","r0",a.quickCode),o.flush()})),s},arm64:function(e,t,n,{availableScratchRegs:r},o){const a=getArtMethodSpec(o).offset;let i;return Memory.patchCode(e,256,(o=>{const s=new Arm64Writer(o,{pc:e}),c=new Arm64Relocator(t,s);s.putPushRegReg("d0","d1"),s.putPushRegReg("d2","d3"),s.putPushRegReg("d4","d5"),s.putPushRegReg("d6","d7"),s.putPushRegReg("x1","x2"),s.putPushRegReg("x3","x4"),s.putPushRegReg("x5","x6"),s.putPushRegReg("x7","x20"),s.putPushRegReg("x21","x22"),s.putPushRegReg("x23","x24"),s.putPushRegReg("x25","x26"),s.putPushRegReg("x27","x28"),s.putPushRegReg("x29","lr"),s.putSubRegRegImm("sp","sp",16),s.putStrRegRegOffset("x0","sp",0),s.putCallAddressWithArguments(C.replacedMethods.findReplacementFromQuickCode,["x0","x19"]),s.putCmpRegReg("x0","xzr"),s.putBCondLabel("eq","restore_registers"),s.putStrRegRegOffset("x0","sp",0),s.putLabel("restore_registers"),s.putLdrRegRegOffset("x0","sp",0),s.putAddRegRegImm("sp","sp",16),s.putPopRegReg("x29","lr"),s.putPopRegReg("x27","x28"),s.putPopRegReg("x25","x26"),s.putPopRegReg("x23","x24"),s.putPopRegReg("x21","x22"),s.putPopRegReg("x7","x20"),s.putPopRegReg("x5","x6"),s.putPopRegReg("x3","x4"),s.putPopRegReg("x1","x2"),s.putPopRegReg("d6","d7"),s.putPopRegReg("d4","d5"),s.putPopRegReg("d2","d3"),s.putPopRegReg("d0","d1"),s.putBCondLabel("ne","invoke_replacement");do{i=c.readOne()}while(i<n&&!c.eoi);if(c.writeAll(),!c.eoi){const e=Array.from(r)[0];s.putLdrRegAddress(e,t.add(i)),s.putBrReg(e)}s.putLabel("invoke_replacement"),s.putLdrRegRegOffset("x16","x0",a.quickCode),s.putBrReg("x16"),s.flush()})),i}};const Se={ia32:Ee,x64:Ee,arm:function(e,t,n){const r=e.and(m);Memory.patchCode(r,16,(e=>{const n=new ThumbWriter(e,{pc:r});n.putLdrRegAddress("pc",t.or(1)),n.flush()}))},arm64:function(e,t,n){Memory.patchCode(e,16,(r=>{const o=new Arm64Writer(r,{pc:e});16===n?o.putLdrRegAddress("x16",t):o.putAdrpRegAddress("x16",t),o.putBrReg("x16"),o.flush()}))}};function Ee(e,t,n){Memory.patchCode(e,16,(n=>{const r=new X86Writer(n,{pc:e});r.putJmpAddress(t),r.flush()}))}const Ne={ia32:5,x64:16,arm:8,arm64:16};class Ae{constructor(e){this.quickCode=e,this.quickCodeAddress="arm"===Process.arch?e.and(m):e,this.redirectSize=0,this.trampoline=null,this.overwrittenPrologue=null,this.overwrittenPrologueLength=0}_canRelocateCode(e,t){const n=ce[Process.arch],r=se[Process.arch],{quickCodeAddress:o}=this,a=new r(o,new n(o));let i;if("arm64"===Process.arch){let n=new Set(["x16","x17"]);do{const e=a.readOne(),t=new Set(n),{read:r,written:o}=a.input.regsAccessed;for(const e of[r,o])for(const n of e){let e;e=n.startsWith("w")?"x"+n.substring(1):n,t.delete(e)}if(0===t.size)break;i=e,n=t}while(i<e&&!a.eoi);t.availableScratchRegs=n}else do{i=a.readOne()}while(i<e&&!a.eoi);return i>=e}_allocateTrampoline(){if(null===J){J=e(4===d?128:256)}const t=Ne[Process.arch];let n,r,o=1;const a={};if(4===d||this._canRelocateCode(t,a))n=t,r={};else{let e;"x64"===Process.arch?(n=5,e=2147467263):"arm64"===Process.arch&&(n=8,e=4294963200,o=4096),r={near:this.quickCodeAddress,maxDistance:e}}return this.redirectSize=n,this.trampoline=J.allocateSlice(r,o),a}_destroyTrampoline(){J.freeSlice(this.trampoline)}activate(e){const t=this._allocateTrampoline(),{trampoline:n,quickCode:r,redirectSize:o}=this,a=(0,ke[Process.arch])(n,r,o,t,e);this.overwrittenPrologueLength=a,this.overwrittenPrologue=Memory.dup(this.quickCodeAddress,a);(0,Se[Process.arch])(r,n,o)}deactivate(){const{quickCodeAddress:e,overwrittenPrologueLength:t}=this,n=ce[Process.arch];Memory.patchCode(e,t,(r=>{const o=new n(r,{pc:e}),{overwrittenPrologue:a}=this;o.putBytes(a.readByteArray(t)),o.flush()})),this._destroyTrampoline()}}class Re{constructor(e){const t=fe(e);this.methodId=t,this.originalMethod=null,this.hookedMethodId=t,this.replacementMethodId=null,this.interceptor=null}replace(e,t,n,r,o){const{kAccCompileDontBother:a,artNterpEntryPoint:i}=o;this.originalMethod=xe(this.methodId,r);const s=this.originalMethod.accessFlags;if(0!=(268435456&s)&&getAndroidApiLevel()<28){const e=this.originalMethod.jniCode;this.hookedMethodId=e.add(2*d).readPointer(),this.originalMethod=xe(this.hookedMethodId,r)}const{hookedMethodId:c}=this,l=function(e,t){const n=getApi();if(getAndroidApiLevel()<23){const t=n["art::Thread::CurrentFromGdb"]();return n["art::mirror::Object::Clone"](e,t)}return Memory.dup(e,getArtMethodSpec(t).size)}(c,r);this.replacementMethodId=l,we(l,{jniCode:e,accessFlags:(-3670017&s|256|a)>>>0,quickCode:o.artClassLinker.quickGenericJniTrampoline,interpreterCode:o.artInterpreterToCompiledCodeBridge},r);let u=1209008128;0==(256&s)&&(u|=524288),we(c,{accessFlags:(s&~u|a)>>>0},r);const p=this.originalMethod.quickCode;if(null!==i&&p.equals(i)&&we(c,{quickCode:o.artQuickToInterpreterBridge},r),!function(e){const t=getApi(),{module:n,artClassLinker:r}=t;return e.equals(r.quickGenericJniTrampoline)||e.equals(r.quickToInterpreterBridgeTrampoline)||e.equals(r.quickResolutionTrampoline)||e.equals(r.quickImtConflictTrampoline)||e.compare(n.base)>=0&&e.compare(n.base.add(n.size))<0}(p)){const e=new Ae(p);e.activate(r),this.interceptor=e}C.replacedMethods.set(c,l),le(0,r)}revert(e){const{hookedMethodId:t,interceptor:n}=this;we(t,this.originalMethod,e),C.replacedMethods.delete(t),null!==n&&(n.deactivate(),this.interceptor=null)}resolveTarget(e,t,n,r){return this.hookedMethodId}}function xe(e,t){const n=getArtMethodSpec(t).offset;return["jniCode","accessFlags","quickCode","interpreterCode"].reduce(((t,r)=>{const o=n[r];if(void 0===o)return t;const a=e.add(o),i="accessFlags"===r?l:u;return t[r]=i.call(a),t}),{})}function we(e,t,n){const r=getArtMethodSpec(n).offset;Object.keys(t).forEach((n=>{const o=r[n];if(void 0===o)return;const a=e.add(o);("accessFlags"===n?p:_).call(a,t[n])}))}class Pe{constructor(e){this.methodId=e,this.originalMethod=null}replace(e,t,n,r,o){const{methodId:a}=this;this.originalMethod=Memory.dup(a,56);let i=n.reduce(((e,t)=>e+t.size),0);t&&i++;const s=(256|a.add(4).readU32())>>>0,c=i,d=i;a.add(4).writeU32(s),a.add(10).writeU16(c),a.add(12).writeU16(0),a.add(14).writeU16(d),a.add(36).writeU32(function(e){if("ia32"!==Process.arch)return 2147483648;const t=e.add(28).readPointer().readCString();if(null===t||0===t.length||t.length>65535)return 2147483648;let n;switch(t[0]){case"V":n=0;break;case"F":n=1;break;case"D":n=2;break;case"J":n=3;break;case"Z":case"B":n=7;break;case"C":n=6;break;case"S":n=5;break;default:n=4}let r=0;for(let e=t.length-1;e>0;e--){const n=t[e];r+="D"===n||"J"===n?2:1}return n<<28|r}(a)),o.dvmUseJNIBridge(a,e)}revert(e){Memory.copy(this.methodId,this.originalMethod,56)}resolveTarget(e,t,n,r){const o=n.handle.add(12).readPointer();let a,i;if(t)a=r.dvmDecodeIndirectRef(o,e.$h);else{const t=e.$borrowClassHandle(n);a=r.dvmDecodeIndirectRef(o,t.value),t.unref(n)}i=t?a.add(0).readPointer():a;const s=i.toString(16);let c=L.get(s);if(void 0===c){const e=i.add(116),t=i.add(112),n=e.readPointer(),r=t.readS32(),o=r*d,a=Memory.alloc(2*o);Memory.copy(a,n,o),e.writePointer(a),c={classObject:i,vtablePtr:e,vtableCountPtr:t,vtable:n,vtableCount:r,shadowVtable:a,shadowVtableCount:r,targetMethods:new Map},L.set(s,c)}const l=this.methodId.toString(16);let u=c.targetMethods.get(l);if(void 0===u){u=Memory.dup(this.originalMethod,56);const e=c.shadowVtableCount++;c.shadowVtable.add(e*d).writePointer(u),u.add(8).writeU16(e),c.vtableCountPtr.writeS32(c.shadowVtableCount),c.targetMethods.set(l,u)}return u}}export function deoptimizeMethod(e,t,n){Me(e,t,5,n)}export function deoptimizeEverything(e,t){Me(e,t,3)}export function deoptimizeBootImage(e,t){const n=getApi();if(getAndroidApiLevel()<26)throw new Error("This API is only available on Android >= 8.0");withRunnableArtThread(e,t,(e=>{n["art::Runtime::DeoptimizeBootImage"](n.artRuntime)}))}function Me(e,t,n,r){const o=getApi();if(getAndroidApiLevel()<24)throw new Error("This API is only available on Android >= 7.0");withRunnableArtThread(e,t,(e=>{if(getAndroidApiLevel()<30){if(!o.isJdwpStarted()){const e=function(e){const t=new ye;e["art::Dbg::SetJdwpAllowed"](1);const n=function(){const e=getAndroidApiLevel()<28?2:3,t=e,n=!0,r=!1,o=0,a=8+f+2,i=Memory.alloc(a);return i.writeU32(t).add(4).writeU8(n?1:0).add(1).writeU8(r?1:0).add(1).add(f).writeU16(o),i}();e["art::Dbg::ConfigureJdwp"](n);const r=e["art::InternalDebuggerControlCallback::StartDebugger"];void 0!==r?r(NULL):e["art::Dbg::StartJdwp"]();return t}(o);Z.push(e)}o.isDebuggerActive()||o["art::Dbg::GoActive"]();const e=Memory.alloc(8+d);switch(e.writeU32(n),n){case 3:break;case 5:e.add(8).writePointer(r);break;default:throw new Error("Unsupported deoptimization kind")}o["art::Dbg::RequestDeoptimization"](e),o["art::Dbg::ManageDeoptimization"]()}else{const e=o.artInstrumentation;if(null===e)throw new Error("Unable to find Instrumentation class in ART; please file a bug");const t=o["art::Instrumentation::EnableDeoptimization"];if(void 0!==t){!!e.add(k().offset.deoptimizationEnabled).readU8()||t(e)}switch(n){case 3:o["art::Instrumentation::DeoptimizeEverything"](e,Memory.allocUtf8String("frida"));break;case 5:o["art::Instrumentation::Deoptimize"](e,r);break;default:throw new Error("Unsupported deoptimization kind")}}}))}class ye{constructor(){const e=Process.getModuleByName("libart.so"),t=e.getExportByName("_ZN3art4JDWP12JdwpAdbState6AcceptEv"),n=e.getExportByName("_ZN3art4JDWP12JdwpAdbState15ReceiveClientFdEv"),r=Ce(),o=Ce();this._controlFd=r[0],this._clientFd=o[0];let a=null;a=Interceptor.attach(t,(function(e){const t=e[0];Memory.scanSync(t.add(8252),256,"00 ff ff ff ff 00")[0].address.add(1).writeS32(r[1]),a.detach()})),Interceptor.replace(n,new NativeCallback((function(e){return Interceptor.revert(n),o[1]}),"int",["pointer"])),Interceptor.flush(),this._handshakeRequest=this._performHandshake()}async _performHandshake(){const e=new UnixInputStream(this._clientFd,{autoClose:!1}),t=new UnixOutputStream(this._clientFd,{autoClose:!1}),n=[74,68,87,80,45,72,97,110,100,115,104,97,107,101];try{await t.writeAll(n),await e.readAll(n.length)}catch(e){}}}function Ce(){null===V&&(V=new NativeFunction(Process.getModuleByName("libc.so").getExportByName("socketpair"),"int",["int","int","int","pointer"]));const e=Memory.alloc(8);if(-1===V(1,1,0,e))throw new Error("Unable to create socketpair for JDWP");return[e.readS32(),e.add(4).readS32()]}const Ie={ia32:Te,x64:Te,arm:function(e,t,n,r,o,a,i){const s={},c=new Set,d=ptr(1).not(),l=[n];for(;l.length>0;){let e=l.shift();const t=Object.values(s).some((({begin:t,end:n})=>e.compare(t)>=0&&e.compare(n)<0));if(t)continue;const n=e.and(d),o=n.toString(),a=e.and(1);let i={begin:n},u=null,p=!1,_=0;do{if(e.equals(r)){p=!0;break}const t=Instruction.parse(e),{mnemonic:n}=t;u=t;const m=e.and(d).toString(),h=s[m];if(void 0!==h){delete s[h.begin.toString()],s[o]=h,h.begin=i.begin,i=null;break}const g=0===_;let f=null;switch(n){case"b":f=ptr(t.operands[0].value),p=g;break;case"beq.w":case"beq":case"bne":case"bne.w":case"bgt":f=ptr(t.operands[0].value);break;case"cbz":case"cbnz":f=ptr(t.operands[1].value);break;case"pop.w":g&&(p=1===t.operands.filter((e=>"pc"===e.value)).length)}switch(n){case"it":_=1;break;case"itt":_=2;break;case"ittt":_=3;break;case"itttt":_=4;break;default:_>0&&_--}null!==f&&(c.add(f.toString()),l.push(f.or(a)),l.sort(((e,t)=>e.compare(t)))),e=t.next}while(!p);null!==i&&(i.end=u.address.add(u.size),s[o]=i)}const u=Object.keys(s).map((e=>s[e]));u.sort(((e,t)=>e.begin.compare(t.begin)));const p=s[n.and(d).toString()];u.splice(u.indexOf(p),1),u.unshift(p);const _=new ThumbWriter(e,{pc:t});let m=!1,g=null,f=null;u.forEach((e=>{const t=new ThumbRelocator(e.begin,_);let n=e.begin;const r=e.end;let s=0;do{if(0===t.readOne())throw new Error("Unexpected end of block");const e=t.input;n=e.address,s=e.size;const{mnemonic:r}=e,d=n.toString();c.has(d)&&_.putLabel(d);let l=!0;switch(r){case"b":_.putBLabel(ze(e.operands[0])),l=!1;break;case"beq.w":_.putBCondLabelWide("eq",ze(e.operands[0])),l=!1;break;case"bne.w":_.putBCondLabelWide("ne",ze(e.operands[0])),l=!1;break;case"beq":case"bne":case"bgt":_.putBCondLabelWide(r.substr(1),ze(e.operands[0])),l=!1;break;case"cbz":{const t=e.operands;_.putCbzRegLabel(t[0].value,ze(t[1])),l=!1;break}case"cbnz":{const t=e.operands;_.putCbnzRegLabel(t[0].value,ze(t[1])),l=!1;break}case"str":case"str.w":{const t=e.operands[1].value,n=t.disp;if(n===o){g=t.base;const e="r4"!==g?"r4":"r5",n=["r0","r1","r2","r3",e,"r9","r12","lr"];_.putPushRegs(n),_.putMrsRegReg(e,"apsr-nzcvq"),_.putCallAddressWithArguments(i,[g]),_.putMsrRegReg("apsr-nzcvq",e),_.putPopRegs(n),m=!0,l=!1}else a.has(n)&&t.base===g&&(l=!1);break}case"ldr":{const[t,n]=e.operands;if("mem"===n.type){const e=n.value;"r"===e.base[0]&&e.disp===h&&(f=t.value)}break}case"blx":e.operands[0].value===f&&(_.putLdrRegRegOffset("r0","r0",4),_.putCallAddressWithArguments(i,["r0"]),m=!0,f=null,l=!1)}l?t.writeAll():t.skipOne()}while(!n.add(s).equals(r));t.dispose()})),_.dispose(),m||je();return new NativeFunction(t.or(1),"void",["pointer"],x)},arm64:function(e,t,n,r,o,a,i){const s={},c=new Set,d=[n];for(;d.length>0;){let e=d.shift();if(Object.values(s).some((({begin:t,end:n})=>e.compare(t)>=0&&e.compare(n)<0)))continue;const t=e.toString();let n={begin:e},o=null,a=!1;do{if(e.equals(r)){a=!0;break}let i;try{i=Instruction.parse(e)}catch(t){if(0===e.readU32()){a=!0;break}throw t}o=i;const l=s[i.address.toString()];if(void 0!==l){delete s[l.begin.toString()],s[t]=l,l.begin=n.begin,n=null;break}let u=null;switch(i.mnemonic){case"b":u=ptr(i.operands[0].value),a=!0;break;case"b.eq":case"b.ne":case"b.le":case"b.gt":u=ptr(i.operands[0].value);break;case"cbz":case"cbnz":u=ptr(i.operands[1].value);break;case"tbz":case"tbnz":u=ptr(i.operands[2].value);break;case"ret":a=!0}null!==u&&(c.add(u.toString()),d.push(u),d.sort(((e,t)=>e.compare(t)))),e=i.next}while(!a);null!==n&&(n.end=o.address.add(o.size),s[t]=n)}const l=Object.keys(s).map((e=>s[e]));l.sort(((e,t)=>e.begin.compare(t.begin)));const u=s[n.toString()];l.splice(l.indexOf(u),1),l.unshift(u);const p=new Arm64Writer(e,{pc:t});p.putBLabel("performTransition");const _=t.add(p.offset);p.putPushAllXRegisters(),p.putCallAddressWithArguments(i,["x0"]),p.putPopAllXRegisters(),p.putRet(),p.putLabel("performTransition");let m=!1,g=null,f=null;l.forEach((e=>{const t=e.end.sub(e.begin).toInt32(),n=new Arm64Relocator(e.begin,p);let r;for(;0!==(r=n.readOne());){const e=n.input,{mnemonic:s}=e,d=e.address.toString();c.has(d)&&p.putLabel(d);let l=!0;switch(s){case"b":p.putBLabel(ze(e.operands[0])),l=!1;break;case"b.eq":case"b.ne":case"b.le":case"b.gt":p.putBCondLabel(s.substr(2),ze(e.operands[0])),l=!1;break;case"cbz":{const t=e.operands;p.putCbzRegLabel(t[0].value,ze(t[1])),l=!1;break}case"cbnz":{const t=e.operands;p.putCbnzRegLabel(t[0].value,ze(t[1])),l=!1;break}case"tbz":{const t=e.operands;p.putTbzRegImmLabel(t[0].value,t[1].value.valueOf(),ze(t[2])),l=!1;break}case"tbnz":{const t=e.operands;p.putTbnzRegImmLabel(t[0].value,t[1].value.valueOf(),ze(t[2])),l=!1;break}case"str":{const t=e.operands,n=t[0].value,r=t[1].value,i=r.disp;"xzr"===n&&i===o?(g=r.base,p.putPushRegReg("x0","lr"),p.putMovRegReg("x0",g),p.putBlImm(_),p.putPopRegReg("x0","lr"),m=!0,l=!1):a.has(i)&&r.base===g&&(l=!1);break}case"ldr":{const t=e.operands,n=t[1].value;"x"===n.base[0]&&n.disp===h&&(f=t[0].value);break}case"blr":e.operands[0].value===f&&(p.putLdrRegRegOffset("x0","x0",8),p.putCallAddressWithArguments(i,["x0"]),m=!0,f=null,l=!1)}if(l?n.writeAll():n.skipOne(),r===t)break}n.dispose()})),p.dispose(),m||je();return new NativeFunction(t,"void",["pointer"],x)}};function Le(e,t,n){const r=getApi(),o=t.handle.readPointer();let a;const i=r.find("_ZN3art3JNIILb1EE14ExceptionClearEP7_JNIEnv");let s;a=null!==i?i:o.add(h).readPointer();const c=r.find("_ZN3art3JNIILb1EE10FatalErrorEP7_JNIEnvPKc");s=null!==c?c:o.add(g).readPointer();const l=Ie[Process.arch];if(void 0===l)throw new Error("Not yet implemented for "+Process.arch);let u=null;const p=getArtThreadSpec(e).offset,_=p.exception,m=new Set,f=p.isExceptionReportedToInstrumentation;null!==f&&m.add(f);const b=p.throwLocation;null!==b&&(m.add(b),m.add(b+d),m.add(b+2*d));const v=Memory.alloc(65536);return Memory.patchCode(v,65536,(e=>{u=l(e,v,a,s,_,m,n)})),u._code=v,u._callback=n,u}function Te(e,t,n,r,o,a,i){const s={},c=new Set,l=[n];for(;l.length>0;){let e=l.shift();if(Object.values(s).some((({begin:t,end:n})=>e.compare(t)>=0&&e.compare(n)<0)))continue;const t=e.toString();let n={begin:e},o=null,a=!1;do{if(e.equals(r)){a=!0;break}const i=Instruction.parse(e);o=i;const d=s[i.address.toString()];if(void 0!==d){delete s[d.begin.toString()],s[t]=d,d.begin=n.begin,n=null;break}let u=null;switch(i.mnemonic){case"jmp":u=ptr(i.operands[0].value),a=!0;break;case"je":case"jg":case"jle":case"jne":case"js":u=ptr(i.operands[0].value);break;case"ret":a=!0}null!==u&&(c.add(u.toString()),l.push(u),l.sort(((e,t)=>e.compare(t)))),e=i.next}while(!a);null!==n&&(n.end=o.address.add(o.size),s[t]=n)}const u=Object.keys(s).map((e=>s[e]));u.sort(((e,t)=>e.begin.compare(t.begin)));const p=s[n.toString()];u.splice(u.indexOf(p),1),u.unshift(p);const _=new X86Writer(e,{pc:t});let m=!1,g=null;return u.forEach((e=>{const t=e.end.sub(e.begin).toInt32(),n=new X86Relocator(e.begin,_);let r;for(;0!==(r=n.readOne());){const e=n.input,{mnemonic:s}=e,l=e.address.toString();c.has(l)&&_.putLabel(l);let u=!0;switch(s){case"jmp":_.putJmpNearLabel(ze(e.operands[0])),u=!1;break;case"je":case"jg":case"jle":case"jne":case"js":_.putJccNearLabel(s,ze(e.operands[0]),"no-hint"),u=!1;break;case"mov":{const[t,n]=e.operands;if("mem"===t.type&&"imm"===n.type){const e=t.value,r=e.disp;if(r===o&&0===n.value.valueOf()){if(g=e.base,_.putPushfx(),_.putPushax(),_.putMovRegReg("xbp","xsp"),4===d)_.putAndRegU32("esp",4294967280);else{const e="rdi"!==g?"rdi":"rsi";_.putMovRegU64(e,uint64("0xfffffffffffffff0")),_.putAndRegReg("rsp",e)}_.putCallAddressWithAlignedArguments(i,[g]),_.putMovRegReg("xsp","xbp"),_.putPopax(),_.putPopfx(),m=!0,u=!1}else a.has(r)&&e.base===g&&(u=!1)}break}case"call":{const t=e.operands[0];"mem"===t.type&&t.value.disp===h&&(4===d?(_.putPopReg("eax"),_.putMovRegRegOffsetPtr("eax","eax",4),_.putPushReg("eax")):_.putMovRegRegOffsetPtr("rdi","rdi",8),_.putCallAddressWithArguments(i,[]),m=!0,u=!1);break}}if(u?n.writeAll():n.skipOne(),r===t)break}n.dispose()})),_.dispose(),m||je(),new NativeFunction(t,"void",["pointer"],x)}function je(){throw new Error("Unable to parse ART internals; please file a bug")}function ze(e){return ptr(e.value).toString()}function Oe(e,t){const{arch:n}=Process;switch(n){case"ia32":case"arm64":{let r;r="ia32"===n?de(64,(n=>{const r=1+t.length,o=4*r;n.putSubRegImm("esp",o);for(let e=0;e!==r;e++){const t=4*e;n.putMovRegRegOffsetPtr("eax","esp",o+4+t),n.putMovRegOffsetPtrReg("esp",t,"eax")}n.putCallAddress(e),n.putAddRegImm("esp",o-4),n.putRet()})):de(32,(n=>{n.putMovRegReg("x8","x0"),t.forEach(((e,t)=>{n.putMovRegReg("x"+t,"x"+(t+1))})),n.putLdrRegAddress("x7",e),n.putBrReg("x7")}));const o=new NativeFunction(r,"void",["pointer"].concat(t),x),a=function(...e){o(...e)};return a.handle=r,a.impl=e,a}default:{const n=new NativeFunction(e,"void",["pointer"].concat(t),x);return n.impl=e,n}}}class Fe{constructor(){this.handle=Memory.alloc(f)}dispose(){const[e,t]=this._getData();t||getApi().$delete(e)}disposeToString(){const e=this.toString();return this.dispose(),e}toString(){const[e]=this._getData();return e.readUtf8String()}_getData(){const e=this.handle,t=0==(1&e.readU8());return[t?e.add(1):e.add(2*d).readPointer(),t]}}export class HandleVector extends class{$delete(){this.dispose(),getApi().$delete(this)}constructor(e,t){this.handle=e,this._begin=e,this._end=e.add(d),this._storage=e.add(2*d),this._elementSize=t}init(){this.begin=NULL,this.end=NULL,this.storage=NULL}dispose(){getApi().$delete(this.begin)}get begin(){return this._begin.readPointer()}set begin(e){this._begin.writePointer(e)}get end(){return this._end.readPointer()}set end(e){this._end.writePointer(e)}get storage(){return this._storage.readPointer()}set storage(e){this._storage.writePointer(e)}get size(){return this.end.sub(this.begin).toInt32()/this._elementSize}}{static $new(){const e=new HandleVector(getApi().$new(b));return e.init(),e}constructor(e){super(e,d)}get handles(){const e=[];let t=this.begin;const n=this.end;for(;!t.equals(n);)e.push(t.readPointer()),t=t.add(d);return e}}const De=d,Ze=De+4;class Ve{$delete(){this.dispose(),getApi().$delete(this)}constructor(e){this.handle=e,this._link=e.add(0),this._numberOfReferences=e.add(De)}init(e,t){this.link=e,this.numberOfReferences=t}dispose(){}get link(){return new Ve(this._link.readPointer())}set link(e){this._link.writePointer(e)}get numberOfReferences(){return this._numberOfReferences.readS32()}set numberOfReferences(e){this._numberOfReferences.writeS32(e)}}const Je=function(e){const t=e%d;if(0!==t)return e+d-t;return e}(Ze),Ue=Je+d,Ge=Ue+d;export class VariableSizedHandleScope extends Ve{static $new(e,t){const n=new VariableSizedHandleScope(getApi().$new(Ge));return n.init(e,t),n}constructor(e){super(e),this._self=e.add(Je),this._currentScope=e.add(Ue);const t=(64-d-4-4)/4;this._scopeLayout=Be.layoutForCapacity(t),this._topHandleScopePtr=null}init(e,t){const n=e.add(getArtThreadSpec(t).offset.topHandleScope);this._topHandleScopePtr=n,super.init(n.readPointer(),-1),this.self=e,this.currentScope=Be.$new(this._scopeLayout),n.writePointer(this)}dispose(){let e;for(this._topHandleScopePtr.writePointer(this.link);null!==(e=this.currentScope);){const t=e.link;e.$delete(),this.currentScope=t}}get self(){return this._self.readPointer()}set self(e){this._self.writePointer(e)}get currentScope(){const e=this._currentScope.readPointer();return e.isNull()?null:new Be(e,this._scopeLayout)}set currentScope(e){this._currentScope.writePointer(e)}newHandle(e){return this.currentScope.newHandle(e)}}class Be extends Ve{static $new(e){const t=new Be(getApi().$new(e.size),e);return t.init(),t}constructor(e,t){super(e);const{offset:n}=t;this._refsStorage=e.add(n.refsStorage),this._pos=e.add(n.pos),this._layout=t}init(){super.init(NULL,this._layout.numberOfReferences),this.pos=0}get pos(){return this._pos.readU32()}set pos(e){this._pos.writeU32(e)}newHandle(e){const t=this.pos,n=this._refsStorage.add(4*t);return n.writeS32(e.toInt32()),this.pos=t+1,n}static layoutForCapacity(e){const t=Ze+4*e;return{size:t+4,numberOfReferences:e,offset:{refsStorage:Ze,pos:t}}}}const qe={arm:function(e,t){const n=Process.pageSize,r=Memory.alloc(n);Memory.protect(r,n,"rwx");const o=new NativeCallback(t,"void",["pointer"]);r._onMatchCallback=o;const a=[26625,18947,17041,53505,19202,18200,18288,48896],i=2*a.length,s=i+4,c=s+4;return Memory.patchCode(r,c,(function(t){a.forEach(((e,n)=>{t.add(2*n).writeU16(e)})),t.add(i).writeS32(e),t.add(s).writePointer(o)})),r.or(1)},arm64:function(e,t){const n=Process.pageSize,r=Memory.alloc(n);Memory.protect(r,n,"rwx");const o=new NativeCallback(t,"void",["pointer"]);r._onMatchCallback=o;const a=[3107979265,402653378,1795293247,1409286241,1476395139,3592355936,3596551104],i=4*a.length,s=i+4,c=s+8;return Memory.patchCode(r,c,(function(t){a.forEach(((e,n)=>{t.add(4*n).writeU32(e)})),t.add(i).writeS32(e),t.add(s).writePointer(o)})),r}};export function makeObjectVisitorPredicate(e,t){return(qe[Process.arch]||We)(e,t)}function We(e,t){return new NativeCallback((n=>{n.readS32()===e&&t(n)}),"void",["pointer","pointer"])}
✄
import{getApi as t,getAndroidVersion as r}from"./android.js";import{getApi as o}from"./jvm.js";let a=t;try{r()}catch(t){a=o}export default a;
✄
import e from"./env.js";import*as t from"./android.js";import{ensureClassInitialized as n,makeMethodMangler as r}from"./jvm.js";import o from"./class-model.js";import s from"./lru.js";import l from"./mkdex.js";import{getType as a,getPrimitiveType as i,getArrayType as c,makeJniObjectTypeName as u}from"./types.js";let{ensureClassInitialized:h,makeMethodMangler:f}=t;const d=Symbol("PENDING_USE"),{getCurrentThreadId:m,pointerSize:p}=Process,y={state:"empty",factories:[],loaders:null,Integer:null};let g=null,b=null,v=null,$=null,w=null,_=null,S=null,C=null,j=null;const E=new Map;export default class T{static _initialize(e,t){g=e,b=t,v="art"===t.flavor,"jvm"===t.flavor&&(h=n,f=r)}static _disposeAll(e){y.factories.forEach((t=>{t._dispose(e)}))}static get(e){const t=function(){switch(y.state){case"empty":{y.state="pending";const e=y.factories[0],t=e.use("java.util.HashMap"),n=e.use("java.lang.Integer");y.loaders=t.$new(),y.Integer=n;const r=e.loader;return null!==r&&J(e,r),y.state="ready",y}case"pending":do{Thread.sleep(.05)}while("pending"===y.state);return y;case"ready":return y}}(),n=t.factories[0];if(null===e)return n;const r=t.loaders.get(e);if(null!==r){const e=n.cast(r,t.Integer);return t.factories[e.intValue()]}const o=new T;return o.loader=e,o.cacheDir=n.cacheDir,J(o,e),o}constructor(){this.cacheDir="/data/local/tmp",this.codeCacheDir="/data/local/tmp/dalvik-cache",this.tempFileNaming={prefix:"frida",suffix:""},this._classes={},this._classHandles=new s(10,M),this._patchedMethods=new Set,this._loader=null,this._types=[{},{}],y.factories.push(this)}_dispose(e){Array.from(this._patchedMethods).forEach((e=>{e.implementation=null})),this._patchedMethods.clear(),t.revertGlobalPatches(),this._classHandles.dispose(e),this._classes={}}get loader(){return this._loader}set loader(e){const t=null===this._loader&&null!==e;this._loader=e,t&&"ready"===y.state&&this===y.factories[0]&&J(this,e)}use(e,t={}){const n="skip"!==t.cache;let r=n?this._getUsedClass(e):void 0;if(void 0===r)try{const t=g.getEnv(),{_loader:o}=this,s=null!==o?function(e,t,n){null===j&&(C=n.vaMethod("pointer",["pointer"]),j=t.loadClass.overload("java.lang.String").handle);return n=null,function(n){const r=n.newStringUtf(e),o=m();G(o);try{const e=C(n.handle,t.$h,j,r);return n.throwIfExceptionPending(),e}finally{U(o),n.deleteLocalRef(r)}}}(e,o,t):function(e){const t=e.replace(/\./g,"/");return function(e){const n=m();G(n);try{return e.findClass(t)}finally{U(n)}}}(e);r=this._make(e,s,t)}finally{n&&this._setUsedClass(e,r)}return r}_getUsedClass(e){let t;for(;(t=this._classes[e])===d;)Thread.sleep(.05);return void 0===t&&(this._classes[e]=d),t}_setUsedClass(e,t){void 0!==t?this._classes[e]=t:delete this._classes[e]}_make(e,t,n){const r=function(e,t,n,r){return O.call(this,e,t,n,r)},s=Object.create(O.prototype,{[Symbol.for("n")]:{value:e},$n:{get(){return this[Symbol.for("n")]}},[Symbol.for("C")]:{value:r},$C:{get(){return this[Symbol.for("C")]}},[Symbol.for("w")]:{value:null,writable:!0},$w:{get(){return this[Symbol.for("w")]},set(e){this[Symbol.for("w")]=e}},[Symbol.for("_s")]:{writable:!0},$_s:{get(){return this[Symbol.for("_s")]},set(e){this[Symbol.for("_s")]=e}},[Symbol.for("c")]:{value:[null]},$c:{get(){return this[Symbol.for("c")]}},[Symbol.for("m")]:{value:new Map},$m:{get(){return this[Symbol.for("m")]}},[Symbol.for("l")]:{value:null,writable:!0},$l:{get(){return this[Symbol.for("l")]},set(e){this[Symbol.for("l")]=e}},[Symbol.for("gch")]:{value:t},$gch:{get(){return this[Symbol.for("gch")]}},[Symbol.for("f")]:{value:this},$f:{get(){return this[Symbol.for("f")]}}});r.prototype=s;const l=new r(null);s[Symbol.for("w")]=l,s.$w=l;const a=l.$borrowClassHandle(n);try{const e=a.value;h(n,e),s.$l=o.build(e,n)}finally{a.unref(n)}return l}retain(e){const t=g.getEnv();return e.$clone(t)}cast(e,t,n){const r=g.getEnv();let o=e.$h;void 0===o&&(o=e);const s=t.$borrowClassHandle(r);try{if(!r.isInstanceOf(o,s.value))throw new Error(`Cast from '${r.getObjectClassName(o)}' to '${t.$n}' isn't possible`)}finally{s.unref(r)}return new(0,t.$C)(o,1,r,n)}wrap(e,t,n){const r=new(0,t.$C)(e,1,n,!1);return r.$r=Script.bindWeak(r,g.makeHandleDestructor(e)),r}array(e,t){const n=g.getEnv(),r=i(e);null!==r&&(e=r.name);const o=c("["+e,!1,this),s=o.toJni(t,n);return o.fromJni(s,n,!0)}registerClass(e){const t=g.getEnv(),n=[];try{const r=this.use("java.lang.Class"),o=t.javaLangReflectMethod(),s=t.vaMethod("pointer",[]),a=e.name,i=e.implements||[],c=e.superClass||this.use("java.lang.Object"),h=[],f=[],d={name:u(a),sourceFileName:W(a),superClass:u(c.$n),interfaces:i.map((e=>u(e.$n))),fields:h,methods:f},m=i.slice();i.forEach((e=>{Array.prototype.slice.call(e.class.getInterfaces()).forEach((e=>{const t=this.cast(e,r).getCanonicalName();m.push(this.use(t))}))}));const y=e.fields||{};Object.getOwnPropertyNames(y).forEach((e=>{const t=this._getType(y[e]);h.push([e,t.name])}));const g={},b={};m.forEach((e=>{const r=e.$borrowClassHandle(t);n.push(r);const o=r.value;e.$ownMembers.filter((t=>void 0!==e[t].overloads)).forEach((t=>{const n=e[t],r=n.overloads,s=r.map((e=>R(t,e.returnType,e.argumentTypes)));g[t]=[n,s,o],r.forEach(((e,t)=>{const n=s[t];b[n]=[e,o]}))}))}));const v=e.methods||{},$=Object.keys(v).reduce(((e,t)=>{const n=v[t],r="$init"===t?"<init>":t;return n instanceof Array?e.push(...n.map((e=>[r,e]))):e.push([r,n]),e}),[]),w=[];$.forEach((([e,n])=>{let r,l,a,i=3,c=[];if("function"==typeof n){const h=g[e];if(void 0!==h&&Array.isArray(h)){const[f,d,m]=h;if(d.length>1)throw new Error(`More than one overload matching '${e}': signature must be specified`);delete b[d[0]];const p=f.overloads[0];i=p.type,r=p.returnType,l=p.argumentTypes,a=n;const y=t.toReflectedMethod(m,p.handle,0),g=s(t.handle,y,o.getGenericExceptionTypes);c=V(t,g).map(u),t.deleteLocalRef(g),t.deleteLocalRef(y)}else r=this._getType("void"),l=[],a=n}else{if(n.isStatic&&(i=2),r=this._getType(n.returnType||"void"),l=(n.argumentTypes||[]).map((e=>this._getType(e))),a=n.implementation,"function"!=typeof a)throw new Error("Expected a function implementation for method: "+e);const h=R(e,r,l),f=b[h];if(void 0!==f){const[e,n]=f;delete b[h],i=e.type,r=e.returnType,l=e.argumentTypes;const a=t.toReflectedMethod(n,e.handle,0),d=s(t.handle,a,o.getGenericExceptionTypes);c=V(t,d).map(u),t.deleteLocalRef(d),t.deleteLocalRef(a)}}const h=r.name,d=l.map((e=>e.name)),m="("+d.join("")+")"+h;f.push([e,h,d,c,2===i?8:0]),w.push([e,m,i,r,l,a])}));const _=Object.keys(b);if(_.length>0)throw new Error("Missing implementation for: "+_.join(", "));const S=A.fromBuffer(l(d),this);try{S.load()}finally{S.file.delete()}const C=this.use(e.name),j=$.length;if(j>0){const e=3*p,r=Memory.alloc(j*e),o=[],s=[];w.forEach((([t,n,l,a,i,c],u)=>{const h=Memory.allocUtf8String(t),f=Memory.allocUtf8String(n),d=I(t,C,l,a,i,c);r.add(u*e).writePointer(h),r.add(u*e+p).writePointer(f),r.add(u*e+2*p).writePointer(d),s.push(h,f),o.push(d)}));const l=C.$borrowClassHandle(t);n.push(l);const a=l.value;t.registerNatives(a,r,j),t.throwIfExceptionPending(),C.$nativeMethods=o}return C}finally{n.forEach((e=>{e.unref(t)}))}}choose(e,n){const r=g.getEnv(),{flavor:o}=b;if("jvm"===o)this._chooseObjectsJvm(e,r,n);else if("art"===o){const o=void 0===b["art::gc::Heap::VisitObjects"];if(o){if(void 0===b["art::gc::Heap::GetInstances"])return this._chooseObjectsJvm(e,r,n)}t.withRunnableArtThread(g,r,(t=>{o?this._chooseObjectsArtPreA12(e,r,t,n):this._chooseObjectsArtLegacy(e,r,t,n)}))}else this._chooseObjectsDalvik(e,r,n)}_chooseObjectsJvm(e,t,n){const r=this.use(e),{jvmti:o}=b,s=r.$borrowClassHandle(t),l=int64(s.value.toString());try{const e=new NativeCallback(((e,t,n,r)=>(n.writeS64(l),1)),"int",["int64","int64","pointer","pointer"]);o.iterateOverInstancesOfClass(s.value,3,e,s.value);const a=Memory.alloc(8);a.writeS64(l);const i=Memory.alloc(4),c=Memory.alloc(p);o.getObjectsWithTags(1,a,i,c,NULL);const u=i.readS32(),h=c.readPointer(),f=[];for(let e=0;e!==u;e++)f.push(h.add(e*p).readPointer());o.deallocate(h);try{for(const e of f){const t=this.cast(e,r);if("stop"===n.onMatch(t))break}n.onComplete()}finally{f.forEach((e=>{t.deleteLocalRef(e)}))}}finally{s.unref(t)}}_chooseObjectsArtPreA12(e,n,r,o){const s=this.use(e),l=t.VariableSizedHandleScope.$new(r,g);let a;const i=s.$borrowClassHandle(n);try{const e=b["art::JavaVMExt::DecodeGlobal"](b.vm,r,i.value);a=l.newHandle(e)}finally{i.unref(n)}const c=t.HandleVector.$new();b["art::gc::Heap::GetInstances"](b.artHeap,l,a,0,c);const u=c.handles.map((e=>n.newGlobalRef(e)));c.$delete(),l.$delete();try{for(const e of u){const t=this.cast(e,s);if("stop"===o.onMatch(t))break}o.onComplete()}finally{u.forEach((e=>{n.deleteGlobalRef(e)}))}}_chooseObjectsArtLegacy(e,n,r,o){const s=this.use(e),l=[],a=b["art::JavaVMExt::AddGlobalRef"],i=b.vm;let c;const u=s.$borrowClassHandle(n);try{c=b["art::JavaVMExt::DecodeGlobal"](i,r,u.value).toInt32()}finally{u.unref(n)}const h=t.makeObjectVisitorPredicate(c,(e=>{l.push(a(i,r,e))}));b["art::gc::Heap::VisitObjects"](b.artHeap,h,NULL);try{for(const e of l){const t=this.cast(e,s);if("stop"===o.onMatch(t))break}}finally{l.forEach((e=>{n.deleteGlobalRef(e)}))}o.onComplete()}_chooseObjectsDalvik(e,n,r){const o=this.use(e);if(null===b.addLocalReference){const e=Process.getModuleByName("libdvm.so");let t;switch(Process.arch){case"arm":t="2d e9 f0 41 05 46 15 4e 0c 46 7e 44 11 b3 43 68";break;case"ia32":t="8d 64 24 d4 89 5c 24 1c 89 74 24 20 e8 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 85 d2"}Memory.scan(e.base,e.size,t,{onMatch:(e,t)=>{let n;if("arm"===Process.arch)e=e.or(1),n=new NativeFunction(e,"pointer",["pointer","pointer"]);else{const t=Memory.alloc(Process.pageSize);Memory.patchCode(t,16,(n=>{const r=new X86Writer(n,{pc:t});r.putMovRegRegOffsetPtr("eax","esp",4),r.putMovRegRegOffsetPtr("edx","esp",8),r.putJmpAddress(e),r.flush()})),n=new NativeFunction(t,"pointer",["pointer","pointer"]),n._thunk=t}return b.addLocalReference=n,g.perform((e=>{s(this,e)})),"stop"},onError(e){},onComplete(){null===b.addLocalReference&&r.onComplete()}})}else s(this,n);function s(e,n){const{DVM_JNI_ENV_OFFSET_SELF:s}=t,l=n.handle.add(s).readPointer();let a;const i=o.$borrowClassHandle(n);try{a=b.dvmDecodeIndirectRef(l,i.value)}finally{i.unref(n)}const c=a.toMatchPattern(),u=b.dvmHeapSourceGetBase(),h=b.dvmHeapSourceGetLimit().sub(u).toInt32();Memory.scan(u,h,c,{onMatch:(t,n)=>{b.dvmIsValidObject(t)&&g.perform((n=>{const l=n.handle.add(s).readPointer();let a;const i=b.addLocalReference(l,t);try{a=e.cast(i,o)}finally{n.deleteLocalRef(i)}if("stop"===r.onMatch(a))return"stop"}))},onError(e){},onComplete(){r.onComplete()}})}}openClassFile(e){return new A(e,null,this)}_getType(e,t=!0){return a(e,t,this)}}function O(e,t,n,r=!0){if(null!==e)if(r){const t=n.newGlobalRef(e);this.$h=t,this.$r=Script.bindWeak(this,g.makeHandleDestructor(t))}else this.$h=e,this.$r=null;else this.$h=null,this.$r=null;return this.$t=t,new Proxy(this,$)}function L(e,t){this.value=t.newGlobalRef(e),t.deleteLocalRef(e),this.refs=1}function M(e,t){e.unref(t)}function N(e){const t=function(){const e=function(){return e.invoke(this,arguments)};return e}();return Object.setPrototypeOf(t,w),t._o=e,t}function R(e,t,n){return`${t.className} ${e}(${n.map((e=>e.className)).join(", ")})`}function H(e){const t=e._o;t.length>1&&P(t[0].methodName,t,"has more than one overload, use .overload(<signature>) to choose from:")}function P(e,t,n){const r=t.slice().sort(((e,t)=>e.argumentTypes.length-t.argumentTypes.length)).map((e=>e.argumentTypes.length>0?".overload('"+e.argumentTypes.map((e=>e.className)).join("', '")+"')":".overload()"));throw new Error(`${e}(): ${n}\n\t${r.join("\n\t")}`)}function k(e,t,n,r,o,s,l,a){const i=o.type,c=s.map((e=>e.type));let u,h;return null===l&&(l=g.getEnv()),3===n?(u=l.vaMethod(i,c,a),h=l.nonvirtualVaMethod(i,c,a)):2===n?(u=l.staticVaMethod(i,c,a),h=u):(u=l.constructor(c,a),h=u),function(e){const t=function(){const e=function(){return e.invoke(this,arguments)};return e}();return Object.setPrototypeOf(t,_),t._p=e,t}([e,t,n,r,o,s,u,h])}function I(e,t,n,r,o,s,l=null){const a=new Set,i=(c=[e,t,n,r,o,s,l,a],function(){return F(arguments,c)});var c;const u=new NativeCallback(i,r.type,["pointer","pointer"].concat(o.map((e=>e.type))));return u._c=a,u}function F(t,n){const r=new e(t[0],g),[o,s,l,a,i,c,u,h]=n,f=[];let d;if(3===l){d=new(0,s.$C)(t[1],1,r,!1)}else d=s;const p=m();r.pushLocalFrame(3);let y=!0;g.link(p,r);try{let e;h.add(p),e=null!==u&&E.has(p)?u:c;const n=[],s=t.length-2;for(let e=0;e!==s;e++){const o=i[e].fromJni(t[2+e],r,!1);n.push(o),f.push(o)}const l=e.apply(d,n);if(!a.isCompatible(l))throw new Error(`Implementation for ${o} expected return value compatible with ${a.className}`);let m=a.toJni(l,r);return"pointer"===a.type&&(m=r.popLocalFrame(m),y=!1,f.push(l)),m}catch(e){const t=e.$h;return void 0!==t?r.throw(t):Script.nextTick((()=>{throw e})),a.defaultValue}finally{g.unlink(p),y&&r.popLocalFrame(NULL),h.delete(p),f.forEach((e=>{if(null===e)return;const t=e.$dispose;void 0!==t&&t.call(e)}))}}function x(e){this._p=e}$={has:(e,t)=>t in e||e.$has(t),get(e,t,n){if("string"!=typeof t||t.startsWith("$")||"class"===t)return e[t];const r=e.$find(t);return null!==r?r(n):e[t]},set:(e,t,n,r)=>(e[t]=n,!0),ownKeys:e=>e.$list(),getOwnPropertyDescriptor:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?Object.getOwnPropertyDescriptor(e,t):{writable:!1,configurable:!0,enumerable:!0}},Object.defineProperties(O.prototype,{[Symbol.for("new")]:{enumerable:!1,get(){return this.$getCtor("allocAndInit")}},$new:{enumerable:!0,get(){return this[Symbol.for("new")]}},[Symbol.for("alloc")]:{enumerable:!1,value(){const e=g.getEnv(),t=this.$borrowClassHandle(e);try{const n=e.allocObject(t.value);return this.$f.cast(n,this)}finally{t.unref(e)}}},$alloc:{enumerable:!0,get(){return this[Symbol.for("alloc")]}},[Symbol.for("init")]:{enumerable:!1,get(){return this.$getCtor("initOnly")}},$init:{enumerable:!0,get(){return this[Symbol.for("init")]}},[Symbol.for("dispose")]:{enumerable:!1,value(){const e=this.$r;null!==e&&(this.$r=null,Script.unbindWeak(e)),null!==this.$h&&(this.$h=void 0)}},$dispose:{enumerable:!0,get(){return this[Symbol.for("dispose")]}},[Symbol.for("clone")]:{enumerable:!1,value(e){return new(0,this.$C)(this.$h,this.$t,e)}},$clone:{value(e){return this[Symbol.for("clone")](e)}},[Symbol.for("class")]:{enumerable:!1,get(){const e=g.getEnv(),t=this.$borrowClassHandle(e);try{const n=this.$f;return n.cast(t.value,n.use("java.lang.Class"))}finally{t.unref(e)}}},class:{enumerable:!0,get(){return this[Symbol.for("class")]}},[Symbol.for("className")]:{enumerable:!1,get(){const e=this.$h;return null===e?this.$n:g.getEnv().getObjectClassName(e)}},$className:{enumerable:!0,get(){return this[Symbol.for("className")]}},[Symbol.for("ownMembers")]:{enumerable:!1,get(){return this.$l.list()}},$ownMembers:{enumerable:!0,get(){return this[Symbol.for("ownMembers")]}},[Symbol.for("super")]:{enumerable:!1,get(){const e=g.getEnv();return new(0,this.$s.$C)(this.$h,2,e)}},$super:{enumerable:!0,get(){return this[Symbol.for("super")]}},[Symbol.for("s")]:{enumerable:!1,get(){const e=Object.getPrototypeOf(this);let t=e.$_s;if(void 0===t){const r=g.getEnv(),o=this.$borrowClassHandle(r);try{const s=r.getSuperclass(o.value);if(s.isNull())t=null;else try{const o=r.getClassName(s),l=e.$f;if(t=l._getUsedClass(o),void 0===t)try{const e=(n=this,function(e){const t=n.$borrowClassHandle(e);try{return e.getSuperclass(t.value)}finally{t.unref(e)}});t=l._make(o,e,r)}finally{l._setUsedClass(o,t)}}finally{r.deleteLocalRef(s)}}finally{o.unref(r)}e.$_s=t}var n;return t}},$s:{get(){return this[Symbol.for("s")]}},[Symbol.for("isSameObject")]:{enumerable:!1,value(e){return g.getEnv().isSameObject(e.$h,this.$h)}},$isSameObject:{value(e){return this[Symbol.for("isSameObject")](e)}},[Symbol.for("getCtor")]:{enumerable:!1,value(e){const t=this.$c;let n=t[0];if(null===n){const e=g.getEnv(),r=this.$borrowClassHandle(e);try{n=function(e,t,n){const{$n:r,$f:o}=t,s=function(e){return e.slice(e.lastIndexOf(".")+1)}(r),l=n.javaLangClass(),a=n.javaLangReflectConstructor(),i=n.vaMethod("pointer",[]),c=n.vaMethod("uint8",[]),u=[],h=[],f=o._getType(r,!1),d=o._getType("void",!1),m=i(n.handle,e,l.getDeclaredConstructors);try{const r=n.getArrayLength(m);if(0!==r)for(let e=0;e!==r;e++){let r,l;const c=n.getObjectArrayElement(m,e);try{r=n.fromReflectedMethod(c),l=i(n.handle,c,a.getGenericParameterTypes)}finally{n.deleteLocalRef(c)}let p;try{p=V(n,l).map((e=>o._getType(e)))}finally{n.deleteLocalRef(l)}u.push(k(s,t,1,r,f,p,n)),h.push(k(s,t,3,r,d,p,n))}else{if(c(n.handle,e,l.isInterface))throw new Error("cannot instantiate an interface");const r=n.javaLangObject(),o=n.getMethodId(r,"<init>","()V");u.push(k(s,t,1,o,f,[],n)),h.push(k(s,t,3,o,d,[],n))}}finally{n.deleteLocalRef(m)}if(0===h.length)throw new Error("no supported overloads");return{allocAndInit:N(u),initOnly:N(h)}}(r.value,this.$w,e),t[0]=n}finally{r.unref(e)}}return n[e]}},$getCtor:{value(e){return this[Symbol.for("getCtor")](e)}},[Symbol.for("borrowClassHandle")]:{enumerable:!1,value(e){const t=this.$n,n=this.$f._classHandles;let r=n.get(t);return void 0===r&&(r=new L(this.$gch(e),e),n.set(t,r,e)),r.ref()}},$borrowClassHandle:{value(e){return this[Symbol.for("borrowClassHandle")](e)}},[Symbol.for("copyClassHandle")]:{enumerable:!1,value(e){const t=this.$borrowClassHandle(e);try{return e.newLocalRef(t.value)}finally{t.unref(e)}}},$copyClassHandle:{value(e){return this[Symbol.for("copyClassHandle")](e)}},[Symbol.for("getHandle")]:{enumerable:!1,value(e){const t=this.$h;if(void 0===t)throw new Error("Wrapper is disposed; perhaps it was borrowed from a hook instead of calling Java.retain() to make a long-lived wrapper?");return t}},$getHandle:{value(e){return this[Symbol.for("getHandle")](e)}},[Symbol.for("list")]:{enumerable:!1,value(){const e=this.$s,t=null!==e?e.$list():[],n=this.$l;return Array.from(new Set(t.concat(n.list())))}},$list:{get(){return this[Symbol.for("list")]}},[Symbol.for("has")]:{enumerable:!1,value(e){if(this.$m.has(e))return!0;if(this.$l.has(e))return!0;const t=this.$s;return!(null===t||!t.$has(e))}},$has:{value(e){return this[Symbol.for("has")](e)}},[Symbol.for("find")]:{enumerable:!1,value(e){const t=this.$m;let n=t.get(e);if(void 0!==n)return n;const r=this.$l.find(e);if(null!==r){const o=g.getEnv(),s=this.$borrowClassHandle(o);try{n=function(e,t,n,r,o){if(t.startsWith("m"))return function(e,t,n,r,o){const{$f:s}=r,l=t.split(":").slice(1),a=o.javaLangReflectMethod(),i=o.vaMethod("pointer",[]),c=o.vaMethod("uint8",[]),u=l.map((t=>{const l="s"===t[0]?2:3,u=ptr(t.substr(1));let h;const f=[],d=o.toReflectedMethod(n,u,2===l?1:0);try{const e=!!c(o.handle,d,a.isVarArgs),t=i(o.handle,d,a.getGenericReturnType);o.throwIfExceptionPending();try{h=s._getType(o.getTypeName(t))}finally{o.deleteLocalRef(t)}const n=i(o.handle,d,a.getParameterTypes);try{const t=o.getArrayLength(n);for(let r=0;r!==t;r++){const l=o.getObjectArrayElement(n,r);let a;try{a=e&&r===t-1?o.getArrayTypeName(l):o.getTypeName(l)}finally{o.deleteLocalRef(l)}const i=s._getType(a);f.push(i)}}finally{o.deleteLocalRef(n)}}catch(e){return null}finally{o.deleteLocalRef(d)}return k(e,r,l,u,h,f,o)})).filter((e=>null!==e));if(0===u.length)throw new Error("No supported overloads");"valueOf"===e&&function(e){const{holder:t,type:n}=e[0];if(e.some((e=>e.type===n&&0===e.argumentTypes.length)))return;e.push(function(e){const t=function(){return this};return Object.setPrototypeOf(t,S),t._p=e,t}([t,n]))}(u);const h=N(u);return function(e){return h}}(e,t,n,r,o);return function(e,t,n,r,o){const s="s"===t[2]?1:2,l=ptr(t.substr(3)),{$f:a}=r;let i;const c=o.toReflectedField(n,l,1===s?1:0);try{i=o.vaMethod("pointer",[])(o.handle,c,o.javaLangReflectField().getGenericType),o.throwIfExceptionPending()}finally{o.deleteLocalRef(c)}let u,h,f;try{u=a._getType(o.getTypeName(i))}finally{o.deleteLocalRef(i)}const d=u.type;1===s?(h=o.getStaticField(d),f=o.setStaticField(d)):(h=o.getField(d),f=o.setField(d));return m=[s,u,l,h,f],function(e){return new x([e].concat(m))};var m}(0,t,n,r,o)}(e,r,s.value,this.$w,o)}finally{s.unref(o)}return t.set(e,n),n}const o=this.$s;return null!==o?o.$find(e):null}},$find:{value(e){return this[Symbol.for("find")](e)}},[Symbol.for("toJSON")]:{enumerable:!1,value(){const e=this.$n;if(null===this.$h)return`<class: ${e}>`;const t=this.$className;return e===t?`<instance: ${e}>`:`<instance: ${e}, $className: ${t}>`}},toJSON:{get(){return this[Symbol.for("toJSON")]}}}),L.prototype.ref=function(){return this.refs++,this},L.prototype.unref=function(e){0==--this.refs&&e.deleteGlobalRef(this.value)},w=Object.create(Function.prototype,{overloads:{enumerable:!0,get(){return this._o}},overload:{value(...e){const t=this._o,n=e.length,r=e.join(":");for(let e=0;e!==t.length;e++){const o=t[e],{argumentTypes:s}=o;if(s.length!==n)continue;if(s.map((e=>e.className)).join(":")===r)return o}P(this.methodName,this.overloads,"specified argument types do not match any of:")}},methodName:{enumerable:!0,get(){return this._o[0].methodName}},holder:{enumerable:!0,get(){return this._o[0].holder}},type:{enumerable:!0,get(){return this._o[0].type}},handle:{enumerable:!0,get(){return H(this),this._o[0].handle}},implementation:{enumerable:!0,get(){return H(this),this._o[0].implementation},set(e){H(this),this._o[0].implementation=e}},returnType:{enumerable:!0,get(){return H(this),this._o[0].returnType}},argumentTypes:{enumerable:!0,get(){return H(this),this._o[0].argumentTypes}},canInvokeWith:{enumerable:!0,get(e){return H(this),this._o[0].canInvokeWith}},clone:{enumerable:!0,value(e){return H(this),this._o[0].clone(e)}},invoke:{value(e,t){const n=this._o,r=null!==e.$h;for(let o=0;o!==n.length;o++){const s=n[o];if(s.canInvokeWith(t)){if(3===s.type&&!r){const t=this.methodName;if("toString"===t)return`<class: ${e.$n}>`;throw new Error(t+": cannot call instance method without an instance")}return s.apply(e,t)}}if("toString"===this.methodName)return`<class: ${e.$n}>`;P(this.methodName,this.overloads,"argument types do not match any of:")}}}),_=Object.create(Function.prototype,{methodName:{enumerable:!0,get(){return this._p[0]}},holder:{enumerable:!0,get(){return this._p[1]}},type:{enumerable:!0,get(){return this._p[2]}},handle:{enumerable:!0,get(){return this._p[3]}},implementation:{enumerable:!0,get(){const e=this._r;return void 0!==e?e:null},set(e){const t=this._p,n=t[1];if(1===t[2])throw new Error("Reimplementing $new is not possible; replace implementation of $init instead");const r=this._r;if(void 0!==r){n.$f._patchedMethods.delete(this);r._m.revert(g),this._r=void 0}if(null!==e){const[r,o,s,l,a,i]=t,c=I(r,o,s,a,i,e,this),u=f(l);c._m=u,this._r=c,u.replace(c,3===s,i,g,b),n.$f._patchedMethods.add(this)}}},returnType:{enumerable:!0,get(){return this._p[4]}},argumentTypes:{enumerable:!0,get(){return this._p[5]}},canInvokeWith:{enumerable:!0,value(e){const t=this._p[5];return e.length===t.length&&t.every(((t,n)=>t.isCompatible(e[n])))}},clone:{enumerable:!0,value(e){return k(...this._p.slice(0,6),null,e)}},invoke:{value(e,t){const n=g.getEnv(),r=this._p,o=r[2],s=r[4],l=r[5],a=this._r,i=3===o,c=t.length,u=2+c;n.pushLocalFrame(u);let h=null;try{let o,u;i?o=e.$getHandle():(h=e.$borrowClassHandle(n),o=h.value);let f=e.$t;if(void 0===a)u=r[3];else{if(u=a._m.resolveTarget(e,i,n,b),v){a._c.has(m())&&(f=2)}}const d=[n.handle,o,u];for(let e=0;e!==c;e++)d.push(l[e].toJni(t[e],n));let p;1===f?p=r[6]:(p=r[7],i&&d.splice(2,0,e.$copyClassHandle(n)));const y=p.apply(null,d);return n.throwIfExceptionPending(),s.fromJni(y,n,!0)}finally{null!==h&&h.unref(n),n.popLocalFrame(NULL)}}},toString:{enumerable:!0,value(){return`function ${this.methodName}(${this.argumentTypes.map((e=>e.className)).join(", ")}): ${this.returnType.className}`}}}),S=Object.create(Function.prototype,{methodName:{enumerable:!0,get:()=>"valueOf"},holder:{enumerable:!0,get(){return this._p[0]}},type:{enumerable:!0,get(){return this._p[1]}},handle:{enumerable:!0,get:()=>NULL},implementation:{enumerable:!0,get:()=>null,set(e){}},returnType:{enumerable:!0,get(){const e=this.holder;return e.$f.use(e.$n)}},argumentTypes:{enumerable:!0,get:()=>[]},canInvokeWith:{enumerable:!0,value:e=>0===e.length},clone:{enumerable:!0,value(e){throw new Error("Invalid operation")}}}),Object.defineProperties(x.prototype,{value:{enumerable:!0,get(){const[e,t,n,r,o]=this._p,s=g.getEnv();s.pushLocalFrame(4);let l=null;try{let a;if(2===t){if(a=e.$getHandle(),null===a)throw new Error("Cannot access an instance field without an instance")}else l=e.$borrowClassHandle(s),a=l.value;const i=o(s.handle,a,r);return s.throwIfExceptionPending(),n.fromJni(i,s,!0)}finally{null!==l&&l.unref(s),s.popLocalFrame(NULL)}},set(e){const[t,n,r,o,,s]=this._p,l=g.getEnv();l.pushLocalFrame(4);let a=null;try{let i;if(2===n){if(i=t.$getHandle(),null===i)throw new Error("Cannot access an instance field without an instance")}else a=t.$borrowClassHandle(l),i=a.value;if(!r.isCompatible(e))throw new Error(`Expected value compatible with ${r.className}`);const c=r.toJni(e,l);s(l.handle,i,o,c),l.throwIfExceptionPending()}finally{null!==a&&a.unref(l),l.popLocalFrame(NULL)}}},holder:{enumerable:!0,get(){return this._p[0]}},fieldType:{enumerable:!0,get(){return this._p[1]}},fieldReturnType:{enumerable:!0,get(){return this._p[2]}},toString:{enumerable:!0,value(){const e=`Java.Field{holder: ${this.holder}, fieldType: ${this.fieldType}, fieldReturnType: ${this.fieldReturnType}, value: ${this.value}}`;if(e.length<200)return e;return`Java.Field{\n\tholder: ${this.holder},\n\tfieldType: ${this.fieldType},\n\tfieldReturnType: ${this.fieldReturnType},\n\tvalue: ${this.value},\n}`.split("\n").map((e=>e.length>200?e.slice(0,e.indexOf(" ")+1)+"...,":e)).join("\n")}}});class A{static fromBuffer(e,t){const n=D(t),r=n.getCanonicalPath().toString(),o=new File(r,"w");return o.write(e.buffer),o.close(),function(e,t){const n=t.use("java.io.File");n.$new(e).setWritable(!1,!1)}(r,t),new A(r,n,t)}constructor(e,t,n){this.path=e,this.file=t,this._factory=n}load(){const{_factory:e}=this,{codeCacheDir:t}=e,n=e.use("dalvik.system.DexClassLoader"),r=e.use("java.io.File");let o=this.file;if(null===o&&(o=e.use("java.io.File").$new(this.path)),!o.exists())throw new Error("File not found");r.$new(t).mkdirs(),e.loader=n.$new(o.getCanonicalPath(),t,null,e.loader),g.preventDetachDueToClassLoader()}getClassNames(){const{_factory:e}=this,t=e.use("dalvik.system.DexFile"),n=D(e),r=[],o=t.loadDex(this.path,n.getCanonicalPath(),0).entries();for(;o.hasMoreElements();)r.push(o.nextElement().toString());return r}}function D(e){const{cacheDir:t,tempFileNaming:n}=e,r=e.use("java.io.File"),o=r.$new(t);return o.mkdirs(),r.createTempFile(n.prefix,n.suffix+".dex",o)}function J(e,t){const{factories:n,loaders:r,Integer:o}=y,s=o.$new(n.indexOf(e));r.put(t,s);for(let e=t.getParent();null!==e&&!r.containsKey(e);e=e.getParent())r.put(e,s)}function G(e){let t=E.get(e);void 0===t&&(t=0),t++,E.set(e,t)}function U(e){let t=E.get(e);if(void 0===t)throw new Error(`Thread ${e} is not ignored`);t--,0===t?E.delete(e):E.set(e,t)}function V(e,t){const n=[],r=e.getArrayLength(t);for(let o=0;o!==r;o++){const r=e.getObjectArrayElement(t,o);try{n.push(e.getTypeName(r))}finally{e.deleteLocalRef(r)}}return n}function W(e){const t=e.split(".");return t[t.length-1]+".java"}
✄
import{withRunnableArtThread as n,getArtClassSpec as e,getArtMethodSpec as t,getArtFieldSpec as s,getApi as a}from"./android.js";const r="#include <json-glib/json-glib.h>\n#include <string.h>\n\n#define kAccStatic 0x0008\n#define kAccConstructor 0x00010000\n\ntypedef struct _Model Model;\ntypedef struct _EnumerateMethodsContext EnumerateMethodsContext;\n\ntypedef struct _JavaApi JavaApi;\ntypedef struct _JavaClassApi JavaClassApi;\ntypedef struct _JavaMethodApi JavaMethodApi;\ntypedef struct _JavaFieldApi JavaFieldApi;\n\ntypedef struct _JNIEnv JNIEnv;\ntypedef guint8 jboolean;\ntypedef gint32 jint;\ntypedef jint jsize;\ntypedef gpointer jobject;\ntypedef jobject jclass;\ntypedef jobject jstring;\ntypedef jobject jarray;\ntypedef jarray jobjectArray;\ntypedef gpointer jfieldID;\ntypedef gpointer jmethodID;\n\ntypedef struct _jvmtiEnv jvmtiEnv;\ntypedef enum\n{\n  JVMTI_ERROR_NONE = 0\n} jvmtiError;\n\ntypedef struct _ArtApi ArtApi;\ntypedef guint32 ArtHeapReference;\ntypedef struct _ArtObject ArtObject;\ntypedef struct _ArtClass ArtClass;\ntypedef struct _ArtClassLinker ArtClassLinker;\ntypedef struct _ArtClassVisitor ArtClassVisitor;\ntypedef struct _ArtClassVisitorVTable ArtClassVisitorVTable;\ntypedef struct _ArtMethod ArtMethod;\ntypedef struct _ArtString ArtString;\n\ntypedef union _StdString StdString;\ntypedef struct _StdStringShort StdStringShort;\ntypedef struct _StdStringLong StdStringLong;\n\ntypedef void (* ArtVisitClassesFunc) (ArtClassLinker * linker, ArtClassVisitor * visitor);\ntypedef const char * (* ArtGetClassDescriptorFunc) (ArtClass * klass, StdString * storage);\ntypedef void (* ArtPrettyMethodFunc) (StdString * result, ArtMethod * method, jboolean with_signature);\n\nstruct _Model\n{\n  GHashTable * members;\n};\n\nstruct _EnumerateMethodsContext\n{\n  GPatternSpec * class_query;\n  GPatternSpec * method_query;\n  jboolean include_signature;\n  jboolean ignore_case;\n  jboolean skip_system_classes;\n  GHashTable * groups;\n};\n\nstruct _JavaClassApi\n{\n  jmethodID get_declared_methods;\n  jmethodID get_declared_fields;\n};\n\nstruct _JavaMethodApi\n{\n  jmethodID get_name;\n  jmethodID get_modifiers;\n};\n\nstruct _JavaFieldApi\n{\n  jmethodID get_name;\n  jmethodID get_modifiers;\n};\n\nstruct _JavaApi\n{\n  jvmtiEnv * jvmti;\n  JavaClassApi clazz;\n  JavaMethodApi method;\n  JavaFieldApi field;\n};\n\nstruct _JNIEnv\n{\n  gpointer * functions;\n};\n\nstruct _jvmtiEnv\n{\n  gpointer * functions;\n};\n\nstruct _ArtApi\n{\n  gboolean available;\n\n  guint class_offset_ifields;\n  guint class_offset_methods;\n  guint class_offset_sfields;\n  guint class_offset_copied_methods_offset;\n\n  guint method_size;\n  guint method_offset_access_flags;\n\n  guint field_size;\n  guint field_offset_access_flags;\n\n  guint alignment_padding;\n\n  ArtClassLinker * linker;\n  ArtVisitClassesFunc visit_classes;\n  ArtGetClassDescriptorFunc get_class_descriptor;\n  ArtPrettyMethodFunc pretty_method;\n\n  void (* free) (gpointer mem);\n};\n\nstruct _ArtObject\n{\n  ArtHeapReference klass;\n  ArtHeapReference monitor;\n};\n\nstruct _ArtClass\n{\n  ArtObject parent;\n\n  ArtHeapReference class_loader;\n};\n\nstruct _ArtClassVisitor\n{\n  ArtClassVisitorVTable * vtable;\n  gpointer user_data;\n};\n\nstruct _ArtClassVisitorVTable\n{\n  void (* reserved1) (ArtClassVisitor * self);\n  void (* reserved2) (ArtClassVisitor * self);\n  jboolean (* visit) (ArtClassVisitor * self, ArtClass * klass);\n};\n\nstruct _ArtString\n{\n  ArtObject parent;\n\n  gint32 count;\n  guint32 hash_code;\n\n  union\n  {\n    guint16 value[0];\n    guint8 value_compressed[0];\n  };\n};\n\nstruct _StdStringShort\n{\n  guint8 size;\n  gchar data[(3 * sizeof (gpointer)) - sizeof (guint8)];\n};\n\nstruct _StdStringLong\n{\n  gsize capacity;\n  gsize size;\n  gchar * data;\n};\n\nunion _StdString\n{\n  StdStringShort s;\n  StdStringLong l;\n};\n\nstatic void model_add_method (Model * self, const gchar * name, jmethodID id, jint modifiers);\nstatic void model_add_field (Model * self, const gchar * name, jfieldID id, jint modifiers);\nstatic void model_free (Model * model);\n\nstatic jboolean collect_matching_class_methods (ArtClassVisitor * self, ArtClass * klass);\nstatic gchar * finalize_method_groups_to_json (GHashTable * groups);\nstatic GPatternSpec * make_pattern_spec (const gchar * pattern, jboolean ignore_case);\nstatic gchar * class_name_from_signature (const gchar * signature);\nstatic gchar * format_method_signature (const gchar * name, const gchar * signature);\nstatic void append_type (GString * output, const gchar ** type);\n\nstatic gpointer read_art_array (gpointer object_base, guint field_offset, guint length_size, guint * length);\n\nstatic void std_string_destroy (StdString * str);\nstatic gchar * std_string_c_str (StdString * self);\n\nextern GMutex lock;\nextern GArray * models;\nextern JavaApi java_api;\nextern ArtApi art_api;\n\nvoid\ninit (void)\n{\n  g_mutex_init (&lock);\n  models = g_array_new (FALSE, FALSE, sizeof (Model *));\n}\n\nvoid\nfinalize (void)\n{\n  guint n, i;\n\n  n = models->len;\n  for (i = 0; i != n; i++)\n  {\n    Model * model = g_array_index (models, Model *, i);\n    model_free (model);\n  }\n\n  g_array_unref (models);\n  g_mutex_clear (&lock);\n}\n\nModel *\nmodel_new (jclass class_handle,\n           gpointer class_object,\n           JNIEnv * env)\n{\n  Model * model;\n  GHashTable * members;\n  jvmtiEnv * jvmti = java_api.jvmti;\n  gpointer * funcs = env->functions;\n  jmethodID (* from_reflected_method) (JNIEnv *, jobject) = funcs[7];\n  jfieldID (* from_reflected_field) (JNIEnv *, jobject) = funcs[8];\n  jobject (* to_reflected_method) (JNIEnv *, jclass, jmethodID, jboolean) = funcs[9];\n  jobject (* to_reflected_field) (JNIEnv *, jclass, jfieldID, jboolean) = funcs[12];\n  void (* delete_local_ref) (JNIEnv *, jobject) = funcs[23];\n  jobject (* call_object_method) (JNIEnv *, jobject, jmethodID, ...) = funcs[34];\n  jint (* call_int_method) (JNIEnv *, jobject, jmethodID, ...) = funcs[49];\n  const char * (* get_string_utf_chars) (JNIEnv *, jstring, jboolean *) = funcs[169];\n  void (* release_string_utf_chars) (JNIEnv *, jstring, const char *) = funcs[170];\n  jsize (* get_array_length) (JNIEnv *, jarray) = funcs[171];\n  jobject (* get_object_array_element) (JNIEnv *, jobjectArray, jsize) = funcs[173];\n  jsize n, i;\n\n  model = g_new (Model, 1);\n\n  members = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);\n  model->members = members;\n\n  if (jvmti != NULL)\n  {\n    gpointer * jf = jvmti->functions - 1;\n    jvmtiError (* deallocate) (jvmtiEnv *, void * mem) = jf[47];\n    jvmtiError (* get_class_methods) (jvmtiEnv *, jclass, jint *, jmethodID **) = jf[52];\n    jvmtiError (* get_class_fields) (jvmtiEnv *, jclass, jint *, jfieldID **) = jf[53];\n    jvmtiError (* get_field_name) (jvmtiEnv *, jclass, jfieldID, char **, char **, char **) = jf[60];\n    jvmtiError (* get_field_modifiers) (jvmtiEnv *, jclass, jfieldID, jint *) = jf[62];\n    jvmtiError (* get_method_name) (jvmtiEnv *, jmethodID, char **, char **, char **) = jf[64];\n    jvmtiError (* get_method_modifiers) (jvmtiEnv *, jmethodID, jint *) = jf[66];\n    jint method_count;\n    jmethodID * methods;\n    jint field_count;\n    jfieldID * fields;\n    char * name;\n    jint modifiers;\n\n    get_class_methods (jvmti, class_handle, &method_count, &methods);\n    for (i = 0; i != method_count; i++)\n    {\n      jmethodID method = methods[i];\n\n      get_method_name (jvmti, method, &name, NULL, NULL);\n      get_method_modifiers (jvmti, method, &modifiers);\n\n      model_add_method (model, name, method, modifiers);\n\n      deallocate (jvmti, name);\n    }\n    deallocate (jvmti, methods);\n\n    get_class_fields (jvmti, class_handle, &field_count, &fields);\n    for (i = 0; i != field_count; i++)\n    {\n      jfieldID field = fields[i];\n\n      get_field_name (jvmti, class_handle, field, &name, NULL, NULL);\n      get_field_modifiers (jvmti, class_handle, field, &modifiers);\n\n      model_add_field (model, name, field, modifiers);\n\n      deallocate (jvmti, name);\n    }\n    deallocate (jvmti, fields);\n  }\n  else if (art_api.available)\n  {\n    gpointer elements;\n    guint n, i;\n    const guint field_arrays[] = {\n      art_api.class_offset_ifields,\n      art_api.class_offset_sfields\n    };\n    guint field_array_cursor;\n    gboolean merged_fields = art_api.class_offset_sfields == 0;\n\n    elements = read_art_array (class_object, art_api.class_offset_methods, sizeof (gsize), NULL);\n    n = *(guint16 *) (class_object + art_api.class_offset_copied_methods_offset);\n    for (i = 0; i != n; i++)\n    {\n      jmethodID id;\n      guint32 access_flags;\n      jboolean is_static;\n      jobject method, name;\n      const char * name_str;\n      jint modifiers;\n\n      id = elements + (i * art_api.method_size);\n\n      access_flags = *(guint32 *) (id + art_api.method_offset_access_flags);\n      if ((access_flags & kAccConstructor) != 0)\n        continue;\n      is_static = (access_flags & kAccStatic) != 0;\n      method = to_reflected_method (env, class_handle, id, is_static);\n      name = call_object_method (env, method, java_api.method.get_name);\n      name_str = get_string_utf_chars (env, name, NULL);\n      modifiers = access_flags & 0xffff;\n\n      model_add_method (model, name_str, id, modifiers);\n\n      release_string_utf_chars (env, name, name_str);\n      delete_local_ref (env, name);\n      delete_local_ref (env, method);\n    }\n\n    for (field_array_cursor = 0; field_array_cursor != G_N_ELEMENTS (field_arrays); field_array_cursor++)\n    {\n      jboolean is_static;\n\n      if (field_arrays[field_array_cursor] == 0)\n        continue;\n\n      if (!merged_fields)\n        is_static = field_array_cursor == 1;\n\n      elements = read_art_array (class_object, field_arrays[field_array_cursor], sizeof (guint32), &n);\n      for (i = 0; i != n; i++)\n      {\n        jfieldID id;\n        guint32 access_flags;\n        jobject field, name;\n        const char * name_str;\n        jint modifiers;\n\n        id = elements + (i * art_api.field_size);\n\n        access_flags = *(guint32 *) (id + art_api.field_offset_access_flags);\n        if (merged_fields)\n          is_static = (access_flags & kAccStatic) != 0;\n        field = to_reflected_field (env, class_handle, id, is_static);\n        name = call_object_method (env, field, java_api.field.get_name);\n        name_str = get_string_utf_chars (env, name, NULL);\n        modifiers = access_flags & 0xffff;\n\n        model_add_field (model, name_str, id, modifiers);\n\n        release_string_utf_chars (env, name, name_str);\n        delete_local_ref (env, name);\n        delete_local_ref (env, field);\n      }\n    }\n  }\n  else\n  {\n    jobject elements;\n\n    elements = call_object_method (env, class_handle, java_api.clazz.get_declared_methods);\n    n = get_array_length (env, elements);\n    for (i = 0; i != n; i++)\n    {\n      jobject method, name;\n      const char * name_str;\n      jmethodID id;\n      jint modifiers;\n\n      method = get_object_array_element (env, elements, i);\n      name = call_object_method (env, method, java_api.method.get_name);\n      name_str = get_string_utf_chars (env, name, NULL);\n      id = from_reflected_method (env, method);\n      modifiers = call_int_method (env, method, java_api.method.get_modifiers);\n\n      model_add_method (model, name_str, id, modifiers);\n\n      release_string_utf_chars (env, name, name_str);\n      delete_local_ref (env, name);\n      delete_local_ref (env, method);\n    }\n    delete_local_ref (env, elements);\n\n    elements = call_object_method (env, class_handle, java_api.clazz.get_declared_fields);\n    n = get_array_length (env, elements);\n    for (i = 0; i != n; i++)\n    {\n      jobject field, name;\n      const char * name_str;\n      jfieldID id;\n      jint modifiers;\n\n      field = get_object_array_element (env, elements, i);\n      name = call_object_method (env, field, java_api.field.get_name);\n      name_str = get_string_utf_chars (env, name, NULL);\n      id = from_reflected_field (env, field);\n      modifiers = call_int_method (env, field, java_api.field.get_modifiers);\n\n      model_add_field (model, name_str, id, modifiers);\n\n      release_string_utf_chars (env, name, name_str);\n      delete_local_ref (env, name);\n      delete_local_ref (env, field);\n    }\n    delete_local_ref (env, elements);\n  }\n\n  g_mutex_lock (&lock);\n  g_array_append_val (models, model);\n  g_mutex_unlock (&lock);\n\n  return model;\n}\n\nstatic void\nmodel_add_method (Model * self,\n                  const gchar * name,\n                  jmethodID id,\n                  jint modifiers)\n{\n  GHashTable * members = self->members;\n  gchar * key, type;\n  const gchar * value;\n\n  if (name[0] == '$')\n    key = g_strdup_printf (\"_%s\", name);\n  else\n    key = g_strdup (name);\n\n  type = (modifiers & kAccStatic) != 0 ? 's' : 'i';\n\n  value = g_hash_table_lookup (members, key);\n  if (value == NULL)\n    g_hash_table_insert (members, key, g_strdup_printf (\"m:%c0x%zx\", type, id));\n  else\n    g_hash_table_insert (members, key, g_strdup_printf (\"%s:%c0x%zx\", value, type, id));\n}\n\nstatic void\nmodel_add_field (Model * self,\n                 const gchar * name,\n                 jfieldID id,\n                 jint modifiers)\n{\n  GHashTable * members = self->members;\n  gchar * key, type;\n\n  if (name[0] == '$')\n    key = g_strdup_printf (\"_%s\", name);\n  else\n    key = g_strdup (name);\n  while (g_hash_table_contains (members, key))\n  {\n    gchar * new_key = g_strdup_printf (\"_%s\", key);\n    g_free (key);\n    key = new_key;\n  }\n\n  type = (modifiers & kAccStatic) != 0 ? 's' : 'i';\n\n  g_hash_table_insert (members, key, g_strdup_printf (\"f:%c0x%zx\", type, id));\n}\n\nstatic void\nmodel_free (Model * model)\n{\n  g_hash_table_unref (model->members);\n\n  g_free (model);\n}\n\ngboolean\nmodel_has (Model * self,\n           const gchar * member)\n{\n  return g_hash_table_contains (self->members, member);\n}\n\nconst gchar *\nmodel_find (Model * self,\n            const gchar * member)\n{\n  return g_hash_table_lookup (self->members, member);\n}\n\ngchar *\nmodel_list (Model * self)\n{\n  GString * result;\n  GHashTableIter iter;\n  guint i;\n  const gchar * name;\n\n  result = g_string_sized_new (128);\n\n  g_string_append_c (result, '[');\n\n  g_hash_table_iter_init (&iter, self->members);\n  for (i = 0; g_hash_table_iter_next (&iter, (gpointer *) &name, NULL); i++)\n  {\n    if (i > 0)\n      g_string_append_c (result, ',');\n\n    g_string_append_c (result, '\"');\n    g_string_append (result, name);\n    g_string_append_c (result, '\"');\n  }\n\n  g_string_append_c (result, ']');\n\n  return g_string_free (result, FALSE);\n}\n\ngchar *\nenumerate_methods_art (const gchar * class_query,\n                       const gchar * method_query,\n                       jboolean include_signature,\n                       jboolean ignore_case,\n                       jboolean skip_system_classes)\n{\n  gchar * result;\n  EnumerateMethodsContext ctx;\n  ArtClassVisitor visitor;\n  ArtClassVisitorVTable visitor_vtable = { NULL, };\n\n  ctx.class_query = make_pattern_spec (class_query, ignore_case);\n  ctx.method_query = make_pattern_spec (method_query, ignore_case);\n  ctx.include_signature = include_signature;\n  ctx.ignore_case = ignore_case;\n  ctx.skip_system_classes = skip_system_classes;\n  ctx.groups = g_hash_table_new_full (NULL, NULL, NULL, NULL);\n\n  visitor.vtable = &visitor_vtable;\n  visitor.user_data = &ctx;\n\n  visitor_vtable.visit = collect_matching_class_methods;\n\n  art_api.visit_classes (art_api.linker, &visitor);\n\n  result = finalize_method_groups_to_json (ctx.groups);\n\n  g_hash_table_unref (ctx.groups);\n  g_pattern_spec_free (ctx.method_query);\n  g_pattern_spec_free (ctx.class_query);\n\n  return result;\n}\n\nstatic jboolean\ncollect_matching_class_methods (ArtClassVisitor * self,\n                                ArtClass * klass)\n{\n  EnumerateMethodsContext * ctx = self->user_data;\n  const char * descriptor;\n  StdString descriptor_storage = { 0, };\n  gchar * class_name = NULL;\n  gchar * class_name_copy = NULL;\n  const gchar * normalized_class_name;\n  JsonBuilder * group;\n  size_t class_name_length;\n  GHashTable * seen_method_names;\n  gpointer elements;\n  guint n, i;\n\n  if (ctx->skip_system_classes && klass->class_loader == 0)\n    goto skip_class;\n\n  descriptor = art_api.get_class_descriptor (klass, &descriptor_storage);\n  if (descriptor[0] != 'L')\n    goto skip_class;\n\n  class_name = class_name_from_signature (descriptor);\n\n  if (ctx->ignore_case)\n  {\n    class_name_copy = g_utf8_strdown (class_name, -1);\n    normalized_class_name = class_name_copy;\n  }\n  else\n  {\n    normalized_class_name = class_name;\n  }\n\n  if (!g_pattern_match_string (ctx->class_query, normalized_class_name))\n    goto skip_class;\n\n  group = NULL;\n  class_name_length = strlen (class_name);\n  seen_method_names = ctx->include_signature ? NULL : g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);\n\n  elements = read_art_array (klass, art_api.class_offset_methods, sizeof (gsize), NULL);\n  n = *(guint16 *) ((gpointer) klass + art_api.class_offset_copied_methods_offset);\n  for (i = 0; i != n; i++)\n  {\n    ArtMethod * method;\n    guint32 access_flags;\n    jboolean is_constructor;\n    StdString method_name = { 0, };\n    const gchar * bare_method_name;\n    gchar * bare_method_name_copy = NULL;\n    const gchar * normalized_method_name;\n    gchar * normalized_method_name_copy = NULL;\n\n    method = elements + (i * art_api.method_size);\n\n    access_flags = *(guint32 *) ((gpointer) method + art_api.method_offset_access_flags);\n    is_constructor = (access_flags & kAccConstructor) != 0;\n\n    art_api.pretty_method (&method_name, method, ctx->include_signature);\n    bare_method_name = std_string_c_str (&method_name);\n    if (ctx->include_signature)\n    {\n      const gchar * return_type_end, * name_begin;\n      GString * name;\n\n      return_type_end = strchr (bare_method_name, ' ');\n      name_begin = return_type_end + 1 + class_name_length + 1;\n      if (is_constructor && g_str_has_prefix (name_begin, \"<clinit>\"))\n        goto skip_method;\n\n      name = g_string_sized_new (64);\n\n      if (is_constructor)\n      {\n        g_string_append (name, \"$init\");\n        g_string_append (name, strchr (name_begin, '>') + 1);\n      }\n      else\n      {\n        g_string_append (name, name_begin);\n      }\n      g_string_append (name, \": \");\n      g_string_append_len (name, bare_method_name, return_type_end - bare_method_name);\n\n      bare_method_name_copy = g_string_free (name, FALSE);\n      bare_method_name = bare_method_name_copy;\n    }\n    else\n    {\n      const gchar * name_begin;\n\n      name_begin = bare_method_name + class_name_length + 1;\n      if (is_constructor && strcmp (name_begin, \"<clinit>\") == 0)\n        goto skip_method;\n\n      if (is_constructor)\n        bare_method_name = \"$init\";\n      else\n        bare_method_name += class_name_length + 1;\n    }\n\n    if (seen_method_names != NULL && g_hash_table_contains (seen_method_names, bare_method_name))\n      goto skip_method;\n\n    if (ctx->ignore_case)\n    {\n      normalized_method_name_copy = g_utf8_strdown (bare_method_name, -1);\n      normalized_method_name = normalized_method_name_copy;\n    }\n    else\n    {\n      normalized_method_name = bare_method_name;\n    }\n\n    if (!g_pattern_match_string (ctx->method_query, normalized_method_name))\n      goto skip_method;\n\n    if (group == NULL)\n    {\n      group = g_hash_table_lookup (ctx->groups, GUINT_TO_POINTER (klass->class_loader));\n      if (group == NULL)\n      {\n        group = json_builder_new_immutable ();\n        g_hash_table_insert (ctx->groups, GUINT_TO_POINTER (klass->class_loader), group);\n\n        json_builder_begin_object (group);\n\n        json_builder_set_member_name (group, \"loader\");\n        json_builder_add_int_value (group, klass->class_loader);\n\n        json_builder_set_member_name (group, \"classes\");\n        json_builder_begin_array (group);\n      }\n\n      json_builder_begin_object (group);\n\n      json_builder_set_member_name (group, \"name\");\n      json_builder_add_string_value (group, class_name);\n\n      json_builder_set_member_name (group, \"methods\");\n      json_builder_begin_array (group);\n    }\n\n    json_builder_add_string_value (group, bare_method_name);\n\n    if (seen_method_names != NULL)\n      g_hash_table_add (seen_method_names, g_strdup (bare_method_name));\n\nskip_method:\n    g_free (normalized_method_name_copy);\n    g_free (bare_method_name_copy);\n    std_string_destroy (&method_name);\n  }\n\n  if (seen_method_names != NULL)\n    g_hash_table_unref (seen_method_names);\n\n  if (group == NULL)\n    goto skip_class;\n\n  json_builder_end_array (group);\n  json_builder_end_object (group);\n\nskip_class:\n  g_free (class_name_copy);\n  g_free (class_name);\n  std_string_destroy (&descriptor_storage);\n\n  return TRUE;\n}\n\ngchar *\nenumerate_methods_jvm (const gchar * class_query,\n                       const gchar * method_query,\n                       jboolean include_signature,\n                       jboolean ignore_case,\n                       jboolean skip_system_classes,\n                       JNIEnv * env)\n{\n  gchar * result;\n  GPatternSpec * class_pattern, * method_pattern;\n  GHashTable * groups;\n  gpointer * ef = env->functions;\n  jobject (* new_global_ref) (JNIEnv *, jobject) = ef[21];\n  void (* delete_local_ref) (JNIEnv *, jobject) = ef[23];\n  jboolean (* is_same_object) (JNIEnv *, jobject, jobject) = ef[24];\n  jvmtiEnv * jvmti = java_api.jvmti;\n  gpointer * jf = jvmti->functions - 1;\n  jvmtiError (* deallocate) (jvmtiEnv *, void * mem) = jf[47];\n  jvmtiError (* get_class_signature) (jvmtiEnv *, jclass, char **, char **) = jf[48];\n  jvmtiError (* get_class_methods) (jvmtiEnv *, jclass, jint *, jmethodID **) = jf[52];\n  jvmtiError (* get_class_loader) (jvmtiEnv *, jclass, jobject *) = jf[57];\n  jvmtiError (* get_method_name) (jvmtiEnv *, jmethodID, char **, char **, char **) = jf[64];\n  jvmtiError (* get_loaded_classes) (jvmtiEnv *, jint *, jclass **) = jf[78];\n  jint class_count, class_index;\n  jclass * classes;\n\n  class_pattern = make_pattern_spec (class_query, ignore_case);\n  method_pattern = make_pattern_spec (method_query, ignore_case);\n  groups = g_hash_table_new_full (NULL, NULL, NULL, NULL);\n\n  if (get_loaded_classes (jvmti, &class_count, &classes) != JVMTI_ERROR_NONE)\n    goto emit_results;\n\n  for (class_index = 0; class_index != class_count; class_index++)\n  {\n    jclass klass = classes[class_index];\n    jobject loader = NULL;\n    gboolean have_loader = FALSE;\n    char * signature = NULL;\n    gchar * class_name = NULL;\n    gchar * class_name_copy = NULL;\n    const gchar * normalized_class_name;\n    jint method_count, method_index;\n    jmethodID * methods = NULL;\n    JsonBuilder * group = NULL;\n    GHashTable * seen_method_names = NULL;\n\n    if (skip_system_classes)\n    {\n      if (get_class_loader (jvmti, klass, &loader) != JVMTI_ERROR_NONE)\n        goto skip_class;\n      have_loader = TRUE;\n\n      if (loader == NULL)\n        goto skip_class;\n    }\n\n    if (get_class_signature (jvmti, klass, &signature, NULL) != JVMTI_ERROR_NONE)\n      goto skip_class;\n\n    class_name = class_name_from_signature (signature);\n\n    if (ignore_case)\n    {\n      class_name_copy = g_utf8_strdown (class_name, -1);\n      normalized_class_name = class_name_copy;\n    }\n    else\n    {\n      normalized_class_name = class_name;\n    }\n\n    if (!g_pattern_match_string (class_pattern, normalized_class_name))\n      goto skip_class;\n\n    if (get_class_methods (jvmti, klass, &method_count, &methods) != JVMTI_ERROR_NONE)\n      goto skip_class;\n\n    if (!include_signature)\n      seen_method_names = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);\n\n    for (method_index = 0; method_index != method_count; method_index++)\n    {\n      jmethodID method = methods[method_index];\n      const gchar * method_name;\n      char * method_name_value = NULL;\n      char * method_signature_value = NULL;\n      gchar * method_name_copy = NULL;\n      const gchar * normalized_method_name;\n      gchar * normalized_method_name_copy = NULL;\n\n      if (get_method_name (jvmti, method, &method_name_value, include_signature ? &method_signature_value : NULL, NULL) != JVMTI_ERROR_NONE)\n        goto skip_method;\n      method_name = method_name_value;\n\n      if (method_name[0] == '<')\n      {\n        if (strcmp (method_name, \"<init>\") == 0)\n          method_name = \"$init\";\n        else if (strcmp (method_name, \"<clinit>\") == 0)\n          goto skip_method;\n      }\n\n      if (include_signature)\n      {\n        method_name_copy = format_method_signature (method_name, method_signature_value);\n        method_name = method_name_copy;\n      }\n\n      if (seen_method_names != NULL && g_hash_table_contains (seen_method_names, method_name))\n        goto skip_method;\n\n      if (ignore_case)\n      {\n        normalized_method_name_copy = g_utf8_strdown (method_name, -1);\n        normalized_method_name = normalized_method_name_copy;\n      }\n      else\n      {\n        normalized_method_name = method_name;\n      }\n\n      if (!g_pattern_match_string (method_pattern, normalized_method_name))\n        goto skip_method;\n\n      if (group == NULL)\n      {\n        if (!have_loader && get_class_loader (jvmti, klass, &loader) != JVMTI_ERROR_NONE)\n          goto skip_method;\n\n        if (loader == NULL)\n        {\n          group = g_hash_table_lookup (groups, NULL);\n        }\n        else\n        {\n          GHashTableIter iter;\n          jobject cur_loader;\n          JsonBuilder * cur_group;\n\n          g_hash_table_iter_init (&iter, groups);\n          while (g_hash_table_iter_next (&iter, (gpointer *) &cur_loader, (gpointer *) &cur_group))\n          {\n            if (cur_loader != NULL && is_same_object (env, cur_loader, loader))\n            {\n              group = cur_group;\n              break;\n            }\n          }\n        }\n\n        if (group == NULL)\n        {\n          jobject l;\n          gchar * str;\n\n          l = (loader != NULL) ? new_global_ref (env, loader) : NULL;\n\n          group = json_builder_new_immutable ();\n          g_hash_table_insert (groups, l, group);\n\n          json_builder_begin_object (group);\n\n          json_builder_set_member_name (group, \"loader\");\n          str = g_strdup_printf (\"0x%\" G_GSIZE_MODIFIER \"x\", GPOINTER_TO_SIZE (l));\n          json_builder_add_string_value (group, str);\n          g_free (str);\n\n          json_builder_set_member_name (group, \"classes\");\n          json_builder_begin_array (group);\n        }\n\n        json_builder_begin_object (group);\n\n        json_builder_set_member_name (group, \"name\");\n        json_builder_add_string_value (group, class_name);\n\n        json_builder_set_member_name (group, \"methods\");\n        json_builder_begin_array (group);\n      }\n\n      json_builder_add_string_value (group, method_name);\n\n      if (seen_method_names != NULL)\n        g_hash_table_add (seen_method_names, g_strdup (method_name));\n\nskip_method:\n      g_free (normalized_method_name_copy);\n      g_free (method_name_copy);\n      deallocate (jvmti, method_signature_value);\n      deallocate (jvmti, method_name_value);\n    }\n\nskip_class:\n    if (group != NULL)\n    {\n      json_builder_end_array (group);\n      json_builder_end_object (group);\n    }\n\n    if (seen_method_names != NULL)\n      g_hash_table_unref (seen_method_names);\n\n    deallocate (jvmti, methods);\n\n    g_free (class_name_copy);\n    g_free (class_name);\n    deallocate (jvmti, signature);\n\n    if (loader != NULL)\n      delete_local_ref (env, loader);\n\n    delete_local_ref (env, klass);\n  }\n\n  deallocate (jvmti, classes);\n\nemit_results:\n  result = finalize_method_groups_to_json (groups);\n\n  g_hash_table_unref (groups);\n  g_pattern_spec_free (method_pattern);\n  g_pattern_spec_free (class_pattern);\n\n  return result;\n}\n\nstatic gchar *\nfinalize_method_groups_to_json (GHashTable * groups)\n{\n  GString * result;\n  GHashTableIter iter;\n  guint i;\n  JsonBuilder * group;\n\n  result = g_string_sized_new (1024);\n\n  g_string_append_c (result, '[');\n\n  g_hash_table_iter_init (&iter, groups);\n  for (i = 0; g_hash_table_iter_next (&iter, NULL, (gpointer *) &group); i++)\n  {\n    JsonNode * root;\n    gchar * json;\n\n    if (i > 0)\n      g_string_append_c (result, ',');\n\n    json_builder_end_array (group);\n    json_builder_end_object (group);\n\n    root = json_builder_get_root (group);\n    json = json_to_string (root, FALSE);\n    g_string_append (result, json);\n    g_free (json);\n    json_node_unref (root);\n\n    g_object_unref (group);\n  }\n\n  g_string_append_c (result, ']');\n\n  return g_string_free (result, FALSE);\n}\n\nstatic GPatternSpec *\nmake_pattern_spec (const gchar * pattern,\n                   jboolean ignore_case)\n{\n  GPatternSpec * spec;\n\n  if (ignore_case)\n  {\n    gchar * str = g_utf8_strdown (pattern, -1);\n    spec = g_pattern_spec_new (str);\n    g_free (str);\n  }\n  else\n  {\n    spec = g_pattern_spec_new (pattern);\n  }\n\n  return spec;\n}\n\nstatic gchar *\nclass_name_from_signature (const gchar * descriptor)\n{\n  gchar * result, * c;\n\n  result = g_strdup (descriptor + 1);\n\n  for (c = result; *c != '\\0'; c++)\n  {\n    if (*c == '/')\n      *c = '.';\n  }\n\n  c[-1] = '\\0';\n\n  return result;\n}\n\nstatic gchar *\nformat_method_signature (const gchar * name,\n                         const gchar * signature)\n{\n  GString * sig;\n  const gchar * cursor;\n  gint arg_index;\n\n  sig = g_string_sized_new (128);\n\n  g_string_append (sig, name);\n\n  cursor = signature;\n  arg_index = -1;\n  while (TRUE)\n  {\n    const gchar c = *cursor;\n\n    if (c == '(')\n    {\n      g_string_append_c (sig, c);\n      cursor++;\n      arg_index = 0;\n    }\n    else if (c == ')')\n    {\n      g_string_append_c (sig, c);\n      cursor++;\n      break;\n    }\n    else\n    {\n      if (arg_index >= 1)\n        g_string_append (sig, \", \");\n\n      append_type (sig, &cursor);\n\n      if (arg_index != -1)\n        arg_index++;\n    }\n  }\n\n  g_string_append (sig, \": \");\n  append_type (sig, &cursor);\n\n  return g_string_free (sig, FALSE);\n}\n\nstatic void\nappend_type (GString * output,\n             const gchar ** type)\n{\n  const gchar * cursor = *type;\n\n  switch (*cursor)\n  {\n    case 'Z':\n      g_string_append (output, \"boolean\");\n      cursor++;\n      break;\n    case 'B':\n      g_string_append (output, \"byte\");\n      cursor++;\n      break;\n    case 'C':\n      g_string_append (output, \"char\");\n      cursor++;\n      break;\n    case 'S':\n      g_string_append (output, \"short\");\n      cursor++;\n      break;\n    case 'I':\n      g_string_append (output, \"int\");\n      cursor++;\n      break;\n    case 'J':\n      g_string_append (output, \"long\");\n      cursor++;\n      break;\n    case 'F':\n      g_string_append (output, \"float\");\n      cursor++;\n      break;\n    case 'D':\n      g_string_append (output, \"double\");\n      cursor++;\n      break;\n    case 'V':\n      g_string_append (output, \"void\");\n      cursor++;\n      break;\n    case 'L':\n    {\n      gchar ch;\n\n      cursor++;\n      for (; (ch = *cursor) != ';'; cursor++)\n      {\n        g_string_append_c (output, (ch != '/') ? ch : '.');\n      }\n      cursor++;\n\n      break;\n    }\n    case '[':\n      *type = cursor + 1;\n      append_type (output, type);\n      g_string_append (output, \"[]\");\n      return;\n    default:\n      g_string_append (output, \"BUG\");\n      cursor++;\n  }\n\n  *type = cursor;\n}\n\nvoid\ndealloc (gpointer mem)\n{\n  g_free (mem);\n}\n\nstatic gpointer\nread_art_array (gpointer object_base,\n                guint field_offset,\n                guint length_size,\n                guint * length)\n{\n  gpointer result, header;\n  guint n;\n\n  header = GSIZE_TO_POINTER (*(guint64 *) (object_base + field_offset));\n  if (header != NULL)\n  {\n    result = header + length_size;\n    if (length_size == sizeof (guint32))\n      n = *(guint32 *) header;\n    else\n      n = *(guint64 *) header;\n  }\n  else\n  {\n    result = NULL;\n    n = 0;\n  }\n\n  if (length != NULL)\n    *length = n;\n\n  return result;\n}\n\nstatic void\nstd_string_destroy (StdString * str)\n{\n  if ((str->l.capacity & 1) != 0)\n    art_api.free (str->l.data);\n}\n\nstatic gchar *\nstd_string_c_str (StdString * self)\n{\n  if ((self->l.capacity & 1) != 0)\n    return self->l.data;\n\n  return self->s.data;\n}\n",_=/(.+)!([^/]+)\/?([isu]+)?/;let o=null,i=null;export default class l{static build(n,e){return d(e),i(n,e,(t=>new l(o.new(n,t,e))))}static enumerateMethods(e,t,s){d(s);const a=e.match(_);if(null===a)throw new Error("Invalid query; format is: class!method -- see documentation of Java.enumerateMethods(query) for details");const r=Memory.allocUtf8String(a[1]),i=Memory.allocUtf8String(a[2]);let l=!1,c=!1,g=!1;const u=a[3];let f;if(void 0!==u&&(l=-1!==u.indexOf("s"),c=-1!==u.indexOf("i"),g=-1!==u.indexOf("u")),null!==t.jvmti){const n=o.enumerateMethodsJvm(r,i,m(l),m(c),m(g),s);try{f=JSON.parse(n.readUtf8String()).map((n=>{const e=ptr(n.loader);return n.loader=e.isNull()?null:e,n}))}finally{o.dealloc(n)}}else n(s.vm,s,(n=>{const e=o.enumerateMethodsArt(r,i,m(l),m(c),m(g));try{const s=t["art::JavaVMExt::AddGlobalRef"],{vm:a}=t;f=JSON.parse(e.readUtf8String()).map((e=>{const t=e.loader;return e.loader=0!==t?s(a,n,ptr(t)):null,e}))}finally{o.dealloc(e)}}));return f}constructor(n){this.handle=n}has(n){return 0!==o.has(this.handle,Memory.allocUtf8String(n))}find(n){return o.find(this.handle,Memory.allocUtf8String(n)).readUtf8String()}list(){const n=o.list(this.handle);try{return JSON.parse(n.readUtf8String())}finally{o.dealloc(n)}}}function d(_){null===o&&(o=function(n){const _=a(),{jvmti:o=null}=_,{pointerSize:i}=Process,l=8,d=i,c=7*i,m=l+d+c+(40+5*i),g=Memory.alloc(m),u=g.add(l),f=u.add(d),{getDeclaredMethods:h,getDeclaredFields:p}=n.javaLangClass(),j=n.javaLangReflectMethod(),b=n.javaLangReflectField();let v=f;[null!==o?o:NULL,h,p,j.getName,j.getModifiers,b.getName,b.getModifiers].forEach((n=>{v=v.writePointer(n).add(i)}));const y=f.add(c),{vm:L}=n;if("art"===_.flavor){let n;if(null!==o)n=[0,0,0,0];else{const t=e(L).offset;n=[t.ifields,t.methods,t.sfields,t.copiedMethodsOffset]}const a=t(L),r=s(L);let l=y;[1,...n,a.size,a.offset.accessFlags,r.size,r.offset.accessFlags,4294967295].forEach((n=>{l=l.writeUInt(n).add(4)})),[_.artClassLinker.address,_["art::ClassLinker::VisitClasses"],_["art::mirror::Class::GetDescriptor"],_["art::ArtMethod::PrettyMethod"],Process.getModuleByName("libc.so").getExportByName("free")].forEach(((n,e)=>{void 0===n&&(n=NULL),l=l.writePointer(n).add(i)}))}const N=new CModule(r,{lock:g,models:u,java_api:f,art_api:y}),k={exceptions:"propagate"},E={exceptions:"propagate",scheduling:"exclusive"};return{handle:N,new:new NativeFunction(N.model_new,"pointer",["pointer","pointer","pointer"],k),has:new NativeFunction(N.model_has,"bool",["pointer","pointer"],E),find:new NativeFunction(N.model_find,"pointer",["pointer","pointer"],E),list:new NativeFunction(N.model_list,"pointer",["pointer"],E),enumerateMethodsArt:new NativeFunction(N.enumerate_methods_art,"pointer",["pointer","pointer","bool","bool","bool"],k),enumerateMethodsJvm:new NativeFunction(N.enumerate_methods_jvm,"pointer",["pointer","pointer","bool","bool","bool","pointer"],k),dealloc:new NativeFunction(N.dealloc,"void",["pointer"],E)}}(_),i=function(e,t){const s=a();if("art"!==s.flavor)return c;const r=s["art::JavaVMExt::DecodeGlobal"];return function(e,s,a){let _;return n(t,s,(n=>{const s=r(t,n,e);_=a(s)})),_}}(0,_.vm))}function c(n,e,t){return t(NULL)}function m(n){return n?1:0}
✄
export default function t(t,e){this.handle=t,this.vm=e}const e=Process.pointerSize,n={pointer:34,uint8:37,int8:40,uint16:43,int16:46,int32:49,int64:52,float:55,double:58,void:61},r={pointer:64,uint8:67,int8:70,uint16:73,int16:76,int32:79,int64:82,float:85,double:88,void:91},i={pointer:114,uint8:117,int8:120,uint16:123,int16:126,int32:129,int64:132,float:135,double:138,void:141},o={pointer:95,uint8:96,int8:97,uint16:98,int16:99,int32:100,int64:101,float:102,double:103},a={pointer:104,uint8:105,int8:106,uint16:107,int16:108,int32:109,int64:110,float:111,double:112},p={pointer:145,uint8:146,int8:147,uint16:148,int16:149,int32:150,int64:151,float:152,double:153},l={pointer:154,uint8:155,int8:156,uint16:157,int16:158,int32:159,int64:160,float:161,double:162},s={exceptions:"propagate"};let c=null,h=[];function u(t){return h.push(t),t}function f(t){return null===c&&(c=t.handle.readPointer()),c}function d(t,n,r,i){let o=null;return function(){null===o&&(o=new NativeFunction(f(this).add(t*e).readPointer(),n,r,s));let a=[o];return a=a.concat.apply(a,arguments),i.apply(this,a)}}t.dispose=function(t){h.forEach(t.deleteGlobalRef,t),h=[]},t.prototype.getVersion=d(4,"int32",["pointer"],(function(t){return t(this.handle)})),t.prototype.findClass=d(6,"pointer",["pointer","pointer"],(function(t,e){const n=t(this.handle,Memory.allocUtf8String(e));return this.throwIfExceptionPending(),n})),t.prototype.throwIfExceptionPending=function(){const t=this.exceptionOccurred();if(t.isNull())return;this.exceptionClear();const e=this.newGlobalRef(t);this.deleteLocalRef(t);const n=this.vaMethod("pointer",[])(this.handle,e,this.javaLangObject().toString),r=this.stringFromJni(n);this.deleteLocalRef(n);const i=new Error(r);throw i.$h=e,Script.bindWeak(i,function(t,e){return function(){t.perform((t=>{t.deleteGlobalRef(e)}))}}(this.vm,e)),i},t.prototype.fromReflectedMethod=d(7,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.fromReflectedField=d(8,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.toReflectedMethod=d(9,"pointer",["pointer","pointer","pointer","uint8"],(function(t,e,n,r){return t(this.handle,e,n,r)})),t.prototype.getSuperclass=d(10,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.isAssignableFrom=d(11,"uint8",["pointer","pointer","pointer"],(function(t,e,n){return!!t(this.handle,e,n)})),t.prototype.toReflectedField=d(12,"pointer",["pointer","pointer","pointer","uint8"],(function(t,e,n,r){return t(this.handle,e,n,r)})),t.prototype.throw=d(13,"int32",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.exceptionOccurred=d(15,"pointer",["pointer"],(function(t){return t(this.handle)})),t.prototype.exceptionDescribe=d(16,"void",["pointer"],(function(t){t(this.handle)})),t.prototype.exceptionClear=d(17,"void",["pointer"],(function(t){t(this.handle)})),t.prototype.pushLocalFrame=d(19,"int32",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.popLocalFrame=d(20,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.newGlobalRef=d(21,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.deleteGlobalRef=d(22,"void",["pointer","pointer"],(function(t,e){t(this.handle,e)})),t.prototype.deleteLocalRef=d(23,"void",["pointer","pointer"],(function(t,e){t(this.handle,e)})),t.prototype.isSameObject=d(24,"uint8",["pointer","pointer","pointer"],(function(t,e,n){return!!t(this.handle,e,n)})),t.prototype.newLocalRef=d(25,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.allocObject=d(27,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.getObjectClass=d(31,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.isInstanceOf=d(32,"uint8",["pointer","pointer","pointer"],(function(t,e,n){return!!t(this.handle,e,n)})),t.prototype.getMethodId=d(33,"pointer",["pointer","pointer","pointer","pointer"],(function(t,e,n,r){return t(this.handle,e,Memory.allocUtf8String(n),Memory.allocUtf8String(r))})),t.prototype.getFieldId=d(94,"pointer",["pointer","pointer","pointer","pointer"],(function(t,e,n,r){return t(this.handle,e,Memory.allocUtf8String(n),Memory.allocUtf8String(r))})),t.prototype.getIntField=d(100,"int32",["pointer","pointer","pointer"],(function(t,e,n){return t(this.handle,e,n)})),t.prototype.getStaticMethodId=d(113,"pointer",["pointer","pointer","pointer","pointer"],(function(t,e,n,r){return t(this.handle,e,Memory.allocUtf8String(n),Memory.allocUtf8String(r))})),t.prototype.getStaticFieldId=d(144,"pointer",["pointer","pointer","pointer","pointer"],(function(t,e,n,r){return t(this.handle,e,Memory.allocUtf8String(n),Memory.allocUtf8String(r))})),t.prototype.getStaticIntField=d(150,"int32",["pointer","pointer","pointer"],(function(t,e,n){return t(this.handle,e,n)})),t.prototype.getStringLength=d(164,"int32",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.getStringChars=d(165,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.releaseStringChars=d(166,"void",["pointer","pointer","pointer"],(function(t,e,n){t(this.handle,e,n)})),t.prototype.newStringUtf=d(167,"pointer",["pointer","pointer"],(function(t,e){const n=Memory.allocUtf8String(e);return t(this.handle,n)})),t.prototype.getStringUtfChars=d(169,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.releaseStringUtfChars=d(170,"void",["pointer","pointer","pointer"],(function(t,e,n){t(this.handle,e,n)})),t.prototype.getArrayLength=d(171,"int32",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.newObjectArray=d(172,"pointer",["pointer","int32","pointer","pointer"],(function(t,e,n,r){return t(this.handle,e,n,r)})),t.prototype.getObjectArrayElement=d(173,"pointer",["pointer","pointer","int32"],(function(t,e,n){return t(this.handle,e,n)})),t.prototype.setObjectArrayElement=d(174,"void",["pointer","pointer","int32","pointer"],(function(t,e,n,r){t(this.handle,e,n,r)})),t.prototype.newBooleanArray=d(175,"pointer",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.newByteArray=d(176,"pointer",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.newCharArray=d(177,"pointer",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.newShortArray=d(178,"pointer",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.newIntArray=d(179,"pointer",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.newLongArray=d(180,"pointer",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.newFloatArray=d(181,"pointer",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.newDoubleArray=d(182,"pointer",["pointer","int32"],(function(t,e){return t(this.handle,e)})),t.prototype.getBooleanArrayElements=d(183,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.getByteArrayElements=d(184,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.getCharArrayElements=d(185,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.getShortArrayElements=d(186,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.getIntArrayElements=d(187,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.getLongArrayElements=d(188,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.getFloatArrayElements=d(189,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.getDoubleArrayElements=d(190,"pointer",["pointer","pointer","pointer"],(function(t,e){return t(this.handle,e,NULL)})),t.prototype.releaseBooleanArrayElements=d(191,"pointer",["pointer","pointer","pointer","int32"],(function(t,e,n){t(this.handle,e,n,2)})),t.prototype.releaseByteArrayElements=d(192,"pointer",["pointer","pointer","pointer","int32"],(function(t,e,n){t(this.handle,e,n,2)})),t.prototype.releaseCharArrayElements=d(193,"pointer",["pointer","pointer","pointer","int32"],(function(t,e,n){t(this.handle,e,n,2)})),t.prototype.releaseShortArrayElements=d(194,"pointer",["pointer","pointer","pointer","int32"],(function(t,e,n){t(this.handle,e,n,2)})),t.prototype.releaseIntArrayElements=d(195,"pointer",["pointer","pointer","pointer","int32"],(function(t,e,n){t(this.handle,e,n,2)})),t.prototype.releaseLongArrayElements=d(196,"pointer",["pointer","pointer","pointer","int32"],(function(t,e,n){t(this.handle,e,n,2)})),t.prototype.releaseFloatArrayElements=d(197,"pointer",["pointer","pointer","pointer","int32"],(function(t,e,n){t(this.handle,e,n,2)})),t.prototype.releaseDoubleArrayElements=d(198,"pointer",["pointer","pointer","pointer","int32"],(function(t,e,n){t(this.handle,e,n,2)})),t.prototype.getByteArrayRegion=d(200,"void",["pointer","pointer","int","int","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.setBooleanArrayRegion=d(207,"void",["pointer","pointer","int32","int32","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.setByteArrayRegion=d(208,"void",["pointer","pointer","int32","int32","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.setCharArrayRegion=d(209,"void",["pointer","pointer","int32","int32","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.setShortArrayRegion=d(210,"void",["pointer","pointer","int32","int32","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.setIntArrayRegion=d(211,"void",["pointer","pointer","int32","int32","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.setLongArrayRegion=d(212,"void",["pointer","pointer","int32","int32","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.setFloatArrayRegion=d(213,"void",["pointer","pointer","int32","int32","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.setDoubleArrayRegion=d(214,"void",["pointer","pointer","int32","int32","pointer"],(function(t,e,n,r,i){t(this.handle,e,n,r,i)})),t.prototype.registerNatives=d(215,"int32",["pointer","pointer","pointer","int32"],(function(t,e,n,r){return t(this.handle,e,n,r)})),t.prototype.monitorEnter=d(217,"int32",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.monitorExit=d(218,"int32",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.getDirectBufferAddress=d(230,"pointer",["pointer","pointer"],(function(t,e){return t(this.handle,e)})),t.prototype.getObjectRefType=d(232,"int32",["pointer","pointer"],(function(t,e){return t(this.handle,e)}));const y=new Map;function g(t,e,n,r){return m(this,"p",j,t,e,n,r)}function v(t,e,n,r){return m(this,"v",T,t,e,n,r)}function L(t,e,n,r){return m(this,"n",R,t,e,n,r)}function m(t,e,n,r,i,o,a){if(void 0!==a)return n(t,r,i,o,a);const p=[r,e,i].concat(o).join("|");let l=y.get(p);return void 0===l&&(l=n(t,r,i,o,s),y.set(p,l)),l}function j(t,n,r,i,o){return new NativeFunction(f(t).add(n*e).readPointer(),r,["pointer","pointer","pointer"].concat(i),o)}function T(t,n,r,i,o){return new NativeFunction(f(t).add(n*e).readPointer(),r,["pointer","pointer","pointer","..."].concat(i),o)}function R(t,n,r,i,o){return new NativeFunction(f(t).add(n*e).readPointer(),r,["pointer","pointer","pointer","pointer","..."].concat(i),o)}t.prototype.constructor=function(t,e){return v.call(this,28,"pointer",t,e)},t.prototype.vaMethod=function(t,e,r){const i=n[t];if(void 0===i)throw new Error("Unsupported type: "+t);return v.call(this,i,t,e,r)},t.prototype.nonvirtualVaMethod=function(t,e,n){const i=r[t];if(void 0===i)throw new Error("Unsupported type: "+t);return L.call(this,i,t,e,n)},t.prototype.staticVaMethod=function(t,e,n){const r=i[t];if(void 0===r)throw new Error("Unsupported type: "+t);return v.call(this,r,t,e,n)},t.prototype.getField=function(t){const e=o[t];if(void 0===e)throw new Error("Unsupported type: "+t);return g.call(this,e,t,[])},t.prototype.getStaticField=function(t){const e=p[t];if(void 0===e)throw new Error("Unsupported type: "+t);return g.call(this,e,t,[])},t.prototype.setField=function(t){const e=a[t];if(void 0===e)throw new Error("Unsupported type: "+t);return g.call(this,e,"void",[t])},t.prototype.setStaticField=function(t){const e=l[t];if(void 0===e)throw new Error("Unsupported type: "+t);return g.call(this,e,"void",[t])};let A=null;t.prototype.javaLangClass=function(){if(null===A){const t=this.findClass("java/lang/Class");try{const e=this.getMethodId.bind(this,t);A={handle:u(this.newGlobalRef(t)),getName:e("getName","()Ljava/lang/String;"),getSimpleName:e("getSimpleName","()Ljava/lang/String;"),getGenericSuperclass:e("getGenericSuperclass","()Ljava/lang/reflect/Type;"),getDeclaredConstructors:e("getDeclaredConstructors","()[Ljava/lang/reflect/Constructor;"),getDeclaredMethods:e("getDeclaredMethods","()[Ljava/lang/reflect/Method;"),getDeclaredFields:e("getDeclaredFields","()[Ljava/lang/reflect/Field;"),isArray:e("isArray","()Z"),isPrimitive:e("isPrimitive","()Z"),isInterface:e("isInterface","()Z"),getComponentType:e("getComponentType","()Ljava/lang/Class;")}}finally{this.deleteLocalRef(t)}}return A};let w=null;t.prototype.javaLangObject=function(){if(null===w){const t=this.findClass("java/lang/Object");try{const e=this.getMethodId.bind(this,t);w={handle:u(this.newGlobalRef(t)),toString:e("toString","()Ljava/lang/String;"),getClass:e("getClass","()Ljava/lang/Class;")}}finally{this.deleteLocalRef(t)}}return w};let b=null;t.prototype.javaLangReflectConstructor=function(){if(null===b){const t=this.findClass("java/lang/reflect/Constructor");try{b={getGenericParameterTypes:this.getMethodId(t,"getGenericParameterTypes","()[Ljava/lang/reflect/Type;")}}finally{this.deleteLocalRef(t)}}return b};let C=null;t.prototype.javaLangReflectMethod=function(){if(null===C){const t=this.findClass("java/lang/reflect/Method");try{const e=this.getMethodId.bind(this,t);C={getName:e("getName","()Ljava/lang/String;"),getGenericParameterTypes:e("getGenericParameterTypes","()[Ljava/lang/reflect/Type;"),getParameterTypes:e("getParameterTypes","()[Ljava/lang/Class;"),getGenericReturnType:e("getGenericReturnType","()Ljava/lang/reflect/Type;"),getGenericExceptionTypes:e("getGenericExceptionTypes","()[Ljava/lang/reflect/Type;"),getModifiers:e("getModifiers","()I"),isVarArgs:e("isVarArgs","()Z")}}finally{this.deleteLocalRef(t)}}return C};let S=null;t.prototype.javaLangReflectField=function(){if(null===S){const t=this.findClass("java/lang/reflect/Field");try{const e=this.getMethodId.bind(this,t);S={getName:e("getName","()Ljava/lang/String;"),getType:e("getType","()Ljava/lang/Class;"),getGenericType:e("getGenericType","()Ljava/lang/reflect/Type;"),getModifiers:e("getModifiers","()I"),toString:e("toString","()Ljava/lang/String;")}}finally{this.deleteLocalRef(t)}}return S};let N=null;t.prototype.javaLangReflectTypeVariable=function(){if(null===N){const t=this.findClass("java/lang/reflect/TypeVariable");try{const e=this.getMethodId.bind(this,t);N={handle:u(this.newGlobalRef(t)),getName:e("getName","()Ljava/lang/String;"),getBounds:e("getBounds","()[Ljava/lang/reflect/Type;"),getGenericDeclaration:e("getGenericDeclaration","()Ljava/lang/reflect/GenericDeclaration;")}}finally{this.deleteLocalRef(t)}}return N};let M=null;t.prototype.javaLangReflectWildcardType=function(){if(null===M){const t=this.findClass("java/lang/reflect/WildcardType");try{const e=this.getMethodId.bind(this,t);M={handle:u(this.newGlobalRef(t)),getLowerBounds:e("getLowerBounds","()[Ljava/lang/reflect/Type;"),getUpperBounds:e("getUpperBounds","()[Ljava/lang/reflect/Type;")}}finally{this.deleteLocalRef(t)}}return M};let E=null;t.prototype.javaLangReflectGenericArrayType=function(){if(null===E){const t=this.findClass("java/lang/reflect/GenericArrayType");try{E={handle:u(this.newGlobalRef(t)),getGenericComponentType:this.getMethodId(t,"getGenericComponentType","()Ljava/lang/reflect/Type;")}}finally{this.deleteLocalRef(t)}}return E};let I=null;t.prototype.javaLangReflectParameterizedType=function(){if(null===I){const t=this.findClass("java/lang/reflect/ParameterizedType");try{const e=this.getMethodId.bind(this,t);I={handle:u(this.newGlobalRef(t)),getActualTypeArguments:e("getActualTypeArguments","()[Ljava/lang/reflect/Type;"),getRawType:e("getRawType","()Ljava/lang/reflect/Type;"),getOwnerType:e("getOwnerType","()Ljava/lang/reflect/Type;")}}finally{this.deleteLocalRef(t)}}return I};let G=null;t.prototype.javaLangString=function(){if(null===G){const t=this.findClass("java/lang/String");try{G={handle:u(this.newGlobalRef(t))}}finally{this.deleteLocalRef(t)}}return G},t.prototype.getClassName=function(t){const e=this.vaMethod("pointer",[])(this.handle,t,this.javaLangClass().getName);try{return this.stringFromJni(e)}finally{this.deleteLocalRef(e)}},t.prototype.getObjectClassName=function(t){const e=this.getObjectClass(t);try{return this.getClassName(e)}finally{this.deleteLocalRef(e)}},t.prototype.getActualTypeArgument=function(t){const e=this.vaMethod("pointer",[])(this.handle,t,this.javaLangReflectParameterizedType().getActualTypeArguments);if(this.throwIfExceptionPending(),!e.isNull())try{return this.getTypeNameFromFirstTypeElement(e)}finally{this.deleteLocalRef(e)}},t.prototype.getTypeNameFromFirstTypeElement=function(t){if(!(this.getArrayLength(t)>0))return"java.lang.Object";{const e=this.getObjectArrayElement(t,0);try{return this.getTypeName(e)}finally{this.deleteLocalRef(e)}}},t.prototype.getTypeName=function(t,e){const n=this.vaMethod("pointer",[]);if(this.isInstanceOf(t,this.javaLangClass().handle))return this.getClassName(t);if(this.isInstanceOf(t,this.javaLangReflectGenericArrayType().handle))return this.getArrayTypeName(t);if(this.isInstanceOf(t,this.javaLangReflectParameterizedType().handle)){const r=n(this.handle,t,this.javaLangReflectParameterizedType().getRawType);let i;this.throwIfExceptionPending();try{i=this.getTypeName(r)}finally{this.deleteLocalRef(r)}return e&&(i+="<"+this.getActualTypeArgument(t)+">"),i}return this.isInstanceOf(t,this.javaLangReflectTypeVariable().handle)||this.isInstanceOf(t,this.javaLangReflectWildcardType().handle),"java.lang.Object"},t.prototype.getArrayTypeName=function(t){const e=this.vaMethod("pointer",[]);if(this.isInstanceOf(t,this.javaLangClass().handle))return this.getClassName(t);if(!this.isInstanceOf(t,this.javaLangReflectGenericArrayType().handle))return"[Ljava.lang.Object;";{const n=e(this.handle,t,this.javaLangReflectGenericArrayType().getGenericComponentType);this.throwIfExceptionPending();try{return"[L"+this.getTypeName(n)+";"}finally{this.deleteLocalRef(n)}}},t.prototype.stringFromJni=function(t){const e=this.getStringChars(t);if(e.isNull())throw new Error("Unable to access string");try{const n=this.getStringLength(t);return e.readUtf16String(n)}finally{this.releaseStringChars(t,e)}};
✄
import{jvmtiVersion as e,jvmtiCapabilities as t,EnvJvmti as o}from"./jvmti.js";import{parseInstructionsAt as s}from"./machine-code.js";import n from"./memoize.js";import{checkJniResult as a}from"./result.js";import i from"./vm.js";const{pointerSize:r}=Process,d={exceptions:"propagate"},l=n((function(){const e=getApi(),{version:t}=e;let o;o=t>=17?"method:early":t>=9&&t<=16?"const-method":"method:late";const s=e["Method::size"](1)*r,n=4*r,a="method:early"===o?r:0,i=n+a,d=i+4,l=d+4+8,c=l+r,_=0!==a?n:c,h=8+r,f=h+r,u="const-method"===o?r:0,p=f+u;return{getAdapterPointer:0!==u?function(e,t){return t.add(f)}:function(e,t){return e.add(_)},method:{size:s,constMethodOffset:r,methodDataOffset:2*r,methodCountersOffset:3*r,accessFlagsOffset:i,vtableIndexOffset:d,i2iEntryOffset:l,nativeFunctionOffset:s-2*r,signatureHandlerOffset:s-r},constMethod:{constantPoolOffset:8,stackmapDataOffset:h,sizeOffset:p,methodIdnumOffset:p+14},constantPool:{cacheOffset:2*r,instanceKlassOffset:3*r}}})),c=n((function(){const{version:e,createNewDefaultVtableIndices:t}=getApi(),o=E[Process.arch];if(void 0===o)throw new Error(`Missing vtable offset parser for ${Process.arch}`);const n=s(t,o,{limit:32});if(null===n)throw new Error("Unable to deduce vtable offset");return{vtableOffset:n,methodsOffset:n-7*r,memberNamesOffset:n-17*r,oopMapCacheOffset:n-(e>=10&&e<=11||e>=15?17:18)*r}})),_=n((function(){const{vtableRedefineClasses:e,redefineClassesDoIt:t,redefineClassesDoItPrologue:o,redefineClassesDoItEpilogue:s,redefineClassesOnError:n,redefineClassesAllow:a,redefineClassesDispose0:i,redefineClassesDispose1:d,"VMThread::execute":l}=getApi(),c=e.add(2*r),_=15*r,h=Memory.dup(c,_),f=new NativeCallback((()=>{}),"void",["pointer"]);let u,p,v;for(let e=0;e!==_;e+=r){const r=h.add(e),l=r.readPointer();void 0!==n&&l.equals(n)||void 0!==i&&l.equals(i)||void 0!==d&&l.equals(d)?r.writePointer(f):l.equals(t)?u=e:l.equals(o)?(p=e,r.writePointer(a)):l.equals(s)&&(v=e,r.writePointer(f))}return{execute:l,emptyCallback:f,vtable:h,vtableSize:_,doItOffset:u,prologueOffset:p,epilogueOffset:v}}));let h=null,f=!1;const u=new Map,p=new Map;export function getApi(){return null===h&&(h=function(){const n=Process.enumerateModules().filter((e=>/jvm.(dll|dylib|so)$/.test(e.name)));if(0===n.length)return null;const l=n[0],c={flavor:"jvm"},_="windows"===Process.platform?[{module:l,functions:{JNI_GetCreatedJavaVMs:["JNI_GetCreatedJavaVMs","int",["pointer","int","pointer"]],JVM_Sleep:["JVM_Sleep","void",["pointer","pointer","long"]],"VMThread::execute":["VMThread::execute","void",["pointer"]],"Method::size":["Method::size","int",["int"]],"Method::set_native_function":["Method::set_native_function","void",["pointer","pointer","int"]],"Method::clear_native_function":["Method::clear_native_function","void",["pointer"]],"Method::jmethod_id":["Method::jmethod_id","pointer",["pointer"]],"ClassLoaderDataGraph::classes_do":["ClassLoaderDataGraph::classes_do","void",["pointer"]],"NMethodSweeper::sweep_code_cache":["NMethodSweeper::sweep_code_cache","void",[]],"OopMapCache::flush_obsolete_entries":["OopMapCache::flush_obsolete_entries","void",["pointer"]]},variables:{"VM_RedefineClasses::`vftable'":function(e){this.vtableRedefineClasses=e},"VM_RedefineClasses::doit":function(e){this.redefineClassesDoIt=e},"VM_RedefineClasses::doit_prologue":function(e){this.redefineClassesDoItPrologue=e},"VM_RedefineClasses::doit_epilogue":function(e){this.redefineClassesDoItEpilogue=e},"VM_RedefineClasses::allow_nested_vm_operations":function(e){this.redefineClassesAllow=e},"NMethodSweeper::_traversals":function(e){this.traversals=e},"NMethodSweeper::_should_sweep":function(e){this.shouldSweep=e}},optionals:[]}]:[{module:l,functions:{JNI_GetCreatedJavaVMs:["JNI_GetCreatedJavaVMs","int",["pointer","int","pointer"]],_ZN6Method4sizeEb:["Method::size","int",["int"]],_ZN6Method19set_native_functionEPhb:["Method::set_native_function","void",["pointer","pointer","int"]],_ZN6Method21clear_native_functionEv:["Method::clear_native_function","void",["pointer"]],_ZN6Method24restore_unshareable_infoEP10JavaThread:["Method::restore_unshareable_info","void",["pointer","pointer"]],_ZN6Method24restore_unshareable_infoEP6Thread:["Method::restore_unshareable_info","void",["pointer","pointer"]],_ZN6Method11link_methodERK12methodHandleP10JavaThread:["Method::link_method","void",["pointer","pointer","pointer"]],_ZN6Method10jmethod_idEv:["Method::jmethod_id","pointer",["pointer"]],_ZN6Method10clear_codeEv:function(e){const t=new NativeFunction(e,"void",["pointer"],d);this["Method::clear_code"]=function(e){t(e)}},_ZN6Method10clear_codeEb:function(e){const t=new NativeFunction(e,"void",["pointer","int"],d),o=0;this["Method::clear_code"]=function(e){t(e,o)}},_ZN18VM_RedefineClasses19mark_dependent_codeEP13InstanceKlass:["VM_RedefineClasses::mark_dependent_code","void",["pointer","pointer"]],_ZN18VM_RedefineClasses20flush_dependent_codeEv:["VM_RedefineClasses::flush_dependent_code","void",[]],_ZN18VM_RedefineClasses20flush_dependent_codeEP13InstanceKlassP6Thread:["VM_RedefineClasses::flush_dependent_code","void",["pointer","pointer","pointer"]],_ZN18VM_RedefineClasses20flush_dependent_codeE19instanceKlassHandleP6Thread:["VM_RedefineClasses::flush_dependent_code","void",["pointer","pointer","pointer"]],_ZN19ResolvedMethodTable21adjust_method_entriesEPb:["ResolvedMethodTable::adjust_method_entries","void",["pointer"]],_ZN15MemberNameTable21adjust_method_entriesEP13InstanceKlassPb:["MemberNameTable::adjust_method_entries","void",["pointer","pointer","pointer"]],_ZN17ConstantPoolCache21adjust_method_entriesEPb:function(e){const t=new NativeFunction(e,"void",["pointer","pointer"],d);this["ConstantPoolCache::adjust_method_entries"]=function(e,o,s){t(e,s)}},_ZN17ConstantPoolCache21adjust_method_entriesEP13InstanceKlassPb:function(e){const t=new NativeFunction(e,"void",["pointer","pointer","pointer"],d);this["ConstantPoolCache::adjust_method_entries"]=function(e,o,s){t(e,o,s)}},_ZN20ClassLoaderDataGraph10classes_doEP12KlassClosure:["ClassLoaderDataGraph::classes_do","void",["pointer"]],_ZN20ClassLoaderDataGraph22clean_deallocate_listsEb:["ClassLoaderDataGraph::clean_deallocate_lists","void",["int"]],_ZN10JavaThread27thread_from_jni_environmentEP7JNIEnv_:["JavaThread::thread_from_jni_environment","pointer",["pointer"]],_ZN8VMThread7executeEP12VM_Operation:["VMThread::execute","void",["pointer"]],_ZN11OopMapCache22flush_obsolete_entriesEv:["OopMapCache::flush_obsolete_entries","void",["pointer"]],_ZN14NMethodSweeper11force_sweepEv:["NMethodSweeper::force_sweep","void",[]],_ZN14NMethodSweeper16sweep_code_cacheEv:["NMethodSweeper::sweep_code_cache","void",[]],_ZN14NMethodSweeper17sweep_in_progressEv:["NMethodSweeper::sweep_in_progress","bool",[]],JVM_Sleep:["JVM_Sleep","void",["pointer","pointer","long"]]},variables:{_ZN18VM_RedefineClasses14_the_class_oopE:function(e){this.redefineClass=e},_ZN18VM_RedefineClasses10_the_classE:function(e){this.redefineClass=e},_ZN18VM_RedefineClasses25AdjustCpoolCacheAndVtable8do_klassEP5Klass:function(e){this.doKlass=e},_ZN18VM_RedefineClasses22AdjustAndCleanMetadata8do_klassEP5Klass:function(e){this.doKlass=e},_ZTV18VM_RedefineClasses:function(e){this.vtableRedefineClasses=e},_ZN18VM_RedefineClasses4doitEv:function(e){this.redefineClassesDoIt=e},_ZN18VM_RedefineClasses13doit_prologueEv:function(e){this.redefineClassesDoItPrologue=e},_ZN18VM_RedefineClasses13doit_epilogueEv:function(e){this.redefineClassesDoItEpilogue=e},_ZN18VM_RedefineClassesD0Ev:function(e){this.redefineClassesDispose0=e},_ZN18VM_RedefineClassesD1Ev:function(e){this.redefineClassesDispose1=e},_ZNK18VM_RedefineClasses26allow_nested_vm_operationsEv:function(e){this.redefineClassesAllow=e},_ZNK18VM_RedefineClasses14print_on_errorEP12outputStream:function(e){this.redefineClassesOnError=e},_ZN13InstanceKlass33create_new_default_vtable_indicesEiP10JavaThread:function(e){this.createNewDefaultVtableIndices=e},_ZN13InstanceKlass33create_new_default_vtable_indicesEiP6Thread:function(e){this.createNewDefaultVtableIndices=e},_ZN19Abstract_VM_Version19jre_release_versionEv:function(e){const t=new NativeFunction(e,"pointer",[],d)().readCString();this.version=t.startsWith("1.8")?8:t.startsWith("9.")?9:parseInt(t.slice(0,2),10),this.versionS=t},_ZN14NMethodSweeper11_traversalsE:function(e){this.traversals=e},_ZN14NMethodSweeper21_sweep_fractions_leftE:function(e){this.fractions=e},_ZN14NMethodSweeper13_should_sweepE:function(e){this.shouldSweep=e}},optionals:["_ZN6Method24restore_unshareable_infoEP10JavaThread","_ZN6Method24restore_unshareable_infoEP6Thread","_ZN6Method11link_methodERK12methodHandleP10JavaThread","_ZN6Method10clear_codeEv","_ZN6Method10clear_codeEb","_ZN18VM_RedefineClasses19mark_dependent_codeEP13InstanceKlass","_ZN18VM_RedefineClasses20flush_dependent_codeEv","_ZN18VM_RedefineClasses20flush_dependent_codeEP13InstanceKlassP6Thread","_ZN18VM_RedefineClasses20flush_dependent_codeE19instanceKlassHandleP6Thread","_ZN19ResolvedMethodTable21adjust_method_entriesEPb","_ZN15MemberNameTable21adjust_method_entriesEP13InstanceKlassPb","_ZN17ConstantPoolCache21adjust_method_entriesEPb","_ZN17ConstantPoolCache21adjust_method_entriesEP13InstanceKlassPb","_ZN20ClassLoaderDataGraph22clean_deallocate_listsEb","_ZN10JavaThread27thread_from_jni_environmentEP7JNIEnv_","_ZN14NMethodSweeper11force_sweepEv","_ZN14NMethodSweeper17sweep_in_progressEv","_ZN18VM_RedefineClasses14_the_class_oopE","_ZN18VM_RedefineClasses10_the_classE","_ZN18VM_RedefineClasses25AdjustCpoolCacheAndVtable8do_klassEP5Klass","_ZN18VM_RedefineClasses22AdjustAndCleanMetadata8do_klassEP5Klass","_ZN18VM_RedefineClassesD0Ev","_ZN18VM_RedefineClassesD1Ev","_ZNK18VM_RedefineClasses14print_on_errorEP12outputStream","_ZN13InstanceKlass33create_new_default_vtable_indicesEiP10JavaThread","_ZN13InstanceKlass33create_new_default_vtable_indicesEiP6Thread","_ZN14NMethodSweeper21_sweep_fractions_leftE"]}],h=[];if(_.forEach((function(e){const t=e.module,o=e.functions||{},s=e.variables||{},n=new Set(e.optionals||[]),a=t.enumerateExports().reduce((function(e,t){return e[t.name]=t,e}),{}),i=t.enumerateSymbols().reduce((function(e,t){return e[t.name]=t,e}),a);Object.keys(o).forEach((function(e){const t=i[e];if(void 0!==t){const s=o[e];"function"==typeof s?s.call(c,t.address):c[s[0]]=new NativeFunction(t.address,s[1],s[2],d)}else n.has(e)||h.push(e)})),Object.keys(s).forEach((function(e){const t=i[e];if(void 0!==t){s[e].call(c,t.address)}else n.has(e)||h.push(e)}))})),h.length>0)throw new Error("Java API only partially available; please file a bug. Missing: "+h.join(", "));const f=Memory.alloc(r),u=Memory.alloc(4);if(a("JNI_GetCreatedJavaVMs",c.JNI_GetCreatedJavaVMs(f,1,u)),0===u.readInt())return null;c.vm=f.readPointer();const p="windows"===Process.platform?{$new:["??2@YAPEAX_K@Z","pointer",["ulong"]],$delete:["??3@YAXPEAX@Z","void",["pointer"]]}:{$new:["_Znwm","pointer",["ulong"]],$delete:["_ZdlPv","void",["pointer"]]};for(const[e,[t,o,s]]of Object.entries(p)){let n=Module.findGlobalExportByName(t);if(null===n&&(n=DebugSymbol.fromName(t).address,n.isNull()))throw new Error(`unable to find C++ allocator API, missing: '${t}'`);c[e]=new NativeFunction(n,o,s,d)}c.jvmti=function(s){const n=new i(s);let r;return n.perform((()=>{const s=n.tryGetEnvHandle(e.v1_0);if(null===s)throw new Error("JVMTI not available");r=new o(s,n);const i=Memory.alloc(8);i.writeU64(t.canTagObjects);const d=r.addCapabilities(i);a("getEnvJvmti::AddCapabilities",d)})),r}(c),void 0===c["JavaThread::thread_from_jni_environment"]&&(c["JavaThread::thread_from_jni_environment"]=function(e){let t=null;const o=v[Process.arch];if(void 0!==o){const n=new i(e).perform((e=>e.handle.readPointer().add(6*r).readPointer()));t=s(n,o,{limit:11})}if(null===t)return()=>{throw new Error("Unable to make thread_from_jni_environment() helper for the current architecture")};return e=>e.add(t)}(c));return c}()),h}const v={x64:function(e){if("lea"!==e.mnemonic)return null;const{base:t,disp:o}=e.operands[1].value;if(!("rdi"===t&&o<0))return null;return o}};export function ensureClassInitialized(e,t){}class m{constructor(e){this.methodId=e,this.method=e.readPointer(),this.originalMethod=null,this.newMethod=null,this.resolved=null,this.impl=null,this.key=e.toString(16)}replace(e,t,o,s,n){const{key:a}=this,i=p.get(a);void 0!==i&&(p.delete(a),this.method=i.method,this.originalMethod=i.originalMethod,this.newMethod=i.newMethod,this.resolved=i.resolved),this.impl=e,u.set(a,this),M(s)}revert(e){const{key:t}=this;u.delete(t),p.set(t,this),M(e)}resolveTarget(e,t,o,s){const{resolved:n,originalMethod:a,methodId:i}=this;if(null!==n)return n;if(null===a)return i;a.oldMethod.vtableIndexPtr.writeS32(-2);const d=Memory.alloc(r);return d.writePointer(this.method),this.resolved=d,d}}function M(e){f||(f=!0,Script.nextTick(N,e))}function N(e){const t=new Map(u),o=new Map(p);u.clear(),p.clear(),f=!1,e.perform((e=>{const s=getApi(),n=s["JavaThread::thread_from_jni_environment"](e.handle);let a=!1;w((()=>{t.forEach((e=>{const{method:t,originalMethod:o,impl:a,methodId:i,newMethod:d}=e;null===o?(e.originalMethod=C(t),e.newMethod=function(e,t,o){const s=getApi(),n=C(e);n.constPtr.writePointer(n.const);const a=(234881280|n.accessFlags)>>>0;if(n.accessFlagsPtr.writeU32(a),n.signatureHandler.writePointer(NULL),n.adapter.writePointer(NULL),n.i2iEntry.writePointer(NULL),s["Method::clear_code"](n.method),n.dataPtr.writePointer(NULL),n.countersPtr.writePointer(NULL),n.stackmapPtr.writePointer(NULL),s["Method::clear_native_function"](n.method),s["Method::set_native_function"](n.method,t,0),s["Method::restore_unshareable_info"](n.method,o),s.version>=17){const e=Memory.alloc(2*r);e.writePointer(n.method),e.add(r).writePointer(o),s["Method::link_method"](n.method,e,o)}return n}(t,a,n),P(e.newMethod,i,n)):s["Method::set_native_function"](d.method,a,0)})),o.forEach((e=>{const{originalMethod:t,methodId:o,newMethod:s}=e;if(null!==t){!function(e){const{oldMethod:t}=e;t.accessFlagsPtr.writeU32(t.accessFlags),t.vtableIndexPtr.writeS32(t.vtableIndex)}(t);const e=t.oldMethod;e.oldMethod=s,P(e,o,n),a=!0}}))})),a&&function(e){const{fractions:t,shouldSweep:o,traversals:s,"NMethodSweeper::sweep_code_cache":n,"NMethodSweeper::sweep_in_progress":a,"NMethodSweeper::force_sweep":i,JVM_Sleep:r}=getApi();if(void 0!==i)Thread.sleep(.05),i(),Thread.sleep(.05),i();else{let i=s.readS64();const d=i+2;for(;d>i;){t.writeS32(1),r(e,NULL,50),a()||w((()=>{Thread.sleep(.05)}));0===o.readU8()&&(t.writeS32(1),n()),i=s.readS64()}}}(e.handle)}))}function w(e,t,o){const{execute:s,vtable:n,vtableSize:a,doItOffset:i,prologueOffset:d,epilogueOffset:l}=_(),c=Memory.dup(n,a),h=Memory.alloc(25*r);h.writePointer(c);const f=new NativeCallback(e,"void",["pointer"]);c.add(i).writePointer(f);let u=null;void 0!==t&&(u=new NativeCallback(t,"int",["pointer"]),c.add(d).writePointer(u));let p=null;void 0!==o&&(p=new NativeCallback(o,"void",["pointer"]),c.add(l).writePointer(p)),s(h)}export function makeMethodMangler(e){return new m(e)}function P(e,t,o){const{method:s,oldMethod:n}=e,a=getApi();e.methodsArray.add(e.methodIndex*r).writePointer(s),e.vtableIndex>=0&&e.vtable.add(e.vtableIndex*r).writePointer(s),t.writePointer(s),n.accessFlagsPtr.writeU32((196608|n.accessFlags)>>>0);const i=a["OopMapCache::flush_obsolete_entries"];if(void 0!==i){const{oopMapCache:t}=e;t.isNull()||i(t)}const d=a["VM_RedefineClasses::mark_dependent_code"],l=a["VM_RedefineClasses::flush_dependent_code"];void 0!==d?(d(NULL,e.instanceKlass),l()):l(NULL,e.instanceKlass,o);const c=Memory.alloc(1);c.writeU8(1),a["ConstantPoolCache::adjust_method_entries"](e.cache,e.instanceKlass,c);const _=Memory.alloc(3*r),h=Memory.alloc(r);h.writePointer(a.doKlass),_.writePointer(h),_.add(r).writePointer(o),_.add(2*r).writePointer(o),void 0!==a.redefineClass&&a.redefineClass.writePointer(e.instanceKlass),a["ClassLoaderDataGraph::classes_do"](_);const f=a["ResolvedMethodTable::adjust_method_entries"];if(void 0!==f)f(c);else{const{memberNames:t}=e;if(!t.isNull()){const o=a["MemberNameTable::adjust_method_entries"];void 0!==o&&o(t,e.instanceKlass,c)}}const u=a["ClassLoaderDataGraph::clean_deallocate_lists"];void 0!==u&&u(0)}function C(e){const t=l(),o=e.add(t.method.constMethodOffset).readPointer(),s=o.add(t.constMethod.sizeOffset).readS32()*r,n=Memory.alloc(s+t.method.size);Memory.copy(n,o,s);const a=n.add(s);Memory.copy(a,e,t.method.size);const i=b(a,n,s),d=b(e,o,s);return i.oldMethod=d,i}function b(e,t,o){const s=getApi(),n=l(),a=e.add(n.method.constMethodOffset),i=e.add(n.method.methodDataOffset),d=e.add(n.method.methodCountersOffset),_=e.add(n.method.accessFlagsOffset),h=_.readU32(),f=n.getAdapterPointer(e,t),u=e.add(n.method.i2iEntryOffset),p=e.add(n.method.signatureHandlerOffset),v=t.add(n.constMethod.constantPoolOffset).readPointer(),m=t.add(n.constMethod.stackmapDataOffset),M=v.add(n.constantPool.instanceKlassOffset).readPointer(),N=v.add(n.constantPool.cacheOffset).readPointer(),w=c(),P=M.add(w.methodsOffset).readPointer(),C=P.readS32(),b=P.add(r),E=t.add(n.constMethod.methodIdnumOffset).readU16(),Z=e.add(n.method.vtableIndexOffset),g=Z.readS32(),V=M.add(w.vtableOffset),I=M.add(w.oopMapCacheOffset).readPointer(),O=s.version>=10?M.add(w.memberNamesOffset).readPointer():NULL;return{method:e,methodSize:n.method.size,const:t,constSize:o,constPtr:a,dataPtr:i,countersPtr:d,stackmapPtr:m,instanceKlass:M,methodsArray:b,methodsCount:C,methodIndex:E,vtableIndex:g,vtableIndexPtr:Z,vtable:V,accessFlags:h,accessFlagsPtr:_,adapter:f,i2iEntry:u,signatureHandler:p,memberNames:O,cache:N,oopMapCache:I}}const E={x64:function(e){if("mov"!==e.mnemonic)return null;const t=e.operands[0];if("mem"!==t.type)return null;const{value:o}=t;if(1!==o.scale)return null;const{disp:s}=o;if(s<256)return null;return s+16}};export function deoptimizeEverything(e,t){}
✄
import{checkJniResult as t}from"./result.js";export const jvmtiVersion={v1_0:805371904,v1_2:805372416};export const jvmtiCapabilities={canTagObjects:1};const{pointerSize:n}=Process,e={exceptions:"propagate"};export function EnvJvmti(t,n){this.handle=t,this.vm=n,this.vtable=t.readPointer()}function i(t,i,o,r){let s=null;return function(){null===s&&(s=new NativeFunction(this.vtable.add((t-1)*n).readPointer(),i,o,e));let p=[s];return p=p.concat.apply(p,arguments),r.apply(this,p)}}EnvJvmti.prototype.deallocate=i(47,"int32",["pointer","pointer"],(function(t,n){return t(this.handle,n)})),EnvJvmti.prototype.getLoadedClasses=i(78,"int32",["pointer","pointer","pointer"],(function(n,e,i){const o=n(this.handle,e,i);t("EnvJvmti::getLoadedClasses",o)})),EnvJvmti.prototype.iterateOverInstancesOfClass=i(112,"int32",["pointer","pointer","int","pointer","pointer"],(function(n,e,i,o,r){const s=n(this.handle,e,i,o,r);t("EnvJvmti::iterateOverInstancesOfClass",s)})),EnvJvmti.prototype.getObjectsWithTags=i(114,"int32",["pointer","int","pointer","pointer","pointer","pointer"],(function(n,e,i,o,r,s){const p=n(this.handle,e,i,o,r,s);t("EnvJvmti::getObjectsWithTags",p)})),EnvJvmti.prototype.addCapabilities=i(142,"int32",["pointer","pointer"],(function(t,n){return t(this.handle,n)}));
✄
export default class t{constructor(t,e){this.items=new Map,this.capacity=t,this.destroy=e}dispose(t){const{items:e,destroy:s}=this;e.forEach((e=>{s(e,t)})),e.clear()}get(t){const{items:e}=this,s=e.get(t);return void 0!==s&&(e.delete(t),e.set(t,s)),s}set(t,e,s){const{items:i}=this,o=i.get(t);if(void 0!==o)i.delete(t),this.destroy(o,s);else if(i.size===this.capacity){const t=i.keys().next().value,e=i.get(t);i.delete(t),this.destroy(e,s)}i.set(t,e)}}
✄
export function parseInstructionsAt(t,n,{limit:r}){let l=t,e=null;for(let t=0;t!==r;t++){const t=Instruction.parse(l),r=n(t,e);if(null!==r)return r;l=t.next,e=t}return null}
✄
export default function n(n){let t=null,u=!1;return function(...e){return u||(t=n(...e),u=!0),t}}
✄
import{Buffer as t}from"buffer";const n=2,e=t.from([3,0,7,14,0]),s=t.from([0]);function o(t){const n=new r,e=Object.assign({},t);return n.addClass(e),n.build()}class r{constructor(){this.classes=[]}addClass(t){this.classes.push(t)}build(){const o=function(t){const n=new Set,e=new Set,s={},o=[],r=[],l={},u=new Set,d=new Set;function E(t,o){const r=[t].concat(o),c=r.join("|");if(void 0!==s[c])return c;n.add(t),e.add(t),o.forEach((t=>{n.add(t),e.add(t)}));const a=r.map(f).join("");return n.add(a),s[c]=[c,a,t,o],c}t.forEach((t=>{const{name:s,superClass:c,sourceFileName:a}=t;n.add("this"),n.add(s),e.add(s),n.add(c),e.add(c),n.add(a),t.interfaces.forEach((t=>{n.add(t),e.add(t)})),t.fields.forEach((s=>{const[r,c]=s;n.add(r),n.add(c),e.add(c),o.push([t.name,c,r])})),t.methods.some((([t])=>"<init>"===t))||(t.methods.unshift(["<init>","V",[]]),u.add(s)),t.methods.forEach((o=>{const[a,i,h,f=[],p]=o;n.add(a);const w=E(i,h);let L=null;if(f.length>0){const t=f.slice();t.sort(),L=t.join("|");let s=l[L];void 0===s&&(s={id:L,types:t},l[L]=s),n.add("Ldalvik/annotation/Throws;"),e.add("Ldalvik/annotation/Throws;"),f.forEach((t=>{n.add(t),e.add(t)})),n.add("value")}if(r.push([t.name,w,a,L,p]),"<init>"===a){d.add(s+"|"+w);const t=c+"|"+w;u.has(s)&&!d.has(t)&&(r.push([c,w,a,null,0]),d.add(t))}}))}));const p=Array.from(n);p.sort();const w=p.reduce(((t,n,e)=>(t[n]=e,t)),{}),L=Array.from(e).map((t=>w[t]));L.sort(c);const I=L.reduce(((t,n,e)=>(t[p[n]]=e,t)),{}),U=Object.keys(s).map((t=>s[t]));U.sort(a);const g={},m=U.map((t=>{const[,n,e,s]=t;let o;if(s.length>0){const t=s.join("|");o=g[t],void 0===o&&(o={types:s.map((t=>I[t])),offset:-1},g[t]=o)}else o=null;return[w[n],I[e],o]})),y=U.reduce(((t,n,e)=>{const[s]=n;return t[s]=e,t}),{}),v=Object.keys(g).map((t=>g[t])),j=o.map((t=>{const[n,e,s]=t;return[I[n],I[e],w[s]]}));j.sort(i);const D=r.map((t=>{const[n,e,s,o,r]=t;return[I[n],y[e],w[s],o,r]}));D.sort(h);const b=Object.keys(l).map((t=>l[t])).map((t=>({id:t.id,type:I["Ldalvik/annotation/Throws;"],value:w.value,thrownTypes:t.types.map((t=>I[t])),offset:-1}))),k=b.map((t=>({id:t.id,items:[t],offset:-1}))),C=k.reduce(((t,n,e)=>(t[n.id]=e,t)),{}),x={},F=[],S=t.map((t=>{const n=I[t.name],e=1,s=I[t.superClass];let o;const r=t.interfaces.map((t=>I[t]));if(r.length>0){r.sort(c);const t=r.join("|");o=x[t],void 0===o&&(o={types:r,offset:-1},x[t]=o)}else o=null;const a=w[t.sourceFileName],i=D.reduce(((t,e,s)=>{const[o,r,c,a,i]=e;return o===n&&t.push([s,c,a,r,i]),t}),[]);let h=null;const f=i.filter((([,,t])=>null!==t)).map((([t,,n])=>[t,k[C[n]]]));f.length>0&&(h={methods:f,offset:-1},F.push(h));const l=j.reduce(((t,e,s)=>{const[o]=e;return o===n&&t.push([s>0?1:0,1]),t}),[]),d=w["<init>"],E=i.filter((([,t])=>t===d)).map((([n,,,e])=>{if(u.has(t.name)){let t=-1;const o=D.length;for(let n=0;n!==o;n++){const[o,r,c]=D[n];if(o===s&&c===d&&r===e){t=n;break}}return[n,65537,t]}return[n,65793,-1]})),p=function(t){let n=0;return t.map((([t,e],s)=>{let o;return o=0===s?[t,e]:[t-n,e],n=t,o}))}(i.filter((([,t])=>t!==d)).map((([t,,,,n])=>[t,257|n])));return{index:n,accessFlags:e,superClassIndex:s,interfaces:o,sourceFileIndex:a,annotationsDirectory:h,classData:{instanceFields:l,constructorMethods:E,virtualMethods:p,offset:-1}}})),M=Object.keys(x).map((t=>x[t]));return{classes:S,interfaces:M,fields:j,methods:D,protos:m,parameters:v,annotationDirectories:F,annotationSets:k,throwsAnnotations:b,types:L,strings:p}}(this.classes),{classes:r,interfaces:d,fields:E,methods:p,protos:w,parameters:L,annotationDirectories:I,annotationSets:U,throwsAnnotations:g,types:m,strings:y}=o;let v=0;v+=112;const j=v,D=4*y.length;v+=D;const b=v,k=4*m.length;v+=k;const C=v,x=12*w.length;v+=x;const F=v,S=8*E.length;v+=S;const M=v,O=8*p.length;v+=O;const T=v,A=32*r.length;v+=A;const N=v,V=U.map((t=>{const n=v;return t.offset=n,v+=4+4*t.items.length,n})),q=r.reduce(((t,n)=>(n.classData.constructorMethods.forEach((n=>{const[,e,s]=n;0==(256&e)&&s>=0&&(n.push(v),t.push({offset:v,superConstructor:s}),v+=24)})),t)),[]);I.forEach((t=>{t.offset=v,v+=16+8*t.methods.length}));const z=d.map((t=>{v=u(v,4);const n=v;return t.offset=n,v+=4+2*t.types.length,n})),B=L.map((t=>{v=u(v,4);const n=v;return t.offset=n,v+=4+2*t.types.length,n})),G=[],H=y.map((n=>{const e=v,o=t.from(l(n.length)),r=t.from(n,"utf8"),c=t.concat([o,r,s]);return G.push(c),v+=c.length,e})),J=q.map((t=>{const n=v;return v+=e.length,n})),K=g.map((e=>{const s=function(e){const{thrownTypes:s}=e;return t.from([n].concat(l(e.type)).concat([1]).concat(l(e.value)).concat([28,s.length]).concat(s.reduce(((t,n)=>(t.push(24,n),t)),[])))}(e);return e.offset=v,v+=s.length,s})),P=r.map(((n,e)=>{n.classData.offset=v;const s=function(n){const{instanceFields:e,constructorMethods:s,virtualMethods:o}=n.classData,r=0;return t.from([r].concat(l(e.length)).concat(l(s.length)).concat(l(o.length)).concat(e.reduce(((t,[n,e])=>t.concat(l(n)).concat(l(e))),[])).concat(s.reduce(((t,[n,e,,s])=>t.concat(l(n)).concat(l(e)).concat(l(s||0))),[])).concat(o.reduce(((t,[n,e])=>{const s=0;return t.concat(l(n)).concat(l(e)).concat([s])}),[])))}(n);return v+=s.length,s}));v=u(v,4);const Q=v,R=d.length+L.length,W=4+(E.length>0?1:0)+2+U.length+q.length+I.length+(R>0?1:0)+1+J.length+g.length+r.length+1;v+=4+12*W;const X=v-N,Y=v,Z=t.alloc(Y);Z.write("dex\n035"),Z.writeUInt32LE(Y,32),Z.writeUInt32LE(112,36),Z.writeUInt32LE(305419896,40),Z.writeUInt32LE(0,44),Z.writeUInt32LE(0,48),Z.writeUInt32LE(Q,52),Z.writeUInt32LE(y.length,56),Z.writeUInt32LE(j,60),Z.writeUInt32LE(m.length,64),Z.writeUInt32LE(b,68),Z.writeUInt32LE(w.length,72),Z.writeUInt32LE(C,76),Z.writeUInt32LE(E.length,80),Z.writeUInt32LE(E.length>0?F:0,84),Z.writeUInt32LE(p.length,88),Z.writeUInt32LE(M,92),Z.writeUInt32LE(r.length,96),Z.writeUInt32LE(T,100),Z.writeUInt32LE(X,104),Z.writeUInt32LE(N,108),H.forEach(((t,n)=>{Z.writeUInt32LE(t,j+4*n)})),m.forEach(((t,n)=>{Z.writeUInt32LE(t,b+4*n)})),w.forEach(((t,n)=>{const[e,s,o]=t,r=C+12*n;Z.writeUInt32LE(e,r),Z.writeUInt32LE(s,r+4),Z.writeUInt32LE(null!==o?o.offset:0,r+8)})),E.forEach(((t,n)=>{const[e,s,o]=t,r=F+8*n;Z.writeUInt16LE(e,r),Z.writeUInt16LE(s,r+2),Z.writeUInt32LE(o,r+4)})),p.forEach(((t,n)=>{const[e,s,o]=t,r=M+8*n;Z.writeUInt16LE(e,r),Z.writeUInt16LE(s,r+2),Z.writeUInt32LE(o,r+4)})),r.forEach(((t,n)=>{const{interfaces:e,annotationsDirectory:s}=t,o=null!==e?e.offset:0,r=null!==s?s.offset:0,c=T+32*n;Z.writeUInt32LE(t.index,c),Z.writeUInt32LE(t.accessFlags,c+4),Z.writeUInt32LE(t.superClassIndex,c+8),Z.writeUInt32LE(o,c+12),Z.writeUInt32LE(t.sourceFileIndex,c+16),Z.writeUInt32LE(r,c+20),Z.writeUInt32LE(t.classData.offset,c+24),Z.writeUInt32LE(0,c+28)})),U.forEach(((t,n)=>{const{items:e}=t,s=V[n];Z.writeUInt32LE(e.length,s),e.forEach(((t,n)=>{Z.writeUInt32LE(t.offset,s+4+4*n)}))})),q.forEach(((t,n)=>{const{offset:e,superConstructor:s}=t;Z.writeUInt16LE(1,e),Z.writeUInt16LE(1,e+2),Z.writeUInt16LE(1,e+4),Z.writeUInt16LE(0,e+6),Z.writeUInt32LE(J[n],e+8),Z.writeUInt32LE(4,e+12),Z.writeUInt16LE(4208,e+16),Z.writeUInt16LE(s,e+18),Z.writeUInt16LE(0,e+20),Z.writeUInt16LE(14,e+22)})),I.forEach((t=>{const n=t.offset,e=t.methods.length;Z.writeUInt32LE(0,n),Z.writeUInt32LE(0,n+4),Z.writeUInt32LE(e,n+8),Z.writeUInt32LE(0,n+12),t.methods.forEach(((t,e)=>{const s=n+16+8*e,[o,r]=t;Z.writeUInt32LE(o,s),Z.writeUInt32LE(r.offset,s+4)}))})),d.forEach(((t,n)=>{const e=z[n];Z.writeUInt32LE(t.types.length,e),t.types.forEach(((t,n)=>{Z.writeUInt16LE(t,e+4+2*n)}))})),L.forEach(((t,n)=>{const e=B[n];Z.writeUInt32LE(t.types.length,e),t.types.forEach(((t,n)=>{Z.writeUInt16LE(t,e+4+2*n)}))})),G.forEach(((t,n)=>{t.copy(Z,H[n])})),J.forEach((t=>{e.copy(Z,t)})),K.forEach(((t,n)=>{t.copy(Z,g[n].offset)})),P.forEach(((t,n)=>{t.copy(Z,r[n].classData.offset)})),Z.writeUInt32LE(W,Q);const $=[[0,1,0],[1,y.length,j],[2,m.length,b],[3,w.length,C]];E.length>0&&$.push([4,E.length,F]),$.push([5,p.length,M]),$.push([6,r.length,T]),U.forEach(((t,n)=>{$.push([4099,t.items.length,V[n]])})),q.forEach((t=>{$.push([8193,1,t.offset])})),I.forEach((t=>{$.push([8198,1,t.offset])})),R>0&&$.push([4097,R,z.concat(B)[0]]),$.push([8194,y.length,H[0]]),J.forEach((t=>{$.push([8195,1,t])})),g.forEach((t=>{$.push([8196,1,t.offset])})),r.forEach((t=>{$.push([8192,1,t.classData.offset])})),$.push([4096,1,Q]),$.forEach(((t,n)=>{const[e,s,o]=t,r=Q+4+12*n;Z.writeUInt16LE(e,r),Z.writeUInt32LE(s,r+4),Z.writeUInt32LE(o,r+8)}));const _=new Checksum("sha1");return _.update(Z.slice(32)),t.from(_.getDigest()).copy(Z,12),Z.writeUInt32LE(function(t,n){let e=1,s=0;const o=t.length;for(let r=n;r<o;r++)e=(e+t[r])%65521,s=(s+e)%65521;return(s<<16|e)>>>0}(Z,12),8),Z}}function c(t,n){return t-n}function a(t,n){const[,,e,s]=t,[,,o,r]=n;if(e<o)return-1;if(e>o)return 1;const c=s.join("|"),a=r.join("|");return c<a?-1:c>a?1:0}function i(t,n){const[e,s,o]=t,[r,c,a]=n;return e!==r?e-r:o!==a?o-a:s-c}function h(t,n){const[e,s,o]=t,[r,c,a]=n;return e!==r?e-r:o!==a?o-a:s-c}function f(t){const n=t[0];return"L"===n||"["===n?"L":t}function l(t){if(t<=127)return[t];const n=[];let e=!1;do{let s=127&t;e=0!==(t>>=7),e&&(s|=128),n.push(s)}while(e);return n}function u(t,n){const e=t%n;return 0===e?t:t+n-e}export default o;
✄
export const JNI_OK=0;export function checkJniResult(e,o){if(0!==o)throw new Error(e+" failed: "+o)}
✄
import e from"./env.js";let t=null,n=null;export function initialize(e){t=e}export function getType(e,t,n){let r=getPrimitiveType(e);return null===r&&(0===e.indexOf("[")?r=getArrayType(e,t,n):("L"===e[0]&&";"===e[e.length-1]&&(e=e.substring(1,e.length-1)),r=function(e,t,n){const r=n._types[t?1:0];let i=r[e];if(void 0!==i)return i;i="java.lang.Object"===e?function(e){return{name:"Ljava/lang/Object;",type:"pointer",size:1,defaultValue:NULL,isCompatible(e){if(null===e)return!0;if(void 0===e)return!1;return!!(e.$h instanceof NativePointer)||"string"==typeof e},fromJni:(t,n,r)=>t.isNull()?null:e.cast(t,e.use("java.lang.Object"),r),toJni:(e,t)=>null===e?NULL:"string"==typeof e?t.newStringUtf(e):e.$h}}(n):function(e,t,n){let r=null,i=null,o=null;function l(){return null===r&&(r=n.use(e).class),r}function a(e){const t=l();return null===i&&(i=t.isInstance.overload("java.lang.Object")),i.call(t,e)}function s(){if(null===o){const e=l();o=n.use("java.lang.String").class.isAssignableFrom(e)}return o}return{name:makeJniObjectTypeName(e),type:"pointer",size:1,defaultValue:NULL,isCompatible(e){if(null===e)return!0;if(void 0===e)return!1;return e.$h instanceof NativePointer?a(e):"string"==typeof e&&s()},fromJni:(r,i,o)=>r.isNull()?null:s()&&t?i.stringFromJni(r):n.cast(r,n.use(e),o),toJni:(e,t)=>null===e?NULL:"string"==typeof e?t.newStringUtf(e):e.$h,toString(){return this.name}}}(e,t,n);return r[e]=i,i}(e,t,n))),Object.assign({className:e},r)}const r={boolean:{name:"Z",type:"uint8",size:1,byteSize:1,defaultValue:!1,isCompatible:e=>"boolean"==typeof e,fromJni:e=>!!e,toJni:e=>e?1:0,read:e=>e.readU8(),write(e,t){e.writeU8(t)},toString(){return this.name}},byte:{name:"B",type:"int8",size:1,byteSize:1,defaultValue:0,isCompatible:e=>Number.isInteger(e)&&e>=-128&&e<=127,fromJni:s,toJni:s,read:e=>e.readS8(),write(e,t){e.writeS8(t)},toString(){return this.name}},char:{name:"C",type:"uint16",size:1,byteSize:2,defaultValue:0,isCompatible(e){if("string"!=typeof e||1!==e.length)return!1;const t=e.charCodeAt(0);return t>=0&&t<=65535},fromJni:e=>String.fromCharCode(e),toJni:e=>e.charCodeAt(0),read:e=>e.readU16(),write(e,t){e.writeU16(t)},toString(){return this.name}},short:{name:"S",type:"int16",size:1,byteSize:2,defaultValue:0,isCompatible:e=>Number.isInteger(e)&&e>=-32768&&e<=32767,fromJni:s,toJni:s,read:e=>e.readS16(),write(e,t){e.writeS16(t)},toString(){return this.name}},int:{name:"I",type:"int32",size:1,byteSize:4,defaultValue:0,isCompatible:e=>Number.isInteger(e)&&e>=-2147483648&&e<=2147483647,fromJni:s,toJni:s,read:e=>e.readS32(),write(e,t){e.writeS32(t)},toString(){return this.name}},long:{name:"J",type:"int64",size:2,byteSize:8,defaultValue:0,isCompatible:e=>"number"==typeof e||e instanceof Int64,fromJni:s,toJni:s,read:e=>e.readS64(),write(e,t){e.writeS64(t)},toString(){return this.name}},float:{name:"F",type:"float",size:1,byteSize:4,defaultValue:0,isCompatible:e=>"number"==typeof e,fromJni:s,toJni:s,read:e=>e.readFloat(),write(e,t){e.writeFloat(t)},toString(){return this.name}},double:{name:"D",type:"double",size:2,byteSize:8,defaultValue:0,isCompatible:e=>"number"==typeof e,fromJni:s,toJni:s,read:e=>e.readDouble(),write(e,t){e.writeDouble(t)},toString(){return this.name}},void:{name:"V",type:"void",size:0,byteSize:0,defaultValue:void 0,isCompatible:e=>void 0===e,fromJni(){},toJni:()=>NULL,toString(){return this.name}}},i=new Set(Object.values(r).map((e=>e.name)));export function getPrimitiveType(e){const t=r[e];return void 0!==t?t:null}const o=[["Z","boolean"],["B","byte"],["C","char"],["D","double"],["F","float"],["I","int"],["J","long"],["S","short"]].reduce(((t,[n,r])=>(t["["+n]=function(t,n){const r=e.prototype,i=(l=n,l.charAt(0).toUpperCase()+l.slice(1)),o={typeName:n,newArray:r["new"+i+"Array"],setRegion:r["set"+i+"ArrayRegion"],getElements:r["get"+i+"ArrayElements"],releaseElements:r["release"+i+"ArrayElements"]};var l;return{name:t,type:"pointer",size:1,defaultValue:NULL,isCompatible:e=>function(e,t){if(null===e)return!0;if(e instanceof a)return e.$s.typeName===t;if("object"!=typeof e||void 0===e.length)return!1;const n=getPrimitiveType(t);return Array.prototype.every.call(e,(e=>n.isCompatible(e)))}(e,n),fromJni:(e,t,n)=>function(e,t,n,r){if(e.isNull())return null;const i=getPrimitiveType(t.typeName),o=n.getArrayLength(e);return new a(e,t,i,o,n,r)}(e,o,t,n),toJni:(e,t)=>function(e,t,n){if(null===e)return NULL;const r=e.$h;if(void 0!==r)return r;const i=e.length,o=getPrimitiveType(t.typeName),l=t.newArray.call(n,i);if(l.isNull())throw new Error("Unable to construct array");if(i>0){const r=o.byteSize,a=o.write,s=o.toJni,u=Memory.alloc(i*o.byteSize);for(let t=0;t!==i;t++)a(u.add(t*r),s(e[t]));t.setRegion.call(n,l,0,i,u),n.throwIfExceptionPending()}return l}(e,o,t)}}("["+n,r),t)),{});export function getArrayType(e,t,n){const r=o[e];if(void 0!==r)return r;if(0!==e.indexOf("["))throw new Error("Unsupported type: "+e);let a=e.substring(1);const s=getType(a,t,n);let u=0;const c=a.length;for(;u!==c&&"["===a[u];)u++;a=a.substring(u),"L"===a[0]&&";"===a[a.length-1]&&(a=a.substring(1,a.length-1));let f=a.replace(/\./g,"/");f=i.has(f)?"[".repeat(u)+f:"[".repeat(u)+"L"+f+";";const p="["+f;return a="[".repeat(u)+a,{name:e.replace(/\./g,"/"),type:"pointer",size:1,defaultValue:NULL,isCompatible:e=>null===e||"object"==typeof e&&void 0!==e.length&&e.every((function(e){return s.isCompatible(e)})),fromJni(e,t,r){if(e.isNull())return null;const i=[],o=t.getArrayLength(e);for(let n=0;n!==o;n++){const r=t.getObjectArrayElement(e,n);try{i.push(s.fromJni(r,t))}finally{t.deleteLocalRef(r)}}try{i.$w=n.cast(e,n.use(p),r)}catch(t){n.use("java.lang.reflect.Array").newInstance(n.use(a).class,0),i.$w=n.cast(e,n.use(p),r)}return i.$dispose=l,i},toJni(e,t){if(null===e)return NULL;if(!(e instanceof Array))throw new Error("Expected an array");const r=e.$w;if(void 0!==r)return r.$h;const i=e.length,o=n.use(a).$borrowClassHandle(t);try{const n=t.newObjectArray(i,o.value,NULL);t.throwIfExceptionPending();for(let r=0;r!==i;r++){const i=s.toJni(e[r],t);try{t.setObjectArrayElement(n,r,i)}finally{"pointer"===s.type&&1===t.getObjectRefType(i)&&t.deleteLocalRef(i)}t.throwIfExceptionPending()}return n}finally{o.unref(t)}}}}function l(){const e=this.length;for(let t=0;t!==e;t++){const e=this[t];if(null===e)continue;const n=e.$dispose;if(void 0===n)break;n.call(e)}this.$w.$dispose()}function a(e,t,r,i,o,l=!0){if(l){const t=o.newGlobalRef(e);this.$h=t,this.$r=Script.bindWeak(this,o.vm.makeHandleDestructor(t))}else this.$h=e,this.$r=null;return this.$s=t,this.$t=r,this.length=i,new Proxy(this,n)}n={has:(e,t)=>t in e||null!==e.tryParseIndex(t),get(e,t,n){const r=e.tryParseIndex(t);return null===r?e[t]:e.readElement(r)},set(e,t,n,r){const i=e.tryParseIndex(t);return null===i?(e[t]=n,!0):(e.writeElement(i,n),!0)},ownKeys(e){const t=[],{length:n}=e;for(let e=0;e!==n;e++){const n=e.toString();t.push(n)}return t.push("length"),t},getOwnPropertyDescriptor:(e,t)=>null!==e.tryParseIndex(t)?{writable:!0,configurable:!0,enumerable:!0}:Object.getOwnPropertyDescriptor(e,t)},Object.defineProperties(a.prototype,{$dispose:{enumerable:!0,value(){const e=this.$r;null!==e&&(this.$r=null,Script.unbindWeak(e))}},$clone:{value(e){return new a(this.$h,this.$s,this.$t,this.length,e)}},tryParseIndex:{value(e){if("symbol"==typeof e)return null;const t=parseInt(e);return isNaN(t)||t<0||t>=this.length?null:t}},readElement:{value(e){return this.withElements((t=>{const n=this.$t;return n.fromJni(n.read(t.add(e*n.byteSize)))}))}},writeElement:{value(e,n){const{$h:r,$s:i,$t:o}=this,l=t.getEnv(),a=Memory.alloc(o.byteSize);o.write(a,o.toJni(n)),i.setRegion.call(l,r,e,1,a)}},withElements:{value(e){const{$h:n,$s:r}=this,i=t.getEnv(),o=r.getElements.call(i,n);if(o.isNull())throw new Error("Unable to get array elements");try{return e(o)}finally{r.releaseElements.call(i,n,o)}}},toJSON:{value(){const{length:e,$t:t}=this,{byteSize:n,fromJni:r,read:i}=t;return this.withElements((t=>{const o=[];for(let l=0;l!==e;l++){const e=r(i(t.add(l*n)));o.push(e)}return o}))}},toString:{value(){return this.toJSON().toString()}}});export function makeJniObjectTypeName(e){return"L"+e.replace(/\./g,"/")+";"}function s(e){return e}
✄
import t from"./env.js";import{JNI_OK as e,checkJniResult as n}from"./result.js";const r=Process.pointerSize,o=Process.getCurrentThreadId(),i=new Map,s=new Map;export default function a(a){const c=a.vm;let u=null,l=null,h=null;function d(t){const e=s.get(t);return void 0===e?null:e[0]}this.handle=c,this.perform=function(t){const e=Process.getCurrentThreadId(),n=d(e);if(null!==n)return t(n);let r=this._tryGetEnv();const s=null!==r;s||(r=this.attachCurrentThread(),i.set(e,!0)),this.link(e,r);try{return t(r)}finally{const t=e===o;if(t||this.unlink(e),!s&&!t){const t=i.get(e);i.delete(e),t&&this.detachCurrentThread()}}},this.attachCurrentThread=function(){const e=Memory.alloc(r);return n("VM::AttachCurrentThread",u(c,e,NULL)),new t(e.readPointer(),this)},this.detachCurrentThread=function(){n("VM::DetachCurrentThread",l(c))},this.preventDetachDueToClassLoader=function(){const t=Process.getCurrentThreadId();i.has(t)&&i.set(t,!1)},this.getEnv=function(){const e=d(Process.getCurrentThreadId());if(null!==e)return e;const o=Memory.alloc(r),i=h(c,o,65542);if(-2===i)throw new Error("Current thread is not attached to the Java VM; please move this code inside a Java.perform() callback");return n("VM::GetEnv",i),new t(o.readPointer(),this)},this.tryGetEnv=function(){const t=d(Process.getCurrentThreadId());return null!==t?t:this._tryGetEnv()},this._tryGetEnv=function(){const e=this.tryGetEnvHandle(65542);return null===e?null:new t(e,this)},this.tryGetEnvHandle=function(t){const n=Memory.alloc(r);return h(c,n,t)!==e?null:n.readPointer()},this.makeHandleDestructor=function(t){return()=>{this.perform((e=>{e.deleteGlobalRef(t)}))}},this.link=function(t,e){const n=s.get(t);void 0===n?s.set(t,[e,1]):n[1]++},this.unlink=function(t){const e=s.get(t);1===e[1]?s.delete(t):e[1]--},function(){const t=c.readPointer(),e={exceptions:"propagate"};u=new NativeFunction(t.add(4*r).readPointer(),"int32",["pointer","pointer","pointer"],e),l=new NativeFunction(t.add(5*r).readPointer(),"int32",["pointer"],e),h=new NativeFunction(t.add(6*r).readPointer(),"int32",["pointer","pointer","int32"],e)}.call(this)}a.dispose=function(t){!0===i.get(o)&&(i.delete(o),t.detachCurrentThread())};