From b0667677b3ef180918e0d7bf52f701eea1581254 Mon Sep 17 00:00:00 2001 From: songzhengchao Date: Fri, 10 Jun 2022 15:34:35 +0800 Subject: [PATCH 001/154] Refactor FrameHandler Iterator 1 FrameHandler Ietrator only visit current Frame stackmap issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5BSW4?from=project-issue Signed-off-by: songzhengchao Change-Id: Id05e57d9dd8c00ff91c596fc2cbb1feabe3aa4da --- .../compiler/llvm/llvm_stackmap_parser.cpp | 171 +++++++----------- .../compiler/llvm/llvm_stackmap_parser.h | 14 +- ecmascript/interpreter/frame_handler.cpp | 153 +++++++--------- ecmascript/interpreter/frame_handler.h | 12 +- 4 files changed, 142 insertions(+), 208 deletions(-) diff --git a/ecmascript/compiler/llvm/llvm_stackmap_parser.cpp b/ecmascript/compiler/llvm/llvm_stackmap_parser.cpp index ef4c9c25..66ffe541 100644 --- a/ecmascript/compiler/llvm/llvm_stackmap_parser.cpp +++ b/ecmascript/compiler/llvm/llvm_stackmap_parser.cpp @@ -51,140 +51,93 @@ const CallSiteInfo* LLVMStackMapParser::GetCallSiteInfoByPc(uintptr_t callSiteAd return nullptr; } -void LLVMStackMapParser::PrintCallSiteInfo(const CallSiteInfo *infos, OptimizedLeaveFrame *frame) const +void LLVMStackMapParser::PrintCallSiteSlotAddr(const CallSiteInfo& callsiteInfo, uintptr_t callSiteSp, + uintptr_t callsiteFp) const { - if (!IsLogEnabled()) { - return; - } - - int i = 0; - uintptr_t address = 0; - uintptr_t base = 0; - uintptr_t derived = 0; - for (auto &info: *infos) { - if (info.first == GCStackMapRegisters::SP) { - uintptr_t rsp = frame->GetCallSiteSp(); - address = rsp + info.second; - COMPILER_LOG(DEBUG) << std::dec << "SP_DWARF_REG_NUM: info.second:" << info.second - << std::hex << "rsp :" << rsp; - } else if (info.first == GCStackMapRegisters::FP) { - uintptr_t fp = frame->callsiteFp; - address = fp + info.second; - COMPILER_LOG(DEBUG) << std::dec << "FP_DWARF_REG_NUM: info.second:" << info.second - << std::hex << "rfp :" << fp; - } else { - COMPILER_LOG(DEBUG) << "REG_NUM : info.first:" << info.first; - UNREACHABLE(); + ASSERT(callsiteInfo.size() % 2 == 0); + for (size_t j = 0; j < callsiteInfo.size(); j += 2) { + const DwarfRegAndOffsetType baseInfo = callsiteInfo[j]; + const DwarfRegAndOffsetType derivedInfo = callsiteInfo[j + 1]; + COMPILER_LOG(DEBUG) << std::hex << " callSiteSp:0x" << callSiteSp << " callsiteFp:" << callsiteFp; + COMPILER_LOG(DEBUG) << std::dec << "base DWARF_REG:" << baseInfo.first + << " OFFSET:" << baseInfo.second; + uintptr_t base = GetStackAddress(baseInfo, callSiteSp, callsiteFp); + uintptr_t derived = GetStackAddress(derivedInfo, callSiteSp, callsiteFp); + if (base != derived) { + COMPILER_LOG(DEBUG) << std::dec << "derived DWARF_REG:" << derivedInfo.first + << " OFFSET:" << derivedInfo.second; } - - if (IsDeriveredPointer(i)) { - derived = reinterpret_cast(address); - if (base == derived) { - COMPILER_LOG(INFO) << std::hex << "visit base:" << base << " base Value: " << - *reinterpret_cast(base); - } else { - COMPILER_LOG(INFO) << std::hex << "push base:" << base << " base Value: " << - *reinterpret_cast(base) << " derived:" << derived; - } - } else { - base = reinterpret_cast(address); - } - i++; } } +void LLVMStackMapParser::PrintCallSiteInfo(const CallSiteInfo *infos, OptimizedLeaveFrame *frame) const +{ + uintptr_t callSiteSp = frame->GetCallSiteSp(); + uintptr_t callsiteFp = frame->callsiteFp; + ASSERT(infos != nullptr); + PrintCallSiteSlotAddr(*infos, callSiteSp, callsiteFp); +} -void LLVMStackMapParser::PrintCallSiteInfo(const CallSiteInfo *infos, uintptr_t *fp, uintptr_t curPc) const +void LLVMStackMapParser::PrintCallSiteInfo(const CallSiteInfo *infos, uintptr_t callsiteFp, uintptr_t callSiteSp) const { if (!IsLogEnabled()) { return; } - int i = 0; - uintptr_t address = 0; - uintptr_t base = 0; - uintptr_t derived = 0; - - uintptr_t callsiteFp = *fp; - uintptr_t callSiteSp = FrameHandler::GetPrevFrameCallSiteSp(reinterpret_cast(fp), curPc); - - for (auto &info: *infos) { - if (info.first == GCStackMapRegisters::SP) { - address = callSiteSp + info.second; - } else if (info.first == GCStackMapRegisters::FP) { - address = callsiteFp + info.second; - } else { - UNREACHABLE(); - } + CallSiteInfo callsiteInfo = *infos; + PrintCallSiteSlotAddr(*infos, callSiteSp, callsiteFp); +} - if (IsDeriveredPointer(i)) { - derived = reinterpret_cast(address); - if (base == derived) { - COMPILER_LOG(DEBUG) << std::hex << "visit base:" << base << " base Value: " << - *reinterpret_cast(base); - } else { - COMPILER_LOG(DEBUG) << std::hex << "push base:" << base << " base Value: " << - *reinterpret_cast(base) << " derived:" << derived; - } - } else { - base = reinterpret_cast(address); - } - i++; +uintptr_t LLVMStackMapParser::GetStackAddress(const DwarfRegAndOffsetType info, + uintptr_t callSiteSp, uintptr_t callsiteFp) const +{ + uintptr_t address = 0; + if (info.first == GCStackMapRegisters::SP) { + address = callSiteSp + info.second; + } else if (info.first == GCStackMapRegisters::FP) { + address = callsiteFp + info.second; + } else { + UNREACHABLE(); } + return address; } -bool LLVMStackMapParser::IsDeriveredPointer(int callsitetime) const +void LLVMStackMapParser::IterateCallSiteInfo(const CallSiteInfo *infos, std::set &baseSet, + ChunkMap *data, uintptr_t callsiteFp, uintptr_t callSiteSp) const { - return static_cast(callsitetime) & 1; + CallSiteInfo callsiteInfo = *infos; + ASSERT(callsiteInfo.size() % 2 == 0); + for (size_t j = 0; j < callsiteInfo.size(); j += 2) { + const DwarfRegAndOffsetType baseInfo = callsiteInfo[j]; + const DwarfRegAndOffsetType derivedInfo = (*infos)[j + 1]; + uintptr_t base = GetStackAddress(baseInfo, callSiteSp, callsiteFp); + uintptr_t derived = GetStackAddress(derivedInfo, callSiteSp, callsiteFp); + baseSet.emplace(base); + if (base != derived) { +#if ECMASCRIPT_ENABLE_HEAP_VERIFY + if (!isVerifying) { +#endif + data->emplace(std::make_pair(base, derived), *reinterpret_cast(base)); +#if ECMASCRIPT_ENABLE_HEAP_VERIFY + } +#endif + } + + } } -bool LLVMStackMapParser::CollectStackMapSlots(uintptr_t callSiteAddr, uintptr_t frameFp, +bool LLVMStackMapParser::CollectStackMapSlots(uintptr_t callSiteAddr, uintptr_t callsiteFp, std::set &baseSet, ChunkMap *data, [[maybe_unused]] bool isVerifying, - uintptr_t curPc) const + uintptr_t callSiteSp) const { const CallSiteInfo *infos = GetCallSiteInfoByPc(callSiteAddr); if (infos == nullptr) { return false; } - - uintptr_t *fp = reinterpret_cast(frameFp); - uintptr_t callsiteFp = *fp; - uintptr_t callSiteSp = FrameHandler::GetPrevFrameCallSiteSp(reinterpret_cast(frameFp), curPc); - uintptr_t address = 0; - uintptr_t base = 0; - uintptr_t derived = 0; - int i = 0; + ASSERT(callsiteFp != callSiteSp); + IterateCallSiteInfo(infos, baseSet, data, callsiteFp, callSiteSp); if (IsLogEnabled()) { - PrintCallSiteInfo(infos, fp, curPc); - } - - for (auto &info: *infos) { - if (info.first == GCStackMapRegisters::SP) { - address = callSiteSp + info.second; - } else if (info.first == GCStackMapRegisters::FP) { - address = callsiteFp + info.second; - } else { - UNREACHABLE(); - } - - if (IsDeriveredPointer(i)) { - derived = reinterpret_cast(address); - if (base == derived) { - baseSet.emplace(base); - } else { -#if ECMASCRIPT_ENABLE_HEAP_VERIFY - if (!isVerifying) { -#endif - data->emplace(std::make_pair(base, derived), *reinterpret_cast(base)); -#if ECMASCRIPT_ENABLE_HEAP_VERIFY - } -#endif - } - } else { - base = reinterpret_cast(address); - baseSet.emplace(base); - } - i++; + PrintCallSiteInfo(infos, callsiteFp, callSiteSp); } return true; } diff --git a/ecmascript/compiler/llvm/llvm_stackmap_parser.h b/ecmascript/compiler/llvm/llvm_stackmap_parser.h index e209cb51..9bf93c3b 100644 --- a/ecmascript/compiler/llvm/llvm_stackmap_parser.h +++ b/ecmascript/compiler/llvm/llvm_stackmap_parser.h @@ -207,11 +207,10 @@ public: } } const CallSiteInfo *GetCallSiteInfoByPc(uintptr_t funcAddr) const; - bool CollectStackMapSlots(uintptr_t callSiteAddr, uintptr_t frameFp, + bool CollectStackMapSlots(uintptr_t callSiteAddr, uintptr_t callsiteFp, std::set &baseSet, ChunkMap *data, [[maybe_unused]] bool isVerifying, - uintptr_t curPc) const; - + uintptr_t callSiteSp) const; bool IsLogEnabled() const { return enableLog_; @@ -250,10 +249,15 @@ private: pc2ConstInfoVec_.clear(); } void CalcCallSite(); - bool IsDeriveredPointer(int callsitetime) const; void PrintCallSiteInfo(const CallSiteInfo *infos, OptimizedLeaveFrame *frame) const; - void PrintCallSiteInfo(const CallSiteInfo *infos, uintptr_t *fp, uintptr_t curPc) const; + void PrintCallSiteInfo(const CallSiteInfo *infos, uintptr_t callSiteFp, uintptr_t callSiteSp) const; int FindFpDelta(uintptr_t funcAddr, uintptr_t callsitePc) const; + inline uintptr_t GetStackAddress(const DwarfRegAndOffsetType info, + uintptr_t callSiteSp, uintptr_t callsiteFp) const; + void IterateCallSiteInfo(const CallSiteInfo *infos, std::set &baseSet, + ChunkMap *data, uintptr_t callsiteFp, uintptr_t callSiteSp) const; + void PrintCallSiteSlotAddr(const CallSiteInfo& callsiteInfo, uintptr_t callSiteSp, + uintptr_t callsiteFp) const; struct LLVMStackMap llvmStackMap_; std::vector pc2CallSiteInfoVec_; diff --git a/ecmascript/interpreter/frame_handler.cpp b/ecmascript/interpreter/frame_handler.cpp index 969eb5c0..ad26e44f 100644 --- a/ecmascript/interpreter/frame_handler.cpp +++ b/ecmascript/interpreter/frame_handler.cpp @@ -135,6 +135,10 @@ uintptr_t FrameHandler::GetPrevFrameCallSiteSp(const JSTaggedType *sp, uintptr_t kungfu::LLVMStackMapParser::GetInstance().GetFuncFpDelta(curPc); return callSiteSp; } + case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME : { + auto callSiteSp = reinterpret_cast(sp) + sizeof(uintptr_t); + return callSiteSp; + } case FrameType::BUILTIN_ENTRY_FRAME: case FrameType::ASM_INTERPRETER_FRAME: case FrameType::INTERPRETER_CONSTRUCTOR_FRAME: @@ -144,8 +148,7 @@ uintptr_t FrameHandler::GetPrevFrameCallSiteSp(const JSTaggedType *sp, uintptr_t case FrameType::INTERPRETER_ENTRY_FRAME: case FrameType::ASM_INTERPRETER_ENTRY_FRAME: default: { - LOG_ECMA(FATAL) << "frame type error!"; - UNREACHABLE(); + return 0; } } } @@ -406,7 +409,9 @@ ARK_INLINE void FrameHandler::InterpretedFrameIterate(const JSTaggedType *sp, ARK_INLINE void FrameHandler::AsmInterpretedFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, - const RootRangeVisitor &v1) const + const RootRangeVisitor &v1, + ChunkMap *derivedPointers, + bool isVerifying) { AsmInterpretedFrame *frame = AsmInterpretedFrame::GetFrameFromSp(sp); uintptr_t start = ToUintPtr(sp); @@ -417,13 +422,30 @@ ARK_INLINE void FrameHandler::AsmInterpretedFrameIterate(const JSTaggedType *sp, v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->acc))); v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->env))); } + + uintptr_t curPc = optimizedReturnAddr_; + std::set slotAddrs; + bool ret = kungfu::LLVMStackMapParser::GetInstance().CollectStackMapSlots( + curPc, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, + optimizedCallSiteSp_); + if (!ret) { +#ifndef NDEBUG + LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << curPc; +#endif + return; + } + + + for (auto slot : slotAddrs) { + v0(Root::ROOT_FRAME, ObjectSlot(slot)); + } } ARK_INLINE void FrameHandler::BuiltinFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, + [[maybe_unused]] const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) const + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) { auto frame = BuiltinFrame::GetFrameFromSp(sp); // no need to visit stack map for entry frame @@ -437,28 +459,13 @@ ARK_INLINE void FrameHandler::BuiltinFrameIterate(const JSTaggedType *sp, uintptr_t start = ToUintPtr(argv); uintptr_t end = ToUintPtr(argv + argc); v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); - - std::set slotAddrs; - bool ret = kungfu::LLVMStackMapParser::GetInstance().CollectStackMapSlots( - frame->returnAddr, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, - optimizedReturnAddr_); - if (!ret) { -#ifndef NDEBUG - LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << frame->returnAddr; -#endif - return; - } - - for (auto slot : slotAddrs) { - v0(Root::ROOT_FRAME, ObjectSlot(slot)); - } } ARK_INLINE void FrameHandler::BuiltinWithArgvFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, + [[maybe_unused]] const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) const + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) { auto frame = BuiltinWithArgvFrame::GetFrameFromSp(sp); auto argc = frame->GetNumArgs() + BuiltinFrame::RESERVED_CALL_ARGCOUNT; @@ -466,21 +473,6 @@ ARK_INLINE void FrameHandler::BuiltinWithArgvFrameIterate(const JSTaggedType *sp uintptr_t start = ToUintPtr(argv); uintptr_t end = ToUintPtr(argv + argc); v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); - - std::set slotAddrs; - bool ret = kungfu::LLVMStackMapParser::GetInstance().CollectStackMapSlots( - frame->returnAddr, reinterpret_cast(sp), slotAddrs, - derivedPointers, isVerifying, optimizedReturnAddr_); - if (!ret) { -#ifndef NDEBUG - LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << frame->returnAddr; -#endif - return; - } - - for (auto slot : slotAddrs) { - v0(Root::ROOT_FRAME, ObjectSlot(slot)); - } } ARK_INLINE JSTaggedType *FrameHandler::GetInterpretedEntryFrameStart(const JSTaggedType *sp) @@ -504,18 +496,16 @@ ARK_INLINE void FrameHandler::OptimizedFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, [[maybe_unused]] const RootRangeVisitor &v1, ChunkMap *derivedPointers, - bool isVerifying) const + bool isVerifying) { std::set slotAddrs; - // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - auto returnAddr = - reinterpret_cast(*(reinterpret_cast(const_cast(sp)) + 1)); bool enableCompilerLog = thread_->GetEcmaVM()->GetJSOptions().WasSetlogCompiledMethods(); bool ret = kungfu::LLVMStackMapParser::GetInstance(enableCompilerLog).CollectStackMapSlots( - returnAddr, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedReturnAddr_); + optimizedReturnAddr_, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); + if (!ret) { #ifndef NDEBUG - LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << returnAddr; + LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << optimizedReturnAddr_; #endif return; } @@ -532,28 +522,26 @@ ARK_INLINE void FrameHandler::OptimizedJSFunctionFrameIterate(const JSTaggedType bool isVerifying) { OptimizedJSFunctionFrame *frame = OptimizedJSFunctionFrame::GetFrameFromSp(sp); - auto currentPc = optimizedReturnAddr_; - optimizedReturnAddr_ = frame->returnAddr; - int delta = kungfu::LLVMStackMapParser::GetInstance().GetFuncFpDelta(currentPc); + + int delta = kungfu::LLVMStackMapParser::GetInstance().GetFuncFpDelta(optimizedReturnAddr_); uintptr_t *preFrameSp = frame->ComputePrevFrameSp(sp, delta); auto argc = *(reinterpret_cast(preFrameSp)); - JSTaggedType *argv = frame->GetArgv(preFrameSp); + JSTaggedType *argv = frame->GetArgv(reinterpret_cast(preFrameSp)); if (argc > 0) { uintptr_t start = ToUintPtr(argv); // argv uintptr_t end = ToUintPtr(argv + argc); v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); } + std::set slotAddrs; - // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - auto returnAddr = - reinterpret_cast(*(reinterpret_cast(const_cast(sp)) + 1)); bool enableCompilerLog = thread_->GetEcmaVM()->GetJSOptions().WasSetlogCompiledMethods(); + auto currentPc = optimizedReturnAddr_; bool ret = kungfu::LLVMStackMapParser::GetInstance(enableCompilerLog).CollectStackMapSlots( - returnAddr, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedReturnAddr_); + currentPc, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); if (!ret) { #ifndef NDEBUG - LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << returnAddr; + LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << currentPc; #endif return; } @@ -588,10 +576,10 @@ ARK_INLINE void FrameHandler::OptimizedEntryFrameIterate(const JSTaggedType *sp, } ARK_INLINE void FrameHandler::OptimizedLeaveFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, + [[maybe_unused]] const RootVisitor &v0, [[maybe_unused]] const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) { OptimizedLeaveFrame *frame = OptimizedLeaveFrame::GetFrameFromSp(sp); if (frame->argc > 0) { @@ -600,25 +588,13 @@ ARK_INLINE void FrameHandler::OptimizedLeaveFrameIterate(const JSTaggedType *sp, uintptr_t end = ToUintPtr(argv + frame->argc); v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); } - - std::set slotAddrs; - bool ret = kungfu::LLVMStackMapParser::GetInstance().CollectStackMapSlots( - frame->returnAddr, reinterpret_cast(sp), slotAddrs, - derivedPointers, isVerifying, optimizedReturnAddr_); - if (!ret) { - return; - } - - for (auto slot : slotAddrs) { - v0(Root::ROOT_FRAME, ObjectSlot(slot)); - } } ARK_INLINE void FrameHandler::OptimizedWithArgvLeaveFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, + [[maybe_unused]] const RootVisitor &v0, [[maybe_unused]] const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) { OptimizedLeaveFrame *frame = OptimizedLeaveFrame::GetFrameFromSp(sp); if (frame->argc > 0) { @@ -628,18 +604,6 @@ ARK_INLINE void FrameHandler::OptimizedWithArgvLeaveFrameIterate(const JSTaggedT uintptr_t end = ToUintPtr(argv + frame->argc); v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); } - - std::set slotAddrs; - bool ret = kungfu::LLVMStackMapParser::GetInstance().CollectStackMapSlots( - frame->returnAddr, reinterpret_cast(sp), slotAddrs, - derivedPointers, isVerifying, optimizedReturnAddr_); - if (!ret) { - return; - } - - for (auto slot : slotAddrs) { - v0(Root::ROOT_FRAME, ObjectSlot(slot)); - } } void FrameHandler::IterateRsp(const RootVisitor &v0, const RootRangeVisitor &v1) @@ -694,12 +658,14 @@ void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, auto frame = OptimizedFrame::GetFrameFromSp(current); auto prevFrame = frame->GetPrevFrameFp(); OptimizedFrameIterate(current, v0, v1, derivedPointers, isVerifying); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current, optimizedReturnAddr_); current = prevFrame; optimizedReturnAddr_ = frame->returnAddr; break; } case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME: { OptimizedJSFunctionFrame *frame = OptimizedJSFunctionFrame::GetFrameFromSp(current); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current); optimizedReturnAddr_ = frame->returnAddr; current = frame->GetPrevFrameFp(); break; @@ -708,28 +674,32 @@ void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, auto frame = OptimizedJSFunctionFrame::GetFrameFromSp(current); auto prevFrame = frame->GetPrevFrameFp(); OptimizedJSFunctionFrameIterate(current, v0, v1, derivedPointers, isVerifying); - current = prevFrame; + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current, optimizedReturnAddr_); optimizedReturnAddr_ = frame->returnAddr; + current = prevFrame; break; } case FrameType::OPTIMIZED_ENTRY_FRAME: { auto frame = OptimizedEntryFrame::GetFrameFromSp(current); current = frame->GetPrevFrameFp(); - optimizedReturnAddr_ = 0; + optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; break; } case FrameType::ASM_INTERPRETER_ENTRY_FRAME: { auto frame = AsmInterpretedEntryFrame::GetFrameFromSp(current); current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; break; } case FrameType::ASM_INTERPRETER_FRAME: case FrameType::INTERPRETER_CONSTRUCTOR_FRAME: { auto frame = AsmInterpretedFrame::GetFrameFromSp(current); - AsmInterpretedFrameIterate(current, v0, v1); + AsmInterpretedFrameIterate(current, v0, v1, derivedPointers, isVerifying); current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; break; } case FrameType::INTERPRETER_FRAME: @@ -738,11 +708,13 @@ void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, InterpretedFrameIterate(current, v0, v1); current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; break; } case FrameType::LEAVE_FRAME: { auto frame = OptimizedLeaveFrame::GetFrameFromSp(current); OptimizedLeaveFrameIterate(current, v0, v1, derivedPointers, isVerifying); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current); current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = frame->returnAddr; break; @@ -757,16 +729,18 @@ void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, case FrameType::BUILTIN_FRAME_WITH_ARGV: { auto frame = BuiltinWithArgvFrame::GetFrameFromSp(current); BuiltinWithArgvFrameIterate(current, v0, v1, derivedPointers, isVerifying); - current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = frame->returnAddr; + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current); + current = frame->GetPrevFrameFp(); break; } case FrameType::BUILTIN_ENTRY_FRAME: case FrameType::BUILTIN_FRAME: { auto frame = BuiltinFrame::GetFrameFromSp(current); BuiltinFrameIterate(current, v0, v1, derivedPointers, isVerifying); - current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = frame->returnAddr; + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current); + current = frame->GetPrevFrameFp(); break; } case FrameType::INTERPRETER_ENTRY_FRAME: { @@ -774,6 +748,7 @@ void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, InterpretedEntryFrameIterate(current, v0, v1); current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; break; } default: { diff --git a/ecmascript/interpreter/frame_handler.h b/ecmascript/interpreter/frame_handler.h index 4e4b8ccf..94d7298d 100644 --- a/ecmascript/interpreter/frame_handler.h +++ b/ecmascript/interpreter/frame_handler.h @@ -115,7 +115,7 @@ public: JSTaggedType *GetPrevInterpretedFrame(); // for llvm. - static uintptr_t GetPrevFrameCallSiteSp(const JSTaggedType *sp, uintptr_t curPc); + static uintptr_t GetPrevFrameCallSiteSp(const JSTaggedType *sp, uintptr_t curPc = 0); // for InterpretedFrame. JSTaggedValue GetVRegValue(size_t index) const; @@ -166,17 +166,18 @@ private: // for Frame GC. void InterpretedFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1) const; - void AsmInterpretedFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1) const; + void AsmInterpretedFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, + ChunkMap *derivedPointers, bool isVerifying); void InterpretedEntryFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1) const; void BuiltinFrameIterate( const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying) const; + ChunkMap *derivedPointers, bool isVerifying); void BuiltinWithArgvFrameIterate( const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying) const; + ChunkMap *derivedPointers, bool isVerifying); void OptimizedFrameIterate( const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying) const; + ChunkMap *derivedPointers, bool isVerifying); void OptimizedJSFunctionFrameIterate( const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, ChunkMap *derivedPointers, bool isVerifying); @@ -194,6 +195,7 @@ private: JSTaggedType *sp_ {nullptr}; JSTaggedType *fp_ {nullptr}; const JSThread *thread_ {nullptr}; + uintptr_t optimizedCallSiteSp_ {0}; uintptr_t optimizedReturnAddr_ {0}; }; -- Gitee From 90c8e7b84fadb56751b48dff9649ddee075873c0 Mon Sep 17 00:00:00 2001 From: songzhengchao Date: Sat, 11 Jun 2022 14:15:59 +0800 Subject: [PATCH 002/154] refactor llvm_stackmap_parser In the future, multiple vm may be existed such as multiple worker.each vm should have one stackmap, while llvm_stackmap_parser is singleton which is not good. issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5BSW4 Signed-off-by: songzhengchao Change-Id: I7501c656f27a2fd34225928079f23a196e7f0bbf --- BUILD.gn | 2 +- .../compiler/llvm/llvm_stackmap_parser.cpp | 2 +- .../compiler/llvm/llvm_stackmap_parser.h | 10 +- ecmascript/compiler/llvm_codegen.cpp | 2 +- ecmascript/compiler/tests/stub_tests.cpp | 34 +- ecmascript/ecma_vm.cpp | 13 +- ecmascript/ecma_vm.h | 8 + ecmascript/file_loader.cpp | 12 +- ecmascript/interpreter/frame_handler.cpp | 17 +- ecmascript/interpreter/frame_handler.h | 2 +- ecmascript/js_thread.cpp | 2 +- ecmascript/llvm_stackmap_parser.cpp | 306 ++++++++++++++++++ ecmascript/llvm_stackmap_parser.h | 266 +++++++++++++++ ecmascript/stubs/runtime_stubs-inl.h | 2 +- 14 files changed, 614 insertions(+), 64 deletions(-) create mode 100644 ecmascript/llvm_stackmap_parser.cpp create mode 100644 ecmascript/llvm_stackmap_parser.h diff --git a/BUILD.gn b/BUILD.gn index 32901a7d..1fe8d7f3 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -366,6 +366,7 @@ ecma_source = [ "ecmascript/ecma_vm.cpp", "ecmascript/free_object.cpp", "ecmascript/file_loader.cpp", + "ecmascript/llvm_stackmap_parser.cpp", "ecmascript/generator_helper.cpp", "ecmascript/global_env.cpp", "ecmascript/global_env_constants.cpp", @@ -490,7 +491,6 @@ ecma_source = [ "ecmascript/template_string.cpp", "ecmascript/waiter_list.cpp", "ecmascript/weak_vector.cpp", - "ecmascript/compiler/llvm/llvm_stackmap_parser.cpp", "ecmascript/stubs/runtime_stubs.cpp", "ecmascript/ts_types/ts_type.cpp", "ecmascript/ts_types/ts_type_table.cpp", diff --git a/ecmascript/compiler/llvm/llvm_stackmap_parser.cpp b/ecmascript/compiler/llvm/llvm_stackmap_parser.cpp index 66ffe541..48ca627e 100644 --- a/ecmascript/compiler/llvm/llvm_stackmap_parser.cpp +++ b/ecmascript/compiler/llvm/llvm_stackmap_parser.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "ecmascript/compiler/llvm/llvm_stackmap_parser.h" +#include "ecmascript/llvm_stackmap_parser.h" #include "ecmascript/compiler/assembler/assembler.h" #include "ecmascript/frames.h" #include "ecmascript/mem/slots.h" diff --git a/ecmascript/compiler/llvm/llvm_stackmap_parser.h b/ecmascript/compiler/llvm/llvm_stackmap_parser.h index 9bf93c3b..0a38bfdc 100644 --- a/ecmascript/compiler/llvm/llvm_stackmap_parser.h +++ b/ecmascript/compiler/llvm/llvm_stackmap_parser.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef ECMASCRIPT_COMPILER_LLVM_LLVMSTACKPARSE_H -#define ECMASCRIPT_COMPILER_LLVM_LLVMSTACKPARSE_H +#ifndef ECMASCRIPT_LLVMSTACKPARSE_ +#define ECMASCRIPT_LLVMSTACKPARSE_ #include #include @@ -230,8 +230,7 @@ public: return {}; } -private: - explicit LLVMStackMapParser(bool enableLog) + explicit LLVMStackMapParser(bool enableLog = false) { pc2CallSiteInfoVec_.clear(); dataInfo_ = nullptr; @@ -248,6 +247,7 @@ private: fun2FpDelta_.clear(); pc2ConstInfoVec_.clear(); } +private: void CalcCallSite(); void PrintCallSiteInfo(const CallSiteInfo *infos, OptimizedLeaveFrame *frame) const; void PrintCallSiteInfo(const CallSiteInfo *infos, uintptr_t callSiteFp, uintptr_t callSiteSp) const; @@ -268,4 +268,4 @@ private: std::vector pc2ConstInfoVec_; }; } // namespace panda::ecmascript::kungfu -#endif // ECMASCRIPT_COMPILER_LLVM_LLVMSTACKPARSE_H \ No newline at end of file +#endif // ECMASCRIPT_LLVMSTACKPARSE_ \ No newline at end of file diff --git a/ecmascript/compiler/llvm_codegen.cpp b/ecmascript/compiler/llvm_codegen.cpp index 8d33f378..df545d3e 100644 --- a/ecmascript/compiler/llvm_codegen.cpp +++ b/ecmascript/compiler/llvm_codegen.cpp @@ -35,6 +35,7 @@ #endif #include "ecmascript/compiler/call_signature.h" +#include "ecmascript/llvm_stackmap_parser.h" #include "llvm-c/Analysis.h" #include "llvm-c/Core.h" #include "llvm-c/Disassembler.h" @@ -64,7 +65,6 @@ #include "llvm/Support/Host.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Transforms/Scalar.h" -#include "llvm/llvm_stackmap_parser.h" #if defined(__clang__) #pragma clang diagnostic pop diff --git a/ecmascript/compiler/tests/stub_tests.cpp b/ecmascript/compiler/tests/stub_tests.cpp index a0cc408f..f322e37a 100644 --- a/ecmascript/compiler/tests/stub_tests.cpp +++ b/ecmascript/compiler/tests/stub_tests.cpp @@ -21,7 +21,7 @@ #include "ecmascript/compiler/common_stubs.h" #include "ecmascript/compiler/llvm_codegen.h" #include "ecmascript/compiler/llvm_ir_builder.h" -#include "ecmascript/compiler/llvm/llvm_stackmap_parser.h" +#include "ecmascript/llvm_stackmap_parser.h" #include "ecmascript/compiler/scheduler.h" #include "ecmascript/compiler/call_signature.h" #include "ecmascript/compiler/verifier.h" @@ -839,38 +839,6 @@ HWTEST_F_L0(StubTest, LoadGCIRTest) } #endif -extern "C" { -void DoSafepoint() -{ - uintptr_t *rbp; - asm("mov %%rbp, %0" : "=rm" (rbp)); - for (int i = 0; i < 3; i++) { // 3: call back depth - uintptr_t returnAddr = *(rbp + 1); - uintptr_t *rsp = rbp + 2; // move 2 steps from rbp to get rsp - rbp = reinterpret_cast(*rbp); - const kungfu::CallSiteInfo *infos = - kungfu::LLVMStackMapParser::GetInstance().GetCallSiteInfoByPc(returnAddr); - if (infos != nullptr) { - for (auto &info : *infos) { - uintptr_t **address = nullptr; - if (info.first == GCStackMapRegisters::SP) { - address = reinterpret_cast(reinterpret_cast(rsp) + info.second); - } else if (info.first == GCStackMapRegisters::FP) { - address = reinterpret_cast(reinterpret_cast(rbp) + info.second); - } - // print ref and vlue for debug - COMPILER_LOG(INFO) << std::hex << "ref addr:" << address; - COMPILER_LOG(INFO) << " value:" << *address; - COMPILER_LOG(INFO) << " *value :" << **address; - } - } - COMPILER_LOG(INFO) << std::hex << "+++++++++++++++++++ returnAddr : 0x" << returnAddr << " rbp:" << rbp - << " rsp: " << rsp; - } - COMPILER_LOG(INFO) << "do_safepoint +++ "; -} -} - HWTEST_F_L0(StubTest, GetPropertyByIndexStub) { auto module = stubModule.GetModule(); diff --git a/ecmascript/ecma_vm.cpp b/ecmascript/ecma_vm.cpp index 34033d6d..3537a437 100644 --- a/ecmascript/ecma_vm.cpp +++ b/ecmascript/ecma_vm.cpp @@ -67,6 +67,7 @@ #include "ecmascript/require/js_cjs_module_cache.h" #include "ecmascript/require/js_require_manager.h" #include "ecmascript/tooling/interface/js_debugger_manager.h" +#include "ecmascript/llvm_stackmap_parser.h" #ifdef PANDA_TARGET_WINDOWS #ifdef ERROR #undef ERROR @@ -177,12 +178,14 @@ bool EcmaVM::Initialize() tsLoader_ = new TSLoader(this); snapshotEnv_ = new SnapshotEnv(this); fileLoader_ = new FileLoader(this); - if (options_.EnableStubAot()) { - LoadStubFile(); - } + bool enableLog = GetJSOptions().WasSetlogCompiledMethods(); + stackMapParser_ = new kungfu::LLVMStackMapParser(enableLog); if (options_.EnableTSAot()) { LoadAOTFiles(); } + if (options_.EnableStubAot()) { + LoadStubFile(); + } InitializeFinish(); return true; } @@ -311,6 +314,10 @@ EcmaVM::~EcmaVM() delete fileLoader_; fileLoader_ = nullptr; } + if (stackMapParser_ != nullptr) { + delete stackMapParser_; + stackMapParser_ = nullptr; + } if (thread_ != nullptr) { delete thread_; diff --git a/ecmascript/ecma_vm.h b/ecmascript/ecma_vm.h index fb499ba3..838852c5 100644 --- a/ecmascript/ecma_vm.h +++ b/ecmascript/ecma_vm.h @@ -67,6 +67,9 @@ class JSFunction; class Program; class TSLoader; class FileLoader; +namespace kungfu { + class LLVMStackMapParser; +}; class ModuleManager; class JSCjsModule; class JSCjsExports; @@ -328,6 +331,10 @@ public: JSTaggedValue FindConstpool(const JSPandaFile *jsPandaFile); void SetAOTFuncEntry(uint32_t hash, uint32_t methodId, uint64_t funcEntry); + kungfu::LLVMStackMapParser *GetStackMapParser() + { + return stackMapParser_; + } protected: void HandleUncaughtException(ObjectHeader *exception); @@ -402,6 +409,7 @@ private: SnapshotEnv *snapshotEnv_ {nullptr}; bool optionalLogEnabled_ {false}; FileLoader *fileLoader_ {nullptr}; + kungfu::LLVMStackMapParser *stackMapParser_ {nullptr}; // Debugger tooling::JsDebuggerManager *debuggerManager_ {nullptr}; diff --git a/ecmascript/file_loader.cpp b/ecmascript/file_loader.cpp index a4b915cc..7208eef0 100644 --- a/ecmascript/file_loader.cpp +++ b/ecmascript/file_loader.cpp @@ -17,7 +17,7 @@ #include "ecmascript/base/config.h" #include "ecmascript/compiler/bc_call_signature.h" #include "ecmascript/compiler/common_stubs.h" -#include "ecmascript/compiler/llvm/llvm_stackmap_parser.h" +#include "ecmascript/llvm_stackmap_parser.h" #include "ecmascript/ecma_vm.h" #include "ecmascript/jspandafile/constpool_value.h" #include "ecmascript/jspandafile/js_pandafile.h" @@ -100,8 +100,7 @@ bool StubModulePackInfo::Load(EcmaVM *vm, const std::string &filename) std::unique_ptr stackmapPtr(std::make_unique(stackmapSize)); moduleFile.read(reinterpret_cast(stackmapPtr.get()), stackmapSize); if (stackmapSize != 0) { - bool enableLog = vm->GetJSOptions().WasSetlogCompiledMethods(); - kungfu::LLVMStackMapParser::GetInstance(enableLog).CalculateStackMap(std::move(stackmapPtr), + vm->GetStackMapParser()->CalculateStackMap(std::move(stackmapPtr), des_[i].GetHostCodeSecAddr(), startAddr); } } @@ -114,7 +113,7 @@ bool StubModulePackInfo::Load(EcmaVM *vm, const std::string &filename) kungfu::Func2FpDelta fun2fpDelta; auto funSize = funcEntryDes.funcSize_; fun2fpDelta[funAddr] = std::make_pair(delta, funSize); - kungfu::LLVMStackMapParser::GetInstance().CalculateFuncFpDelta(fun2fpDelta); + vm->GetStackMapParser()->CalculateFuncFpDelta(fun2fpDelta); } for (size_t i = 0; i < entries_.size(); i++) { auto des = des_[entries_[i].moduleIndex_]; @@ -190,8 +189,7 @@ bool AOTModulePackInfo::Load(EcmaVM *vm, const std::string &filename) std::unique_ptr stackmapPtr(std::make_unique(stackmapSize)); moduleFile.read(reinterpret_cast(stackmapPtr.get()), stackmapSize); if (stackmapSize != 0) { - bool enableLog = vm->GetJSOptions().WasSetlogCompiledMethods(); - kungfu::LLVMStackMapParser::GetInstance(enableLog).CalculateStackMap(std::move(stackmapPtr), + vm->GetStackMapParser()->CalculateStackMap(std::move(stackmapPtr), des_[i].GetHostCodeSecAddr(), startAddr); } } @@ -204,7 +202,7 @@ bool AOTModulePackInfo::Load(EcmaVM *vm, const std::string &filename) uintptr_t funAddr = startAddr + codeAddr; kungfu::Func2FpDelta fun2fpDelta; fun2fpDelta[funAddr] = std::make_pair(delta, funSize); - kungfu::LLVMStackMapParser::GetInstance().CalculateFuncFpDelta(fun2fpDelta); + vm->GetStackMapParser()->CalculateFuncFpDelta(fun2fpDelta); } for (size_t i = 0; i < entries_.size(); i++) { diff --git a/ecmascript/interpreter/frame_handler.cpp b/ecmascript/interpreter/frame_handler.cpp index ad26e44f..b9409abc 100644 --- a/ecmascript/interpreter/frame_handler.cpp +++ b/ecmascript/interpreter/frame_handler.cpp @@ -16,7 +16,7 @@ #include "ecmascript/interpreter/frame_handler.h" -#include "ecmascript/compiler/llvm/llvm_stackmap_parser.h" +#include "ecmascript/llvm_stackmap_parser.h" #include "ecmascript/js_function.h" #include "ecmascript/js_thread.h" #include "ecmascript/mem/heap.h" @@ -132,7 +132,7 @@ uintptr_t FrameHandler::GetPrevFrameCallSiteSp(const JSTaggedType *sp, uintptr_t case FrameType::OPTIMIZED_FRAME: case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: { auto callSiteSp = reinterpret_cast(sp) + - kungfu::LLVMStackMapParser::GetInstance().GetFuncFpDelta(curPc); + thread_->GetEcmaVM()->GetStackMapParser()->GetFuncFpDelta(curPc); return callSiteSp; } case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME : { @@ -425,7 +425,7 @@ ARK_INLINE void FrameHandler::AsmInterpretedFrameIterate(const JSTaggedType *sp, uintptr_t curPc = optimizedReturnAddr_; std::set slotAddrs; - bool ret = kungfu::LLVMStackMapParser::GetInstance().CollectStackMapSlots( + bool ret = thread_->GetEcmaVM()->GetStackMapParser()->CollectStackMapSlots( curPc, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); if (!ret) { @@ -499,8 +499,7 @@ ARK_INLINE void FrameHandler::OptimizedFrameIterate(const JSTaggedType *sp, bool isVerifying) { std::set slotAddrs; - bool enableCompilerLog = thread_->GetEcmaVM()->GetJSOptions().WasSetlogCompiledMethods(); - bool ret = kungfu::LLVMStackMapParser::GetInstance(enableCompilerLog).CollectStackMapSlots( + bool ret = thread_->GetEcmaVM()->GetStackMapParser()->CollectStackMapSlots( optimizedReturnAddr_, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); if (!ret) { @@ -523,7 +522,7 @@ ARK_INLINE void FrameHandler::OptimizedJSFunctionFrameIterate(const JSTaggedType { OptimizedJSFunctionFrame *frame = OptimizedJSFunctionFrame::GetFrameFromSp(sp); - int delta = kungfu::LLVMStackMapParser::GetInstance().GetFuncFpDelta(optimizedReturnAddr_); + int delta = thread_->GetEcmaVM()->GetStackMapParser()->GetFuncFpDelta(optimizedReturnAddr_); uintptr_t *preFrameSp = frame->ComputePrevFrameSp(sp, delta); auto argc = *(reinterpret_cast(preFrameSp)); @@ -535,9 +534,8 @@ ARK_INLINE void FrameHandler::OptimizedJSFunctionFrameIterate(const JSTaggedType } std::set slotAddrs; - bool enableCompilerLog = thread_->GetEcmaVM()->GetJSOptions().WasSetlogCompiledMethods(); auto currentPc = optimizedReturnAddr_; - bool ret = kungfu::LLVMStackMapParser::GetInstance(enableCompilerLog).CollectStackMapSlots( + bool ret = thread_->GetEcmaVM()->GetStackMapParser()->CollectStackMapSlots( currentPc, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); if (!ret) { #ifndef NDEBUG @@ -560,8 +558,7 @@ ARK_INLINE void FrameHandler::OptimizedEntryFrameIterate(const JSTaggedType *sp, std::set slotAddrs; // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) auto returnAddr = reinterpret_cast(*(reinterpret_cast(const_cast(sp)) + 1)); - bool enableCompilerLog = thread_->GetEcmaVM()->GetJSOptions().WasSetlogCompiledMethods(); - bool ret = kungfu::LLVMStackMapParser::GetInstance(enableCompilerLog).CollectStackMapSlots( + bool ret = thread_->GetEcmaVM()->GetStackMapParser()->CollectStackMapSlots( returnAddr, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedReturnAddr_); if (!ret) { #ifndef NDEBUG diff --git a/ecmascript/interpreter/frame_handler.h b/ecmascript/interpreter/frame_handler.h index 94d7298d..86c5a6b4 100644 --- a/ecmascript/interpreter/frame_handler.h +++ b/ecmascript/interpreter/frame_handler.h @@ -115,7 +115,7 @@ public: JSTaggedType *GetPrevInterpretedFrame(); // for llvm. - static uintptr_t GetPrevFrameCallSiteSp(const JSTaggedType *sp, uintptr_t curPc = 0); + uintptr_t GetPrevFrameCallSiteSp(const JSTaggedType *sp, uintptr_t curPc = 0); // for InterpretedFrame. JSTaggedValue GetVRegValue(size_t index) const; diff --git a/ecmascript/js_thread.cpp b/ecmascript/js_thread.cpp index 3db677a3..dc8db7e3 100644 --- a/ecmascript/js_thread.cpp +++ b/ecmascript/js_thread.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ #include "ecmascript/js_thread.h" -#include "ecmascript/compiler/llvm/llvm_stackmap_parser.h" +#include "ecmascript/llvm_stackmap_parser.h" #include "ecmascript/ecma_param_configuration.h" #include "ecmascript/global_env_constants-inl.h" #include "ecmascript/ic/properties_cache.h" diff --git a/ecmascript/llvm_stackmap_parser.cpp b/ecmascript/llvm_stackmap_parser.cpp new file mode 100644 index 00000000..48ca627e --- /dev/null +++ b/ecmascript/llvm_stackmap_parser.cpp @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ecmascript/llvm_stackmap_parser.h" +#include "ecmascript/compiler/assembler/assembler.h" +#include "ecmascript/frames.h" +#include "ecmascript/mem/slots.h" +#include "ecmascript/mem/visitor.h" + +using namespace panda::ecmascript; + +namespace panda::ecmascript::kungfu { +std::string LocationTy::TypeToString(Kind loc) const +{ + switch (loc) { + case Kind::REGISTER: + return "Register Reg Value in a register"; + case Kind::DIRECT: + return "Direct Reg + Offset Frame index value"; + case Kind::INDIRECT: + return "Indirect [Reg + Offset] Spilled value"; + case Kind::CONSTANT: + return "Constant Offset Small constant"; + case Kind::CONSTANTNDEX: + return "ConstIndex constants[Offset] Large constant"; + default: + return "no know location"; + } +} + +const CallSiteInfo* LLVMStackMapParser::GetCallSiteInfoByPc(uintptr_t callSiteAddr) const +{ + for (auto &callSiteInfo: pc2CallSiteInfoVec_) { + auto it = callSiteInfo.find(callSiteAddr); + if (it != callSiteInfo.end()) { + return &(it->second); + } + } + return nullptr; +} + +void LLVMStackMapParser::PrintCallSiteSlotAddr(const CallSiteInfo& callsiteInfo, uintptr_t callSiteSp, + uintptr_t callsiteFp) const +{ + ASSERT(callsiteInfo.size() % 2 == 0); + for (size_t j = 0; j < callsiteInfo.size(); j += 2) { + const DwarfRegAndOffsetType baseInfo = callsiteInfo[j]; + const DwarfRegAndOffsetType derivedInfo = callsiteInfo[j + 1]; + COMPILER_LOG(DEBUG) << std::hex << " callSiteSp:0x" << callSiteSp << " callsiteFp:" << callsiteFp; + COMPILER_LOG(DEBUG) << std::dec << "base DWARF_REG:" << baseInfo.first + << " OFFSET:" << baseInfo.second; + uintptr_t base = GetStackAddress(baseInfo, callSiteSp, callsiteFp); + uintptr_t derived = GetStackAddress(derivedInfo, callSiteSp, callsiteFp); + if (base != derived) { + COMPILER_LOG(DEBUG) << std::dec << "derived DWARF_REG:" << derivedInfo.first + << " OFFSET:" << derivedInfo.second; + } + } +} +void LLVMStackMapParser::PrintCallSiteInfo(const CallSiteInfo *infos, OptimizedLeaveFrame *frame) const +{ + uintptr_t callSiteSp = frame->GetCallSiteSp(); + uintptr_t callsiteFp = frame->callsiteFp; + ASSERT(infos != nullptr); + PrintCallSiteSlotAddr(*infos, callSiteSp, callsiteFp); +} + +void LLVMStackMapParser::PrintCallSiteInfo(const CallSiteInfo *infos, uintptr_t callsiteFp, uintptr_t callSiteSp) const +{ + if (!IsLogEnabled()) { + return; + } + + CallSiteInfo callsiteInfo = *infos; + PrintCallSiteSlotAddr(*infos, callSiteSp, callsiteFp); +} + +uintptr_t LLVMStackMapParser::GetStackAddress(const DwarfRegAndOffsetType info, + uintptr_t callSiteSp, uintptr_t callsiteFp) const +{ + uintptr_t address = 0; + if (info.first == GCStackMapRegisters::SP) { + address = callSiteSp + info.second; + } else if (info.first == GCStackMapRegisters::FP) { + address = callsiteFp + info.second; + } else { + UNREACHABLE(); + } + return address; +} + +void LLVMStackMapParser::IterateCallSiteInfo(const CallSiteInfo *infos, std::set &baseSet, + ChunkMap *data, uintptr_t callsiteFp, uintptr_t callSiteSp) const +{ + CallSiteInfo callsiteInfo = *infos; + ASSERT(callsiteInfo.size() % 2 == 0); + for (size_t j = 0; j < callsiteInfo.size(); j += 2) { + const DwarfRegAndOffsetType baseInfo = callsiteInfo[j]; + const DwarfRegAndOffsetType derivedInfo = (*infos)[j + 1]; + uintptr_t base = GetStackAddress(baseInfo, callSiteSp, callsiteFp); + uintptr_t derived = GetStackAddress(derivedInfo, callSiteSp, callsiteFp); + baseSet.emplace(base); + if (base != derived) { +#if ECMASCRIPT_ENABLE_HEAP_VERIFY + if (!isVerifying) { +#endif + data->emplace(std::make_pair(base, derived), *reinterpret_cast(base)); +#if ECMASCRIPT_ENABLE_HEAP_VERIFY + } +#endif + } + + } +} + +bool LLVMStackMapParser::CollectStackMapSlots(uintptr_t callSiteAddr, uintptr_t callsiteFp, + std::set &baseSet, ChunkMap *data, [[maybe_unused]] bool isVerifying, + uintptr_t callSiteSp) const +{ + const CallSiteInfo *infos = GetCallSiteInfoByPc(callSiteAddr); + if (infos == nullptr) { + return false; + } + ASSERT(callsiteFp != callSiteSp); + IterateCallSiteInfo(infos, baseSet, data, callsiteFp, callSiteSp); + + if (IsLogEnabled()) { + PrintCallSiteInfo(infos, callsiteFp, callSiteSp); + } + return true; +} + +void LLVMStackMapParser::CalcCallSite() +{ + uint64_t recordNum = 0; + Pc2CallSiteInfo pc2CallSiteInfo; + Pc2ConstInfo pc2ConstInfo; + auto calStkMapRecordFunc = [this, &recordNum, &pc2CallSiteInfo, &pc2ConstInfo](uintptr_t address, int recordId) { + struct StkMapRecordHeadTy recordHead = llvmStackMap_.StkMapRecord[recordNum + recordId].head; + for (int j = 0; j < recordHead.NumLocations; j++) { + struct LocationTy loc = llvmStackMap_.StkMapRecord[recordNum + recordId].Locations[j]; + uint32_t instructionOffset = recordHead.InstructionOffset; + uintptr_t callsite = address + instructionOffset; + uint64_t patchPointID = recordHead.PatchPointID; + if (loc.location == LocationTy::Kind::INDIRECT) { + COMPILER_OPTIONAL_LOG(DEBUG) << "DwarfRegNum:" << loc.DwarfRegNum << " loc.OffsetOrSmallConstant:" + << loc.OffsetOrSmallConstant << "address:" << address << " instructionOffset:" << + instructionOffset << " callsite:" << " patchPointID :" << std::hex << patchPointID << + callsite; + DwarfRegAndOffsetType info(loc.DwarfRegNum, loc.OffsetOrSmallConstant); + auto it = pc2CallSiteInfo.find(callsite); + if (pc2CallSiteInfo.find(callsite) == pc2CallSiteInfo.end()) { + pc2CallSiteInfo.insert(std::pair(callsite, {info})); + } else { + it->second.emplace_back(info); + } + } else if (loc.location == LocationTy::Kind::CONSTANT) { + if (j >= LocationTy::CONSTANT_FIRST_ELEMENT_INDEX) { + pc2ConstInfo[callsite].push_back(loc.OffsetOrSmallConstant); + } + } + } + }; + for (size_t i = 0; i < llvmStackMap_.StkSizeRecords.size(); i++) { + uintptr_t address = llvmStackMap_.StkSizeRecords[i].functionAddress; + uint64_t recordCount = llvmStackMap_.StkSizeRecords[i].recordCount; + for (uint64_t k = 0; k < recordCount; k++) { + calStkMapRecordFunc(address, k); + } + recordNum += recordCount; + } + pc2CallSiteInfoVec_.emplace_back(pc2CallSiteInfo); + pc2ConstInfoVec_.emplace_back(pc2ConstInfo); +} + +bool LLVMStackMapParser::CalculateStackMap(std::unique_ptr stackMapAddr) +{ + if (!stackMapAddr) { + COMPILER_LOG(ERROR) << "stackMapAddr nullptr error ! "; + return false; + } + dataInfo_ = std::make_unique(std::move(stackMapAddr)); + llvmStackMap_.head = dataInfo_->Read(); + uint32_t numFunctions, numConstants, numRecords; + numFunctions = dataInfo_->Read(); + numConstants = dataInfo_->Read(); + numRecords = dataInfo_->Read(); + for (uint32_t i = 0; i < numFunctions; i++) { + auto stkRecord = dataInfo_->Read(); + llvmStackMap_.StkSizeRecords.push_back(stkRecord); + } + + for (uint32_t i = 0; i < numConstants; i++) { + auto val = dataInfo_->Read(); + llvmStackMap_.Constants.push_back(val); + } + for (uint32_t i = 0; i < numRecords; i++) { + struct StkMapRecordTy stkSizeRecord; + auto head = dataInfo_->Read(); + stkSizeRecord.head = head; + for (uint16_t j = 0; j < head.NumLocations; j++) { + auto location = dataInfo_->Read(); + stkSizeRecord.Locations.push_back(location); + } + while (dataInfo_->GetOffset() & 7) { // 7: 8 byte align + dataInfo_->Read(); + } + uint32_t numLiveOuts = dataInfo_->Read(); + if (numLiveOuts > 0) { + for (uint32_t j = 0; j < numLiveOuts; j++) { + auto liveOut = dataInfo_->Read(); + stkSizeRecord.LiveOuts.push_back(liveOut); + } + } + while (dataInfo_->GetOffset() & 7) { // 7: 8 byte align + dataInfo_->Read(); + } + llvmStackMap_.StkMapRecord.push_back(stkSizeRecord); + } + CalcCallSite(); + return true; +} + +bool LLVMStackMapParser::CalculateStackMap(std::unique_ptr stackMapAddr, + uintptr_t hostCodeSectionAddr, uintptr_t deviceCodeSectionAddr) +{ + bool ret = CalculateStackMap(std::move(stackMapAddr)); + if (!ret) { + return ret; + } + + // update functionAddress from host side to device side + COMPILER_OPTIONAL_LOG(DEBUG) << "stackmap calculate update funcitonaddress "; + + for (size_t i = 0; i < llvmStackMap_.StkSizeRecords.size(); i++) { + uintptr_t hostAddr = llvmStackMap_.StkSizeRecords[i].functionAddress; + uintptr_t deviceAddr = hostAddr - hostCodeSectionAddr + deviceCodeSectionAddr; + llvmStackMap_.StkSizeRecords[i].functionAddress = deviceAddr; + COMPILER_OPTIONAL_LOG(DEBUG) << std::dec << i << "th function " << std::hex << hostAddr << " ---> " + << deviceAddr; + } + CalcCallSite(); + return true; +} + +void LLVMStackMapParser::CalculateFuncFpDelta(Func2FpDelta info) +{ + bool find = std::find(fun2FpDelta_.begin(), fun2FpDelta_.end(), info) == fun2FpDelta_.end(); + if (!info.empty() && find) { + fun2FpDelta_.emplace_back(info); + } + for (auto &it: info) { + funAddr_.insert(it.first); + } +} + +int LLVMStackMapParser::FindFpDelta(uintptr_t funcAddr, uintptr_t callsitePc) const +{ + int delta = 0; + // next optimization can be performed via sorted/map. + for (auto &info: fun2FpDelta_) { + if (info.find(funcAddr) != info.end()) { + delta = info.at(funcAddr).first; + uint32_t funcSize = info.at(funcAddr).second; + if (callsitePc <= funcAddr + funcSize && callsitePc >= funcAddr) { + return delta; + } + } + } + return delta; +} + +int LLVMStackMapParser::GetFuncFpDelta(uintptr_t callsitePc) const +{ + int delta = 0; + auto itupper = funAddr_.upper_bound(callsitePc); + if (itupper != funAddr_.end()) { // find first element >= callsitePc + --itupper; + // callsitePC may jscall or entry, thus not existed in funAddr_ + if ((itupper == funAddr_.end()) || (*itupper > callsitePc)) { + return delta; + } + delta = FindFpDelta(*itupper, callsitePc); + } else { + auto rit = funAddr_.crbegin(); // find last element + // callsitePC may jscall or entry, thus not existed in funAddr_ + if ((rit == funAddr_.crend()) || (*rit > callsitePc)) { + return delta; + } + delta = FindFpDelta(*rit, callsitePc); + } + return delta; +} +} // namespace panda::ecmascript::kungfu diff --git a/ecmascript/llvm_stackmap_parser.h b/ecmascript/llvm_stackmap_parser.h new file mode 100644 index 00000000..29806edf --- /dev/null +++ b/ecmascript/llvm_stackmap_parser.h @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ECMASCRIPT_LLVMSTACKPARSE_ +#define ECMASCRIPT_LLVMSTACKPARSE_ + +#include +#include +#include +#include +#include +#include "ecmascript/common.h" +#include "ecmascript/ecma_macros.h" +#include "ecmascript/interpreter/interpreter-inl.h" + +namespace panda::ecmascript::kungfu { +using OffsetType = int32_t; +using DwarfRegType = uint16_t; +using DwarfRegAndOffsetType = std::pair; +using CallSiteInfo = std::vector; +using Fun2InfoType = std::pair; +using Pc2CallSiteInfo = std::unordered_map; +using FpDelta = std::pair; +using Func2FpDelta = std::unordered_map; // value: fpDelta & funcSize +using ConstInfo = std::vector; +using Pc2ConstInfo = std::unordered_map; + +struct Header { + uint8_t stackmapversion; // Stack Map Version (current version is 3) + uint8_t Reserved0; // Reserved (expected to be 0) + uint16_t Reserved1; // Reserved (expected to be 0) + void Print() const + { + COMPILER_LOG(DEBUG) << "----- head ----"; + COMPILER_LOG(DEBUG) << " version:" << static_cast(stackmapversion); + COMPILER_LOG(DEBUG) << "+++++ head ++++"; + } +}; + +#pragma pack(1) +struct StkSizeRecordTy { + uintptr_t functionAddress; + uint64_t stackSize; + uint64_t recordCount; + void Print() const + { + COMPILER_LOG(DEBUG) << " functionAddress:0x" << std::hex << functionAddress; + COMPILER_LOG(DEBUG) << " stackSize:0x" << std::hex << stackSize; + COMPILER_LOG(DEBUG) << " recordCount:" << std::hex << recordCount; + } +}; +#pragma pack() + +struct ConstantsTy { + uintptr_t LargeConstant; + void Print() const + { + COMPILER_LOG(DEBUG) << " LargeConstant:0x" << std::hex << LargeConstant; + } +}; + +struct StkMapRecordHeadTy { + uint64_t PatchPointID; + uint32_t InstructionOffset; + uint16_t Reserved; + uint16_t NumLocations; + void Print() const + { + COMPILER_LOG(DEBUG) << " PatchPointID:0x" << std::hex << PatchPointID; + COMPILER_LOG(DEBUG) << " instructionOffset:0x" << std::hex << InstructionOffset; + COMPILER_LOG(DEBUG) << " Reserved:0x" << std::hex << Reserved; + COMPILER_LOG(DEBUG) << " NumLocations:0x" << std::hex << NumLocations; + } +}; + +struct LocationTy { + enum class Kind: uint8_t { + REGISTER = 1, + DIRECT = 2, + INDIRECT = 3, + CONSTANT = 4, + CONSTANTNDEX = 5, + }; + static constexpr int CONSTANT_FIRST_ELEMENT_INDEX = 3; + Kind location; + uint8_t Reserved_0; + uint16_t LocationSize; + uint16_t DwarfRegNum; + uint16_t Reserved_1; + OffsetType OffsetOrSmallConstant; + + std::string PUBLIC_API TypeToString(Kind loc) const; + + void Print() const + { + COMPILER_LOG(DEBUG) << TypeToString(location); + COMPILER_LOG(DEBUG) << ", size:" << std::dec << LocationSize; + COMPILER_LOG(DEBUG) << "\tDwarfRegNum:" << DwarfRegNum; + COMPILER_LOG(DEBUG) << "\t OffsetOrSmallConstant:" << OffsetOrSmallConstant; + } +}; + +struct LiveOutsTy { + DwarfRegType DwarfRegNum; + uint8_t Reserved; + uint8_t SizeinBytes; + void Print() const + { + COMPILER_LOG(DEBUG) << " Dwarf RegNum:" << DwarfRegNum; + COMPILER_LOG(DEBUG) << " Reserved:" << Reserved; + COMPILER_LOG(DEBUG) << " SizeinBytes:" << SizeinBytes; + } +}; + +struct StkMapRecordTy { + struct StkMapRecordHeadTy head; + std::vector Locations; + std::vector LiveOuts; + void Print() const + { + head.Print(); + auto size = Locations.size(); + for (size_t i = 0; i < size; i++) { + COMPILER_LOG(DEBUG) << " #" << std::dec << i << ":"; + Locations[i].Print(); + } + size = LiveOuts.size(); + for (size_t i = 0; i < size; i++) { + COMPILER_LOG(DEBUG) << " liveOuts[" << i << "] info:"; + } + } +}; + +class DataInfo { +public: + explicit DataInfo(std::unique_ptr data): data_(std::move(data)), offset_(0) {} + ~DataInfo() + { + data_.reset(); + offset_ = 0; + } + template + T Read() + { + T t = *reinterpret_cast(data_.get() + offset_); + offset_ += sizeof(T); + return t; + } + unsigned int GetOffset() const + { + return offset_; + } +private: + std::unique_ptr data_ {nullptr}; + unsigned int offset_ {0}; +}; + +struct LLVMStackMap { + struct Header head; + std::vector StkSizeRecords; + std::vector Constants; + std::vector StkMapRecord; + void Print() const + { + head.Print(); + for (size_t i = 0; i < StkSizeRecords.size(); i++) { + COMPILER_LOG(DEBUG) << "stkSizeRecord[" << i << "] info:"; + StkSizeRecords[i].Print(); + } + for (size_t i = 0; i < Constants.size(); i++) { + COMPILER_LOG(DEBUG) << "constants[" << i << "] info:"; + Constants[i].Print(); + } + for (size_t i = 0; i < StkMapRecord.size(); i++) { + COMPILER_LOG(DEBUG) << "StkMapRecord[" << i << "] info:"; + StkMapRecord[i].Print(); + } + } +}; + +class LLVMStackMapParser { +public: + bool PUBLIC_API CalculateStackMap(std::unique_ptr stackMapAddr); + bool PUBLIC_API CalculateStackMap(std::unique_ptr stackMapAddr, + uintptr_t hostCodeSectionAddr, uintptr_t deviceCodeSectionAddr); + void PUBLIC_API Print() const + { + if (IsLogEnabled()) { + llvmStackMap_.Print(); + } + } + const CallSiteInfo *GetCallSiteInfoByPc(uintptr_t funcAddr) const; + bool CollectStackMapSlots(uintptr_t callSiteAddr, uintptr_t callsiteFp, + std::set &baseSet, ChunkMap *data, + [[maybe_unused]] bool isVerifying, + uintptr_t callSiteSp) const; + bool IsLogEnabled() const + { + return enableLog_; + } + + void PUBLIC_API CalculateFuncFpDelta(Func2FpDelta info); + int PUBLIC_API GetFuncFpDelta(uintptr_t callsitePc) const; + ConstInfo GetConstInfo(uintptr_t callsite) + { + // next optimization can be performed via sorted/map to accelerate the search + for (auto &pc2ConstInfo : pc2ConstInfoVec_) { + auto it = pc2ConstInfo.find(callsite); + if (it != pc2ConstInfo.end()) { + return pc2ConstInfo[callsite]; + } + } + return {}; + } + + explicit LLVMStackMapParser(bool enableLog = false) + { + pc2CallSiteInfoVec_.clear(); + dataInfo_ = nullptr; + enableLog_ = enableLog; + funAddr_.clear(); + fun2FpDelta_.clear(); + pc2ConstInfoVec_.clear(); + } + ~LLVMStackMapParser() + { + pc2CallSiteInfoVec_.clear(); + dataInfo_ = nullptr; + funAddr_.clear(); + fun2FpDelta_.clear(); + pc2ConstInfoVec_.clear(); + } +private: + void CalcCallSite(); + void PrintCallSiteInfo(const CallSiteInfo *infos, OptimizedLeaveFrame *frame) const; + void PrintCallSiteInfo(const CallSiteInfo *infos, uintptr_t callSiteFp, uintptr_t callSiteSp) const; + int FindFpDelta(uintptr_t funcAddr, uintptr_t callsitePc) const; + inline uintptr_t GetStackAddress(const DwarfRegAndOffsetType info, + uintptr_t callSiteSp, uintptr_t callsiteFp) const; + void IterateCallSiteInfo(const CallSiteInfo *infos, std::set &baseSet, + ChunkMap *data, uintptr_t callsiteFp, uintptr_t callSiteSp) const; + void PrintCallSiteSlotAddr(const CallSiteInfo& callsiteInfo, uintptr_t callSiteSp, + uintptr_t callsiteFp) const; + + struct LLVMStackMap llvmStackMap_; + std::vector pc2CallSiteInfoVec_; + [[maybe_unused]] std::unique_ptr dataInfo_; + bool enableLog_ {false}; + std::set funAddr_; + std::vector fun2FpDelta_; + std::vector pc2ConstInfoVec_; +}; +} // namespace panda::ecmascript::kungfu +#endif // ECMASCRIPT_LLVMSTACKPARSE_ \ No newline at end of file diff --git a/ecmascript/stubs/runtime_stubs-inl.h b/ecmascript/stubs/runtime_stubs-inl.h index 2cf45b15..6cdf7900 100644 --- a/ecmascript/stubs/runtime_stubs-inl.h +++ b/ecmascript/stubs/runtime_stubs-inl.h @@ -18,7 +18,7 @@ #include "runtime_stubs.h" #include "ecmascript/builtins/builtins_regexp.h" -#include "ecmascript/compiler/llvm/llvm_stackmap_parser.h" +#include "ecmascript/llvm_stackmap_parser.h" #include "ecmascript/ecma_string_table.h" #include "ecmascript/global_dictionary-inl.h" #include "ecmascript/global_env.h" -- Gitee From d45b3095fc8bf68c127651f1a40f0483f7b11067 Mon Sep 17 00:00:00 2001 From: songzhengchao Date: Sat, 11 Jun 2022 20:47:30 +0800 Subject: [PATCH 003/154] refactor frameHandler refactor frame add FrameIterator to visit frame issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5BSW4 Signed-off-by: songzhengchao Change-Id: Ieb408a2334098043e504a8527aac008b8d0181a1 --- BUILD.gn | 1 + ecmascript/frames.cpp | 31 +++++++++++ ecmascript/frames.h | 64 ++++++++++++++++++++++ ecmascript/interpreter/frame_handler.cpp | 69 +++++++++--------------- 4 files changed, 121 insertions(+), 44 deletions(-) create mode 100644 ecmascript/frames.cpp diff --git a/BUILD.gn b/BUILD.gn index 1fe8d7f3..9988b3a5 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -364,6 +364,7 @@ ecma_source = [ "ecmascript/ecma_string.cpp", "ecmascript/ecma_string_table.cpp", "ecmascript/ecma_vm.cpp", + "ecmascript/frames.cpp", "ecmascript/free_object.cpp", "ecmascript/file_loader.cpp", "ecmascript/llvm_stackmap_parser.cpp", diff --git a/ecmascript/frames.cpp b/ecmascript/frames.cpp new file mode 100644 index 00000000..de4902f6 --- /dev/null +++ b/ecmascript/frames.cpp @@ -0,0 +1,31 @@ +#include "ecmascript/frames.h" +namespace panda::ecmascript { + +#define IMPLEMENT_GET_FRAME(Frame) \ + template<> \ + Frame* FrameIterator::GetFrame() \ + { \ + return Frame::GetFrameFromSp(current_); \ + } + FRAME_LIST(IMPLEMENT_GET_FRAME) +#undef IMPLEMENT_GET_FRAME + +void FrameIterator::Advance() +{ + ASSERT(!done()); + FrameType t = GetFrameType(); + switch (t) { + #define CASE(FRAME, Type) \ + case FrameType::Type : { \ + auto frame = GetFrame(); \ + current_ = frame->GetPrevFrameFp(); \ + break; \ + } + FRAME_AND_TYPE_LIST(CASE) + #undef CASE + default: { + UNREACHABLE(); + } + } +} +} // namespace panda::ecmascript \ No newline at end of file diff --git a/ecmascript/frames.h b/ecmascript/frames.h index 58f3ba27..a02ee387 100644 --- a/ecmascript/frames.h +++ b/ecmascript/frames.h @@ -817,5 +817,69 @@ struct BuiltinWithArgvFrame : public base::AlignedStruct( + reinterpret_cast(current_) - sizeof(FrameType)); + return *typeAddr; + } + template + Frame* GetFrame(); + + #define EXPLICIT_DECLARE_GET_FRAME(Frame) \ + template<> \ + Frame* GetFrame(); + FRAME_LIST(EXPLICIT_DECLARE_GET_FRAME) + #undef EXPLICIT_DECLARE_GET_FRAME + bool done() + { + return current_ == nullptr; + } + JSTaggedType *GetSp() + { + return current_; + } + void Advance(); +private: + JSTaggedType *current_; +}; } // namespace panda::ecmascript #endif // ECMASCRIPT_FRAMES_H diff --git a/ecmascript/interpreter/frame_handler.cpp b/ecmascript/interpreter/frame_handler.cpp index b9409abc..c567976e 100644 --- a/ecmascript/interpreter/frame_handler.cpp +++ b/ecmascript/interpreter/frame_handler.cpp @@ -73,7 +73,7 @@ void FrameHandler::PrevFrame() break; } case FrameType::LEAVE_FRAME_WITH_ARGV: { - auto frame = OptimizedLeaveFrame::GetFrameFromSp(sp_); + auto frame = OptimizedWithArgvLeaveFrame::GetFrameFromSp(sp_); sp_ = frame->GetPrevFrameFp(); break; } @@ -648,102 +648,83 @@ void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, isVerifying = thread_->GetEcmaVM()->GetHeap()->IsVerifying(); #endif JSTaggedType *current = start; - while (current) { - FrameType type = FrameHandler::GetFrameType(current); + for (FrameIterator it(current); !it.done(); it.Advance()) { + FrameType type = it.GetFrameType(); switch (type) { case FrameType::OPTIMIZED_FRAME: { - auto frame = OptimizedFrame::GetFrameFromSp(current); - auto prevFrame = frame->GetPrevFrameFp(); - OptimizedFrameIterate(current, v0, v1, derivedPointers, isVerifying); - optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current, optimizedReturnAddr_); - current = prevFrame; + auto frame = it.GetFrame(); + OptimizedFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(it.GetSp(), optimizedReturnAddr_); optimizedReturnAddr_ = frame->returnAddr; break; } case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME: { - OptimizedJSFunctionFrame *frame = OptimizedJSFunctionFrame::GetFrameFromSp(current); - optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current); + auto frame = it.GetFrame(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(it.GetSp()); optimizedReturnAddr_ = frame->returnAddr; - current = frame->GetPrevFrameFp(); break; } case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: { - auto frame = OptimizedJSFunctionFrame::GetFrameFromSp(current); - auto prevFrame = frame->GetPrevFrameFp(); - OptimizedJSFunctionFrameIterate(current, v0, v1, derivedPointers, isVerifying); - optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current, optimizedReturnAddr_); + auto frame = it.GetFrame(); + OptimizedJSFunctionFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(it.GetSp(), optimizedReturnAddr_); optimizedReturnAddr_ = frame->returnAddr; - current = prevFrame; break; } case FrameType::OPTIMIZED_ENTRY_FRAME: { - auto frame = OptimizedEntryFrame::GetFrameFromSp(current); - current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = 0; optimizedCallSiteSp_ = 0; break; } case FrameType::ASM_INTERPRETER_ENTRY_FRAME: { - auto frame = AsmInterpretedEntryFrame::GetFrameFromSp(current); - current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = 0; optimizedCallSiteSp_ = 0; break; } case FrameType::ASM_INTERPRETER_FRAME: case FrameType::INTERPRETER_CONSTRUCTOR_FRAME: { - auto frame = AsmInterpretedFrame::GetFrameFromSp(current); - AsmInterpretedFrameIterate(current, v0, v1, derivedPointers, isVerifying); - current = frame->GetPrevFrameFp(); + AsmInterpretedFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); optimizedReturnAddr_ = 0; optimizedCallSiteSp_ = 0; break; } case FrameType::INTERPRETER_FRAME: case FrameType::INTERPRETER_FAST_NEW_FRAME: { - auto frame = InterpretedFrame::GetFrameFromSp(current); - InterpretedFrameIterate(current, v0, v1); - current = frame->GetPrevFrameFp(); + InterpretedFrameIterate(it.GetSp(), v0, v1); optimizedReturnAddr_ = 0; optimizedCallSiteSp_ = 0; break; } case FrameType::LEAVE_FRAME: { - auto frame = OptimizedLeaveFrame::GetFrameFromSp(current); - OptimizedLeaveFrameIterate(current, v0, v1, derivedPointers, isVerifying); - optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current); - current = frame->GetPrevFrameFp(); + auto frame = it.GetFrame(); + OptimizedLeaveFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(it.GetSp()); optimizedReturnAddr_ = frame->returnAddr; break; } case FrameType::LEAVE_FRAME_WITH_ARGV: { - auto frame = OptimizedLeaveFrame::GetFrameFromSp(current); - OptimizedWithArgvLeaveFrameIterate(current, v0, v1, derivedPointers, isVerifying); - current = frame->GetPrevFrameFp(); + auto frame = it.GetFrame(); + OptimizedWithArgvLeaveFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(it.GetSp()); optimizedReturnAddr_ = frame->returnAddr; break; } case FrameType::BUILTIN_FRAME_WITH_ARGV: { - auto frame = BuiltinWithArgvFrame::GetFrameFromSp(current); - BuiltinWithArgvFrameIterate(current, v0, v1, derivedPointers, isVerifying); + auto frame = it.GetFrame(); + BuiltinWithArgvFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); optimizedReturnAddr_ = frame->returnAddr; - optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current); - current = frame->GetPrevFrameFp(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(it.GetSp()); break; } case FrameType::BUILTIN_ENTRY_FRAME: case FrameType::BUILTIN_FRAME: { - auto frame = BuiltinFrame::GetFrameFromSp(current); - BuiltinFrameIterate(current, v0, v1, derivedPointers, isVerifying); + auto frame = it.GetFrame(); + BuiltinFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); optimizedReturnAddr_ = frame->returnAddr; - optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(current); - current = frame->GetPrevFrameFp(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(it.GetSp()); break; } case FrameType::INTERPRETER_ENTRY_FRAME: { - auto frame = InterpretedEntryFrame::GetFrameFromSp(current); - InterpretedEntryFrameIterate(current, v0, v1); - current = frame->GetPrevFrameFp(); optimizedReturnAddr_ = 0; optimizedCallSiteSp_ = 0; break; -- Gitee From 95513b5ba5409e88dc0f1541394ff3e10d93c08c Mon Sep 17 00:00:00 2001 From: xdmal Date: Mon, 13 Jun 2022 16:08:00 +0800 Subject: [PATCH 004/154] Optimize the finalizationRegistry interface code according to the review Optimize the finalizationRegistry interface code according to the review issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5C10P Signed-off-by: xdmal --- .../tests/builtins_finalizationregistry_test.cpp | 16 ++++++++-------- ecmascript/js_finalization_registry.cpp | 9 --------- ecmascript/js_finalization_registry.h | 14 -------------- ecmascript/js_thread.h | 11 ----------- ecmascript/mem/heap.cpp | 4 +--- 5 files changed, 9 insertions(+), 45 deletions(-) diff --git a/ecmascript/builtins/tests/builtins_finalizationregistry_test.cpp b/ecmascript/builtins/tests/builtins_finalizationregistry_test.cpp index 7a864ddf..8b68e375 100644 --- a/ecmascript/builtins/tests/builtins_finalizationregistry_test.cpp +++ b/ecmascript/builtins/tests/builtins_finalizationregistry_test.cpp @@ -181,7 +181,7 @@ HWTEST_F_L0(BuiltinsFinalizationRegistryTest, Register2) { [[maybe_unused]] EcmaHandleScope handleScope(thread); auto obj = - factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); + factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); target = obj.GetTaggedValue(); auto ecmaRuntimeCallInfo = TestHelper::CreateEcmaRuntimeCallInfo(thread, JSTaggedValue::Undefined(), 10); ecmaRuntimeCallInfo->SetFunction(JSTaggedValue::Undefined()); @@ -220,9 +220,9 @@ HWTEST_F_L0(BuiltinsFinalizationRegistryTest, Register3) { [[maybe_unused]] EcmaHandleScope handleScope(thread); auto obj = - factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); + factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); auto obj1 = - factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); + factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); target = obj.GetTaggedValue(); target1 = obj1.GetTaggedValue(); auto ecmaRuntimeCallInfo = TestHelper::CreateEcmaRuntimeCallInfo(thread, JSTaggedValue::Undefined(), 10); @@ -274,9 +274,9 @@ HWTEST_F_L0(BuiltinsFinalizationRegistryTest, Register4) { [[maybe_unused]] EcmaHandleScope handleScope(thread); auto obj = - factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); + factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); auto obj1 = - factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); + factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); target = obj.GetTaggedValue(); target1 = obj1.GetTaggedValue(); auto ecmaRuntimeCallInfo = TestHelper::CreateEcmaRuntimeCallInfo(thread, JSTaggedValue::Undefined(), 10); @@ -326,9 +326,9 @@ HWTEST_F_L0(BuiltinsFinalizationRegistryTest, Register5) { [[maybe_unused]] EcmaHandleScope handleScope(thread); auto obj = - factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); + factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); auto obj1 = - factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); + factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); target = obj.GetTaggedValue(); target1 = obj1.GetTaggedValue(); auto ecmaRuntimeCallInfo = TestHelper::CreateEcmaRuntimeCallInfo(thread, JSTaggedValue::Undefined(), 10); @@ -411,7 +411,7 @@ HWTEST_F_L0(BuiltinsFinalizationRegistryTest, Unregister2) { [[maybe_unused]] EcmaHandleScope handleScope(thread); auto obj = - factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); + factory->NewJSObjectByConstructor(JSHandle(objectFunc), objectFunc); target = obj.GetTaggedValue(); auto ecmaRuntimeCallInfo = TestHelper::CreateEcmaRuntimeCallInfo(thread, JSTaggedValue::Undefined(), 10); ecmaRuntimeCallInfo->SetFunction(JSTaggedValue::Undefined()); diff --git a/ecmascript/js_finalization_registry.cpp b/ecmascript/js_finalization_registry.cpp index 8951fd82..021dea36 100644 --- a/ecmascript/js_finalization_registry.cpp +++ b/ecmascript/js_finalization_registry.cpp @@ -140,7 +140,6 @@ void JSFinalizationRegistry::CleanFinRegLists(JSThread *thread, JSHandle env = thread->GetEcmaVM()->GetGlobalEnv(); JSHandle prev = env->GetFinRegLists(); @@ -228,14 +227,6 @@ bool JSFinalizationRegistry::CleanupFinalizationRegistry(JSThread *thread, JSHan continue; } maybeUnregister->RemoveEntry(thread, index - 1); - // Maybe add or delete - JSTaggedValue nextTable = maybeUnregister->GetNextTable(); - while (!nextTable.IsHole()) { - index -= maybeUnregister->GetDeletedElementsAt(index); - maybeUnregister.Update(nextTable); - nextTable = maybeUnregister->GetNextTable(); - } - totalElements = maybeUnregister->NumberOfElements() + maybeUnregister->NumberOfDeletedElements(); } } JSHandle newMap = LinkedHashMap::Shrink(thread, maybeUnregister); diff --git a/ecmascript/js_finalization_registry.h b/ecmascript/js_finalization_registry.h index fff20249..df9b7d13 100644 --- a/ecmascript/js_finalization_registry.h +++ b/ecmascript/js_finalization_registry.h @@ -21,20 +21,6 @@ #include "ecmascript/weak_vector.h" namespace panda::ecmascript { -class CheckAndCallScrop { -public: - CheckAndCallScrop(JSThread *thread) : thread_(thread) - { - thread_->SetCheckAndCallEnterState(true); - } - ~CheckAndCallScrop() - { - thread_->SetCheckAndCallEnterState(false); - } -private: - JSThread *thread_; -}; - class CellRecord final : public Record { public: CAST_CHECK(CellRecord, IsCellRecord); diff --git a/ecmascript/js_thread.h b/ecmascript/js_thread.h index 6a766a61..295a175e 100644 --- a/ecmascript/js_thread.h +++ b/ecmascript/js_thread.h @@ -449,16 +449,6 @@ public: return gcState_; } - void SetCheckAndCallEnterState(bool checkAndCallEnterState) - { - checkAndCallEnterState_ = checkAndCallEnterState; - } - - bool GetCheckAndCallEnterState() const - { - return checkAndCallEnterState_; - } - void EnableAsmInterpreter() { isAsmInterpreter_ = true; @@ -657,7 +647,6 @@ private: bool stableArrayElementsGuardians_ {true}; GlueData glueData_; - bool checkAndCallEnterState_ {false}; friend class EcmaHandleScope; friend class GlobalHandleCollection; }; diff --git a/ecmascript/mem/heap.cpp b/ecmascript/mem/heap.cpp index 190f2456..63ec1cef 100644 --- a/ecmascript/mem/heap.cpp +++ b/ecmascript/mem/heap.cpp @@ -362,9 +362,7 @@ void Heap::CollectGarbage(TriggerGCType gcType) } isVerifying_ = false; #endif - if (!thread_->GetCheckAndCallEnterState()) { - JSFinalizationRegistry::CheckAndCall(thread_); - } + JSFinalizationRegistry::CheckAndCall(thread_); } void Heap::ThrowOutOfMemoryError(size_t size, std::string functionName) -- Gitee From 05765a69b4c02c0ea780604429fcbe9b8e4f5e35 Mon Sep 17 00:00:00 2001 From: zhangyouyou Date: Mon, 13 Jun 2022 17:00:40 +0800 Subject: [PATCH 005/154] https://gitee.com/openharmony/ark_ts2abc/issues/I5C02G Signed-off-by: zhangyouyou --- docs/development-example-zh.md | 12 ++++++++---- docs/development-example.md | 11 ++++++++--- test/run_test262.sh | 8 ++++---- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/docs/development-example-zh.md b/docs/development-example-zh.md index 8a53e172..9351fa05 100644 --- a/docs/development-example-zh.md +++ b/docs/development-example-zh.md @@ -260,16 +260,20 @@ python3 test262/run_test262.py [options] python3 test262/run_test262.py --es51 ``` -- 仅运行ES2015测试用: +- 仅运行ES2015测试用例: ``` - python3 test262/run_test262.py --es2015 only + python3 test262/run_test262.py --es2015 ``` +- 仅运行ES2021测试用例: -- 运行ES2015和ES51所有测试用例: + ``` + python3 test262/run_test262.py --es2021 only + +- 运行ES2015和ES51和ES2021所有测试用例: ``` - python3 test262/run_test262.py --es2015 all + python3 test262/run_test262.py --es2021 all ``` - 运行单一测试用例: diff --git a/docs/development-example.md b/docs/development-example.md index 444e4a42..62d73c07 100644 --- a/docs/development-example.md +++ b/docs/development-example.md @@ -251,13 +251,18 @@ Run the script in _Project root directory_**/ark/ts2abc**. - Run test case ES2015 only. ``` - python3 test262/run_test262.py --es2015 only + python3 test262/run_test262.py --es2015 ``` -- Run all ES2015 and ES51 test cases. +- Run test case ES2021 only. ``` - python3 test262/run_test262.py --es2015 all + python3 test262/run_test262.py --es2021 only + +- Run all ES2015 and ES51 and ES2021 test cases. + + ``` + python3 test262/run_test262.py --es2021 all ``` - Run a test case. diff --git a/test/run_test262.sh b/test/run_test262.sh index 43539778..233a493c 100644 --- a/test/run_test262.sh +++ b/test/run_test262.sh @@ -26,12 +26,12 @@ pushd ark/ts2abc pushd ../../ if [ -d out/rk3568 ];then pushd ark/ts2abc - python3 test262/run_test262.py --es2015 all --threads=16 --libs-dir ../../out/rk3568/clang_x64/ark/ark:../../out/rk3568/clang_x64/ark/ark_js_runtime:../../out/rk3568/clang_x64/thirdparty/icu:../../prebuilts/clang/ohos/linux-x86_64/llvm/lib --ark-tool=../../out/rk3568/clang_x64/ark/ark_js_runtime/ark_js_vm --ark-frontend-tool=../../out/rk3568/clang_x64/ark/ark/build/src/index.js + python3 test262/run_test262.py --es2021 all --threads=16 --libs-dir ../../out/rk3568/clang_x64/ark/ark:../../out/rk3568/clang_x64/ark/ark_js_runtime:../../out/rk3568/clang_x64/thirdparty/icu:../../prebuilts/clang/ohos/linux-x86_64/llvm/lib --ark-tool=../../out/rk3568/clang_x64/ark/ark_js_runtime/ark_js_vm --ark-frontend-tool=../../out/rk3568/clang_x64/ark/ark/build/src/index.js popd fi if [ -d out/hispark_taurus ];then pushd ark/ts2abc - python3 test262/run_test262.py --es2015 all --threads=16 --libs-dir ../../out/hispark_taurus/clang_x64/ark/ark:../../out/hispark_taurus/clang_x64/ark/ark_js_runtime:../../out/hispark_taurus/clang_x64/thirdparty/icu:../../prebuilts/clang/ohos/linux-x86_64/llvm/lib --ark-tool=../../out/hispark_taurus/clang_x64/ark/ark_js_runtime/ark_js_vm --ark-frontend-tool=../../out/hispark_taurus/clang_x64/ark/ark/build/src/index.js + python3 test262/run_test262.py --es2021 all --threads=16 --libs-dir ../../out/hispark_taurus/clang_x64/ark/ark:../../out/hispark_taurus/clang_x64/ark/ark_js_runtime:../../out/hispark_taurus/clang_x64/thirdparty/icu:../../prebuilts/clang/ohos/linux-x86_64/llvm/lib --ark-tool=../../out/hispark_taurus/clang_x64/ark/ark_js_runtime/ark_js_vm --ark-frontend-tool=../../out/hispark_taurus/clang_x64/ark/ark/build/src/index.js popd fi popd @@ -46,10 +46,10 @@ pushd ark/ts2abc exit 1; fi - cp out/test262/result.txt report/result_es2015_${time}.txt + cp out/test262/result.txt report/result_es2021_${time}.txt pushd report - es2015_fail=$(grep FAIL result_es2015_${time}.txt | wc -l) + es2015_fail=$(grep FAIL result_es2021_${time}.txt | wc -l) threshold=0 if [ ${es2015_fail} -gt ${threshold} ];then echo 'test262 fail case over thresgold' -- Gitee From cd642b8bdab64de41f913e4731335e55b36cc35e Mon Sep 17 00:00:00 2001 From: DaiH Date: Fri, 10 Jun 2022 14:50:14 +0800 Subject: [PATCH 006/154] Modification of compilation commands ------------------------------------ "rk3568" --> "hispark_taurus_standard" issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5BP4B?from=project-issue Signed-off-by: DaiH Change-Id: I76420f696d9f7a2174b9018a1f7754eaa1fdb4d8 --- README.md | 4 ++-- README_zh.md | 4 ++-- docs/development-example-zh.md | 16 ++++++++-------- docs/development-example.md | 14 +++++++------- docs/environment-setup-and-compilation-zh.md | 12 ++++++------ docs/environment-setup-and-compilation.md | 12 ++++++------ docs/using-the-toolchain-zh.md | 4 ++-- docs/using-the-toolchain.md | 4 ++-- 8 files changed, 35 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 49559d09..901b52c3 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ For more information, see: [ARK Runtime Subsystem](https://gitee.com/openharmony ## Build ``` -./build.sh --product-name rk3568 --build-target ark_js_host_linux_tools_packages +./build.sh --product-name hispark_taurus_standard --build-target ark_js_host_linux_tools_packages ``` ### Available APIs @@ -68,7 +68,7 @@ For details about how to generate JS bytecodes, see [Using the Toolchain](docs/ To run bytecodes: ``` -LD_LIBRARY_PATH=out/rk3568/clang_x64/ark/ark:out/rk3568/clang_x64/ark/ark_js_runtime:out/rk3568/clang_x64/thirdparty/icu:prebuilts/clang/ohos/linux-x86_64/llvm/lib ./out/rk3568/clang_x64/ark/ark_js_runtime/ark_js_vm helloworld.abc +LD_LIBRARY_PATH=out/hispark_taurus/clang_x64/ark/ark:out/hispark_taurus/clang_x64/ark/ark_js_runtime:out/hispark_taurus/clang_x64/thirdparty/icu:prebuilts/clang/ohos/linux-x86_64/llvm/lib ./out/hispark_taurus/clang_x64/ark/ark_js_runtime/ark_js_vm helloworld.abc ``` For more information, please see: [ARK-Runtime-Usage-Guide](https://gitee.com/openharmony/ark_js_runtime/blob/master/docs/ARK-Runtime-Usage-Guide.md). diff --git a/README_zh.md b/README_zh.md index 3dce8938..4b108eb4 100644 --- a/README_zh.md +++ b/README_zh.md @@ -57,7 +57,7 @@ ## 编译构建 ``` -$./build.sh --product-name rk3568 --build-target ark_js_host_linux_tools_packages +$./build.sh --product-name hispark_taurus_standard --build-target ark_js_host_linux_tools_packages ``` ### 接口说明 @@ -70,7 +70,7 @@ JS生成字节码参考[工具链使用](docs/using-the-toolchain-zh.md) 字节码执行: ``` -LD_LIBRARY_PATH=out/rk3568/clang_x64/ark/ark:out/rk3568/clang_x64/ark/ark_js_runtime:out/rk3568/clang_x64/thirdparty/icu:prebuilts/clang/ohos/linux-x86_64/llvm/lib ./out/rk3568/clang_x64/ark/ark_js_runtime/ark_js_vm helloworld.abc +LD_LIBRARY_PATH=out/hispark_taurus/clang_x64/ark/ark:out/hispark_taurus/clang_x64/ark/ark_js_runtime:out/hispark_taurus/clang_x64/thirdparty/icu:prebuilts/clang/ohos/linux-x86_64/llvm/lib ./out/hispark_taurus/clang_x64/ark/ark_js_runtime/ark_js_vm helloworld.abc ``` diff --git a/docs/development-example-zh.md b/docs/development-example-zh.md index 8a53e172..e3032896 100644 --- a/docs/development-example-zh.md +++ b/docs/development-example-zh.md @@ -37,7 +37,7 @@ 2. 编译方舟前端,编译命令: ``` - ./build.sh --product-name rk3568 --build-target ark_ts2abc_build + ./build.sh --product-name hispark_taurus_standard --build-target ark_ts2abc_build ``` **说明**:上述编译命令为release版本,且执行路径为项目根目录。编译debug版本需增加编译选项:--gn-args is_debug=true。 @@ -55,20 +55,20 @@ 1. 通过方舟前端生成hello-world.abc文件,编译命令: ``` - node --expose-gc /your code path/out/rk3568/clang_x64/ark/ark/build/src/index.js hello-world.js + node --expose-gc /your code path/out/hispark_taurus/clang_x64/ark/ark/build/src/index.js hello-world.js ``` 2. 执行hello-world.abc文件: 1. 设置搜索路径: ``` - export LD_LIBRARY_PATH= /your code path/out/rk3568/clang_x64/ark/ark:/your code path/out/rk3568/clang_x64/ark/ark_js_runtime:/your code path/out/rk3568/clang_x64/global/i18n_standard:/your code path/prebuilts/clang/ohos/linux-x86_64/llvm/lib + export LD_LIBRARY_PATH= /your code path/out/hispark_taurus/clang_x64/ark/ark:/your code path/out/hispark_taurus/clang_x64/ark/ark_js_runtime:/your code path/out/hispark_taurus/clang_x64/global/i18n_standard:/your code path/prebuilts/clang/ohos/linux-x86_64/llvm/lib ``` 2. 执行ark\_js\_vm: ``` - /your code path/out/rk3568/clang_x64/ark/ark_js_runtime/ark_js_vm hello-world.abc + /your code path/out/hispark_taurus/clang_x64/ark/ark_js_runtime/ark_js_vm hello-world.abc ``` 执行结果如下: @@ -92,7 +92,7 @@ 执行如下命令,结果输出到output.pa文件中: ``` -./your code path/out/rk3568/clang_x64/ark/ark/ark_disasm hello-world.abc output.pa +./your code path/out/hispark_taurus/clang_x64/ark/ark/ark_disasm hello-world.abc output.pa ``` hello-world.abc反汇编结果如下: @@ -139,13 +139,13 @@ hello-world.abc反汇编结果如下: 1. 编译方舟运行时,编译命令: ``` -./build.sh --product-name rk3568 --build-target ark_js_host_linux_tools_packages +./build.sh --product-name hispark_taurus_standard --build-target ark_js_host_linux_tools_packages ``` 1. 编译方舟前端,编译命令: ``` -./build.sh --product-name rk3568 --build-target ark_ts2abc_build +./build.sh --product-name hispark_taurus_standard --build-target ark_ts2abc_build ``` **说明**:编译命令执行路径为项目根目录。 @@ -305,7 +305,7 @@ node test262/harness/bin/run.js --hostType=panda --hostPath=python3 - --hostArgs='-B test262/run_sunspider.py --ark-tool=/your code path/out/rk3568/clang_x64/ark/ark_js_runtime/ark_js_vm --ark-frontend-tool=/your code path/out/rk3568/clang_x64/ark/ark/build/src/index.js --libs-dir=/your code path/out/rk3568/clang_x64/ark/ark:/your code path/out/rk3568/clang_x64/global/i18n:/your code path/prebuilts/clang/ohos/linux-x86_64/llvm/lib/ --ark-frontend=ts2panda' + --hostArgs='-B test262/run_sunspider.py --ark-tool=/your code path/out/hispark_taurus/clang_x64/ark/ark_js_runtime/ark_js_vm --ark-frontend-tool=/your code path/out/hispark_taurus/clang_x64/ark/ark/build/src/index.js --libs-dir=/your code path/out/hispark_taurus/clang_x64/ark/ark:/your code path/out/hispark_taurus/clang_x64/global/i18n:/your code path/prebuilts/clang/ohos/linux-x86_64/llvm/lib/ --ark-frontend=ts2panda' --threads=15 --mode=only strict mode --timeout=60000 diff --git a/docs/development-example.md b/docs/development-example.md index 444e4a42..f96c8268 100644 --- a/docs/development-example.md +++ b/docs/development-example.md @@ -48,20 +48,20 @@ Run the **hello-world.js** file. 1. Use the ARK frontend to create the **hello-world.abc** file. ``` - node --expose-gc /your code path/out/rk3568/clang_x64/ark/ark/build/src/index.js hello-world.js + node --expose-gc /your code path/out/hispark_taurus/clang_x64/ark/ark/build/src/index.js hello-world.js ``` 2. Run the **hello-world.abc** file. 1. Set the search path. ``` - export LD_LIBRARY_PATH= out/rk3568/clang_x64/ark/ark:out/rk3568/clang_x64/ark/ark_js_runtime:out/rk3568/clang_x64/global/i18n_standard:prebuilts/clang/ohos/linux-x86_64/llvm/lib + export LD_LIBRARY_PATH= out/hispark_taurus/clang_x64/ark/ark:out/hispark_taurus/clang_x64/ark/ark_js_runtime:out/hispark_taurus/clang_x64/global/i18n_standard:prebuilts/clang/ohos/linux-x86_64/llvm/lib ``` 2. Run **ark\_js\_vm**. ``` - /your code path/out/rk3568/clang_x64/ark/ark_js_runtime/ark_js_vm hello-world.abc + /your code path/out/hispark_taurus/clang_x64/ark/ark_js_runtime/ark_js_vm hello-world.abc ``` The execution result is as follows: @@ -77,7 +77,7 @@ Run the **hello-world.js** file. Run the following command to export the result to the **output** file: ``` -./your code path/out/rk3568/clang_x64/ark/ark/ark_disasm hello-world.abc output +./your code path/out/hispark_taurus/clang_x64/ark/ark/ark_disasm hello-world.abc output ``` The output is as follows: @@ -124,13 +124,13 @@ The output is as follows: 1. Run the following command to compile ARK runtime: ``` -./build.sh --product-name rk3568 --build-target ark_js_host_linux_tools_packages +./build.sh --product-name hispark_taurus_standard --build-target ark_js_host_linux_tools_packages ``` 2. Run the following command to compile the ARK frontend: ``` -./build.sh --product-name rk3568 --build-target ark_ts2abc_build +./build.sh --product-name hispark_taurus_standard --build-target ark_ts2abc_build ``` **NOTE**: Run the compilation commands in the project root directory. @@ -293,7 +293,7 @@ node test262/harness/bin/run.js --hostType=panda --hostPath=python3 - --hostArgs='-B test262/run_sunspider.py --ark-tool=/your code path/out/rk3568/clang_x64/ark/ark_js_runtime/ark_js_vm --ark-frontend-tool=/your code path/out/rk3568/clang_x64/ark/ark/build/src/index.js --libs-dir=/your code path/out/rk3568/clang_x64/ark/ark:/your code path/out/rk3568/clang_x64/global/i18n:/your code path/prebuilts/clang/ohos/linux-x86_64/llvm/lib/ --ark-frontend=ts2panda' + --hostArgs='-B test262/run_sunspider.py --ark-tool=/your code path/out/hispark_taurus/clang_x64/ark/ark_js_runtime/ark_js_vm --ark-frontend-tool=/your code path/out/hispark_taurus/clang_x64/ark/ark/build/src/index.js --libs-dir=/your code path/out/hispark_taurus/clang_x64/ark/ark:/your code path/out/hispark_taurus/clang_x64/global/i18n:/your code path/prebuilts/clang/ohos/linux-x86_64/llvm/lib/ --ark-frontend=ts2panda' --threads=15 --mode=only strict mode --timeout=60000 diff --git a/docs/environment-setup-and-compilation-zh.md b/docs/environment-setup-and-compilation-zh.md index 47e6c176..4247a6ef 100644 --- a/docs/environment-setup-and-compilation-zh.md +++ b/docs/environment-setup-and-compilation-zh.md @@ -14,7 +14,7 @@ Ubuntu版本要求18.04或20.04,详细环境搭建参考: 1. 首次编译: ``` - ./build.sh --product-name rk3568 + ./build.sh --product-name hispark_taurus_standard ``` 2. 首次编译后增量编译方舟运行时: @@ -37,7 +37,7 @@ Ubuntu版本要求18.04或20.04,详细环境搭建参考: 3. 首次编译后增量编译方舟前端: ``` - ./build.sh --product-name rk3568 --build-target ark_ts2abc_build + ./build.sh --product-name hispark_taurus_standard --build-target ark_ts2abc_build ``` **说明**:上述编译命令为release版本,且执行路径为项目根目录。编译debug版本需增加编译选项:--gn-args is_debug=true。 @@ -45,9 +45,9 @@ Ubuntu版本要求18.04或20.04,详细环境搭建参考: 方舟相关的二进制文件在如下路径: ``` -out/rk3568/ark/ark/ -out/rk3568/ark/ark_js_runtime/ -out/rk3568/clang_x64/ark/ark/ -out/rk3568/clang_x64/ark/ark_js_runtime +out/hispark_taurus/ark/ark/ +out/hispark_taurus/ark/ark_js_runtime/ +out/hispark_taurus/clang_x64/ark/ark/ +out/hispark_taurus/clang_x64/ark/ark_js_runtime ``` diff --git a/docs/environment-setup-and-compilation.md b/docs/environment-setup-and-compilation.md index d8d0bfed..51c94e61 100644 --- a/docs/environment-setup-and-compilation.md +++ b/docs/environment-setup-and-compilation.md @@ -11,7 +11,7 @@ Use Ubuntu 18.04 or 20.04. For details about how to set up the environment, see: 1. First compilation: ``` - ./build.sh --product-name rk3568 + ./build.sh --product-name hispark_taurus_standard ``` 2. Compile an ARK runtime after the first compilation: @@ -34,7 +34,7 @@ Use Ubuntu 18.04 or 20.04. For details about how to set up the environment, see: 3. Compile the ARK frontend after the first compilation: ``` - ./build.sh --product-name rk3568 --build-target ark_ts2abc_build + ./build.sh --product-name hispark_taurus_standard --build-target ark_ts2abc_build ``` **NOTE**: Run the compilation commands in the project root directory. @@ -42,8 +42,8 @@ Use Ubuntu 18.04 or 20.04. For details about how to set up the environment, see: The binary files related to ARK are available in the following paths: ``` -out/rk3568/ark/ark/ -out/rk3568/ark/ark_js_runtime/ -out/rk3568/clang_x64/ark/ark/ -out/rk3568/clang_x64/ark/ark_js_runtime +out/hispark_taurus/ark/ark/ +out/hispark_taurus/ark/ark_js_runtime/ +out/hispark_taurus/clang_x64/ark/ark/ +out/hispark_taurus/clang_x64/ark/ark_js_runtime ``` diff --git a/docs/using-the-toolchain-zh.md b/docs/using-the-toolchain-zh.md index 50d48919..8ea6b4ec 100644 --- a/docs/using-the-toolchain-zh.md +++ b/docs/using-the-toolchain-zh.md @@ -9,13 +9,13 @@ 构建编译: ``` -$ ./build.sh --product-name rk3568 --build-target ark_ts2abc_build +$ ./build.sh --product-name hispark_taurus_standard --build-target ark_ts2abc_build ``` 安装`node`和`npm`后, 使用前端工具: ``` -$ cd out/rk3568/clang_x64/ark/ark/build +$ cd out/hispark_taurus/clang_x64/ark/ark/build $ npm install $ node --expose-gc src/index.js [选项] file.js ``` diff --git a/docs/using-the-toolchain.md b/docs/using-the-toolchain.md index 637170af..fe1b811a 100644 --- a/docs/using-the-toolchain.md +++ b/docs/using-the-toolchain.md @@ -9,13 +9,13 @@ Front-end tools, converting JS source code into ARK bytecode, can be built by sp Build tools: ``` -$ ./build.sh --product-name rk3568 --build-target ark_ts2abc +$ ./build.sh --product-name hispark_taurus_standard --build-target ark_ts2abc ``` Install `node` and `npm`, then use tools: ``` -$ cd out/rk3568/clang_x64/ark/ark/build +$ cd out/hispark_taurus/clang_x64/ark/ark/build $ npm install $ node --expose-gc src/index.js [option] file.js ``` -- Gitee From a8847d7c1913beb944c3bd768880ddf408ed79af Mon Sep 17 00:00:00 2001 From: songzhengchao Date: Tue, 14 Jun 2022 15:10:13 +0800 Subject: [PATCH 007/154] Code review issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5BSW4 Signed-off-by: songzhengchao Change-Id: I7b822d9bf29d5978f3fdaab4f7aee103421319d4 --- ecmascript/ecma_vm.cpp | 5 - ecmascript/ecma_vm.h | 2 - ecmascript/file_loader.cpp | 8 +- ecmascript/frames.cpp | 135 ++++++++++++++--------- ecmascript/frames.h | 26 +---- ecmascript/interpreter/frame_handler.cpp | 31 +++--- 6 files changed, 110 insertions(+), 97 deletions(-) diff --git a/ecmascript/ecma_vm.cpp b/ecmascript/ecma_vm.cpp index 7c317d16..793e8957 100644 --- a/ecmascript/ecma_vm.cpp +++ b/ecmascript/ecma_vm.cpp @@ -686,9 +686,4 @@ void EcmaVM::SetAOTFuncEntry(uint32_t hash, uint32_t methodId, uint64_t funcEntr { fileLoader_->SetAOTFuncEntry(hash, methodId, funcEntry); } - -kungfu::LLVMStackMapParser* EcmaVM::GetStackMapParser() -{ - return fileLoader_->GetStackMapParser(); -} } // namespace panda::ecmascript diff --git a/ecmascript/ecma_vm.h b/ecmascript/ecma_vm.h index 066ad12a..8931f4b2 100644 --- a/ecmascript/ecma_vm.h +++ b/ecmascript/ecma_vm.h @@ -337,8 +337,6 @@ public: void SetAOTFuncEntry(uint32_t hash, uint32_t methodId, uint64_t funcEntry); - kungfu::LLVMStackMapParser* GetStackMapParser(); - void StoreBCOffsetInfo(const std::string& methodName, int32_t bcOffset) { exceptionBCList_.emplace_back(std::pair(methodName, bcOffset)); diff --git a/ecmascript/file_loader.cpp b/ecmascript/file_loader.cpp index 9d23f25f..9f2d985d 100644 --- a/ecmascript/file_loader.cpp +++ b/ecmascript/file_loader.cpp @@ -100,7 +100,7 @@ bool StubModulePackInfo::Load(EcmaVM *vm, const std::string &filename) std::unique_ptr stackmapPtr(std::make_unique(stackmapSize)); moduleFile.read(reinterpret_cast(stackmapPtr.get()), stackmapSize); if (stackmapSize != 0) { - vm->GetStackMapParser()->CalculateStackMap(std::move(stackmapPtr), + vm->GetFileLoader()->GetStackMapParser()->CalculateStackMap(std::move(stackmapPtr), des_[i].GetHostCodeSecAddr(), startAddr); } } @@ -113,7 +113,7 @@ bool StubModulePackInfo::Load(EcmaVM *vm, const std::string &filename) kungfu::Func2FpDelta fun2fpDelta; auto funSize = funcEntryDes.funcSize_; fun2fpDelta[funAddr] = std::make_pair(delta, funSize); - vm->GetStackMapParser()->CalculateFuncFpDelta(fun2fpDelta); + vm->GetFileLoader()->GetStackMapParser()->CalculateFuncFpDelta(fun2fpDelta); } for (size_t i = 0; i < entries_.size(); i++) { auto des = des_[entries_[i].moduleIndex_]; @@ -192,7 +192,7 @@ bool AOTModulePackInfo::Load(EcmaVM *vm, const std::string &filename) std::unique_ptr stackmapPtr(std::make_unique(stackmapSize)); moduleFile.read(reinterpret_cast(stackmapPtr.get()), stackmapSize); if (stackmapSize != 0) { - vm->GetStackMapParser()->CalculateStackMap(std::move(stackmapPtr), + vm->GetFileLoader()->GetStackMapParser()->CalculateStackMap(std::move(stackmapPtr), des_[i].GetHostCodeSecAddr(), startAddr); } } @@ -205,7 +205,7 @@ bool AOTModulePackInfo::Load(EcmaVM *vm, const std::string &filename) uintptr_t funAddr = startAddr + codeAddr; kungfu::Func2FpDelta fun2fpDelta; fun2fpDelta[funAddr] = std::make_pair(delta, funSize); - vm->GetStackMapParser()->CalculateFuncFpDelta(fun2fpDelta); + vm->GetFileLoader()->GetStackMapParser()->CalculateFuncFpDelta(fun2fpDelta); } for (size_t i = 0; i < entries_.size(); i++) { diff --git a/ecmascript/frames.cpp b/ecmascript/frames.cpp index bd635bb2..f5092d33 100644 --- a/ecmascript/frames.cpp +++ b/ecmascript/frames.cpp @@ -13,52 +13,81 @@ * limitations under the License. */ #include "ecmascript/frames.h" -#include #include "ecmascript/ecma_vm.h" +#include "ecmascript/file_loader.h" #include "ecmascript/js_thread.h" #include "ecmascript/llvm_stackmap_parser.h" namespace panda::ecmascript { -#define FRAME_AND_TYPE_LIST(V) \ - V(OptimizedFrame, OPTIMIZED_FRAME) \ - V(OptimizedEntryFrame, OPTIMIZED_ENTRY_FRAME) \ - V(OptimizedJSFunctionFrame, OPTIMIZED_JS_FUNCTION_FRAME) \ - V(OptimizedLeaveFrame, LEAVE_FRAME) \ - V(OptimizedWithArgvLeaveFrame, LEAVE_FRAME_WITH_ARGV) \ - V(InterpretedFrame, INTERPRETER_FRAME) \ - V(AsmInterpretedFrame, ASM_INTERPRETER_FRAME) \ - V(AsmInterpretedFrame, INTERPRETER_CONSTRUCTOR_FRAME) \ - V(BuiltinFrame, BUILTIN_FRAME) \ - V(BuiltinWithArgvFrame, BUILTIN_FRAME_WITH_ARGV) \ - V(BuiltinFrame, BUILTIN_ENTRY_FRAME) \ - V(InterpretedFrame, INTERPRETER_FAST_NEW_FRAME) \ - V(InterpretedEntryFrame, INTERPRETER_ENTRY_FRAME) \ - V(AsmInterpretedEntryFrame, ASM_INTERPRETER_ENTRY_FRAME) \ - V(OptimizedJSFunctionFrame, OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME) \ - V(AsmInterpretedBridgeFrame, ASM_INTERPRETER_BRIDGE_FRAME) - -#define IMPLEMENT_GET_FRAME(Frame) \ - template<> \ - Frame* FrameIterator::GetFrame() \ - { \ - return Frame::GetFrameFromSp(current_); \ - } - FRAME_LIST(IMPLEMENT_GET_FRAME) -#undef IMPLEMENT_GET_FRAME - void FrameIterator::Advance() { ASSERT(!Done()); FrameType t = GetFrameType(); switch (t) { -#define CASE(FRAME, Type) \ - case FrameType::Type : { \ - auto frame = GetFrame(); \ - current_ = frame->GetPrevFrameFp(); \ - break; \ - } - FRAME_AND_TYPE_LIST(CASE) -#undef CASE + case FrameType::OPTIMIZED_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::OPTIMIZED_ENTRY_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: + case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::LEAVE_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::LEAVE_FRAME_WITH_ARGV : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::INTERPRETER_FRAME: + case FrameType::INTERPRETER_FAST_NEW_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::INTERPRETER_CONSTRUCTOR_FRAME: + case FrameType::ASM_INTERPRETER_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::BUILTIN_FRAME: + case FrameType::BUILTIN_ENTRY_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::BUILTIN_FRAME_WITH_ARGV : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::INTERPRETER_ENTRY_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::ASM_INTERPRETER_ENTRY_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::ASM_INTERPRETER_BRIDGE_FRAME : { + auto frame = GetFrame(); + current_ = frame->GetPrevFrameFp(); + break; + } default: { UNREACHABLE(); } @@ -69,26 +98,32 @@ uintptr_t FrameIterator::GetPrevFrameCallSiteSp(uintptr_t curPc) if (Done()) { return 0; } -#define GET_CALLSITE_SP_LIST(V) \ - V(LEAVE_FRAME, OptimizedLeaveFrame) \ - V(LEAVE_FRAME_WITH_ARGV, OptimizedWithArgvLeaveFrame) \ - V(BUILTIN_FRAME_WITH_ARGV, BuiltinWithArgvFrame) \ - V(BUILTIN_FRAME, BuiltinFrame) \ - V(ASM_INTERPRETER_BRIDGE_FRAME, AsmInterpretedBridgeFrame) - auto type = GetFrameType(); switch (type) { -#define CASE(Type, Frame) \ - case FrameType::Type: { \ - auto frame = GetFrame(); \ - return frame->GetCallSiteSp(); \ + case FrameType::LEAVE_FRAME: { + auto frame = GetFrame(); + return frame->GetCallSiteSp(); + } + case FrameType::LEAVE_FRAME_WITH_ARGV: { + auto frame = GetFrame(); + return frame->GetCallSiteSp(); + } + case FrameType::BUILTIN_FRAME_WITH_ARGV: { + auto frame = GetFrame(); + return frame->GetCallSiteSp(); + } + case FrameType::BUILTIN_FRAME: { + auto frame = GetFrame(); + return frame->GetCallSiteSp(); + } + case FrameType::ASM_INTERPRETER_BRIDGE_FRAME: { + auto frame = GetFrame(); + return frame->GetCallSiteSp(); } - GET_CALLSITE_SP_LIST(CASE) -#undef CASE case FrameType::OPTIMIZED_FRAME: case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: { auto callSiteSp = reinterpret_cast(current_) + - thread_->GetEcmaVM()->GetStackMapParser()->GetFuncFpDelta(curPc); + thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->GetFuncFpDelta(curPc); return callSiteSp; } case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME : { diff --git a/ecmascript/frames.h b/ecmascript/frames.h index 845fba9a..bc39fac7 100644 --- a/ecmascript/frames.h +++ b/ecmascript/frames.h @@ -877,20 +877,6 @@ struct BuiltinWithArgvFrame : public base::AlignedStruct(current_) - sizeof(FrameType)); return *typeAddr; } - template - Frame* GetFrame(); - #define EXPLICIT_DECLARE_GET_FRAME(Frame) \ - template<> \ - Frame* GetFrame(); - FRAME_LIST(EXPLICIT_DECLARE_GET_FRAME) - #undef EXPLICIT_DECLARE_GET_FRAME + template + T* GetFrame() + { + return T::GetFrameFromSp(current_); + } bool Done() { diff --git a/ecmascript/interpreter/frame_handler.cpp b/ecmascript/interpreter/frame_handler.cpp index 3f55061a..b3cac6a3 100644 --- a/ecmascript/interpreter/frame_handler.cpp +++ b/ecmascript/interpreter/frame_handler.cpp @@ -16,6 +16,7 @@ #include "ecmascript/interpreter/frame_handler.h" +#include "ecmascript/file_loader.h" #include "ecmascript/llvm_stackmap_parser.h" #include "ecmascript/js_function.h" #include "ecmascript/js_thread.h" @@ -298,10 +299,10 @@ ARK_INLINE void FrameHandler::InterpretedFrameIterate(const JSTaggedType *sp, } ARK_INLINE void FrameHandler::AsmInterpretedFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, - const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) + const RootVisitor &v0, + const RootRangeVisitor &v1, + ChunkMap *derivedPointers, + bool isVerifying) { AsmInterpretedFrame *frame = AsmInterpretedFrame::GetFrameFromSp(sp); uintptr_t start = ToUintPtr(sp); @@ -315,7 +316,7 @@ ARK_INLINE void FrameHandler::AsmInterpretedFrameIterate(const JSTaggedType *sp, uintptr_t curPc = optimizedReturnAddr_; std::set slotAddrs; - bool ret = thread_->GetEcmaVM()->GetStackMapParser()->CollectGCSlots( + bool ret = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( curPc, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); if (!ret) { @@ -330,10 +331,10 @@ ARK_INLINE void FrameHandler::AsmInterpretedFrameIterate(const JSTaggedType *sp, } ARK_INLINE void FrameHandler::BuiltinFrameIterate(const JSTaggedType *sp, - [[maybe_unused]] const RootVisitor &v0, - const RootRangeVisitor &v1, - [[maybe_unused]] ChunkMap *derivedPointers, - [[maybe_unused]] bool isVerifying) + [[maybe_unused]] const RootVisitor &v0, + const RootRangeVisitor &v1, + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) { auto frame = BuiltinFrame::GetFrameFromSp(sp); // no need to visit stack map for entry frame @@ -387,7 +388,7 @@ ARK_INLINE void FrameHandler::OptimizedFrameIterate(const JSTaggedType *sp, bool isVerifying) { std::set slotAddrs; - bool ret = thread_->GetEcmaVM()->GetStackMapParser()->CollectGCSlots( + bool ret = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( optimizedReturnAddr_, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); if (!ret) { @@ -410,7 +411,7 @@ ARK_INLINE void FrameHandler::OptimizedJSFunctionFrameIterate(const JSTaggedType { OptimizedJSFunctionFrame *frame = OptimizedJSFunctionFrame::GetFrameFromSp(sp); - int delta = thread_->GetEcmaVM()->GetStackMapParser()->GetFuncFpDelta(optimizedReturnAddr_); + int delta = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->GetFuncFpDelta(optimizedReturnAddr_); uintptr_t *preFrameSp = frame->ComputePrevFrameSp(sp, delta); auto argc = *(reinterpret_cast(preFrameSp)); @@ -423,7 +424,7 @@ ARK_INLINE void FrameHandler::OptimizedJSFunctionFrameIterate(const JSTaggedType std::set slotAddrs; auto currentPc = optimizedReturnAddr_; - bool ret = thread_->GetEcmaVM()->GetStackMapParser()->CollectGCSlots( + bool ret = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( currentPc, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); if (!ret) { #ifndef NDEBUG @@ -446,7 +447,7 @@ ARK_INLINE void FrameHandler::OptimizedEntryFrameIterate(const JSTaggedType *sp, std::set slotAddrs; // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) auto returnAddr = reinterpret_cast(*(reinterpret_cast(const_cast(sp)) + 1)); - bool ret = thread_->GetEcmaVM()->GetStackMapParser()->CollectGCSlots( + bool ret = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( returnAddr, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedReturnAddr_); if (!ret) { #ifndef NDEBUG @@ -651,7 +652,7 @@ void FrameHandler::CollectBCOffsetInfo() case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: { auto frame = it.GetFrame(); auto returnAddr = frame->GetReturnAddr(); - auto constInfo = thread_->GetEcmaVM()->GetStackMapParser()->GetConstInfo(returnAddr); + auto constInfo = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->GetConstInfo(returnAddr); if (!constInfo.empty()) { auto prevFp = frame->GetPrevFrameFp(); auto name = GetAotExceptionFuncName(prevFp); @@ -662,7 +663,7 @@ void FrameHandler::CollectBCOffsetInfo() case FrameType::LEAVE_FRAME: { auto frame = it.GetFrame(); auto returnAddr = frame->GetReturnAddr(); - auto constInfo = thread_->GetEcmaVM()->GetStackMapParser()->GetConstInfo(returnAddr); + auto constInfo = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->GetConstInfo(returnAddr); if (!constInfo.empty()) { auto prevFp = frame->GetPrevFrameFp(); auto name = GetAotExceptionFuncName(prevFp); -- Gitee From 496687fe52ae64b6d04dc565a5daedaf70cdb3d2 Mon Sep 17 00:00:00 2001 From: Gongyuhang Date: Tue, 14 Jun 2022 16:13:59 +0800 Subject: [PATCH 008/154] Desciption: Deal with the "use after free" error occurs while debugging ark_js_vm executable on windows. Details: Enclose the part where the LocalScope object should take effect with a pair of braces. Thus, the destructor of the LocalScope object will be called at the right brace which is above the JSNApi::DestroyJSVM() function. Issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5C7XG Signed-off-by: Gongyuhang --- ecmascript/compiler/aot_compiler.cpp | 45 +++++++++++++++------------- ecmascript/js_vm/main.cpp | 22 +++++++------- 2 files changed, 36 insertions(+), 31 deletions(-) diff --git a/ecmascript/compiler/aot_compiler.cpp b/ecmascript/compiler/aot_compiler.cpp index 10a6ba63..a45c64b2 100644 --- a/ecmascript/compiler/aot_compiler.cpp +++ b/ecmascript/compiler/aot_compiler.cpp @@ -110,29 +110,32 @@ int Main(const int argc, const char **argv) return -1; } - LocalScope scope(vm); - std::string entry = entrypoint.GetValue(); - arg_list_t pandaFileNames = files.GetValue(); - std::string triple = runtimeOptions.GetTargetTriple(); - std::string outputFileName = runtimeOptions.GetAOTOutputFile(); - size_t optLevel = runtimeOptions.GetOptLevel(); - BytecodeStubCSigns::Initialize(); - CommonStubCSigns::Initialize(); - RuntimeStubCSigns::Initialize(); - - std::string logMethods = vm->GetJSOptions().GetlogCompiledMethods(); - AotLog log(logMethods); - AOTFileGenerator generator(&log, vm); - PassManager passManager(vm, entry, triple, optLevel, &log); - for (const auto &fileName : pandaFileNames) { - COMPILER_LOG(INFO) << "AOT start to execute ark file: " << fileName; - if (passManager.Compile(fileName, generator) == false) { - ret = false; - break; + { + LocalScope scope(vm); + std::string entry = entrypoint.GetValue(); + arg_list_t pandaFileNames = files.GetValue(); + std::string triple = runtimeOptions.GetTargetTriple(); + std::string outputFileName = runtimeOptions.GetAOTOutputFile(); + size_t optLevel = runtimeOptions.GetOptLevel(); + BytecodeStubCSigns::Initialize(); + CommonStubCSigns::Initialize(); + RuntimeStubCSigns::Initialize(); + + std::string logMethods = vm->GetJSOptions().GetlogCompiledMethods(); + AotLog log(logMethods); + AOTFileGenerator generator(&log, vm); + PassManager passManager(vm, entry, triple, optLevel, &log); + for (const auto &fileName : pandaFileNames) { + COMPILER_LOG(INFO) << "AOT start to execute ark file: " << fileName; + if (passManager.Compile(fileName, generator) == false) { + ret = false; + break; + } } + generator.SaveAOTFile(outputFileName); + generator.GenerateSnapshotFile(); } - generator.SaveAOTFile(outputFileName); - generator.GenerateSnapshotFile(); + JSNApi::DestroyJSVM(vm); paParser.DisableTail(); return ret ? 0 : -1; diff --git a/ecmascript/js_vm/main.cpp b/ecmascript/js_vm/main.cpp index c39560aa..5b33dd1e 100644 --- a/ecmascript/js_vm/main.cpp +++ b/ecmascript/js_vm/main.cpp @@ -109,16 +109,18 @@ int Main(const int argc, const char **argv) return -1; } - LocalScope scope(vm); - std::string entry = entrypoint.GetValue(); - - arg_list_t fileNames = files.GetValue(); - for (const auto &fileName : fileNames) { - auto res = JSNApi::Execute(vm, fileName, entry); - if (!res) { - std::cerr << "Cannot execute panda file '" << fileName << "' with entry '" << entry << "'" << std::endl; - ret = false; - break; + { + LocalScope scope(vm); + std::string entry = entrypoint.GetValue(); + + arg_list_t fileNames = files.GetValue(); + for (const auto &fileName : fileNames) { + auto res = JSNApi::Execute(vm, fileName, entry); + if (!res) { + std::cerr << "Cannot execute panda file '" << fileName << "' with entry '" << entry << "'" << std::endl; + ret = false; + break; + } } } -- Gitee From 64ee35964ce6adeb74848c83f6e0775a20d32c17 Mon Sep 17 00:00:00 2001 From: buzhuyu Date: Fri, 10 Jun 2022 17:09:08 +0800 Subject: [PATCH 009/154] Modify the type in Create and ToJson ISSUE:https://gitee.com/openharmony/ark_js_runtime/issues/I5BQOT Signed-off-by: buzhuyu --- ecmascript/tooling/base/pt_types.cpp | 897 +++++++++++++++++- ecmascript/tooling/base/pt_types.h | 36 +- .../tooling/test/debugger_types_test.cpp | 429 +++++++-- 3 files changed, 1294 insertions(+), 68 deletions(-) diff --git a/ecmascript/tooling/base/pt_types.cpp b/ecmascript/tooling/base/pt_types.cpp index bc34f93e..07d07e48 100644 --- a/ecmascript/tooling/base/pt_types.cpp +++ b/ecmascript/tooling/base/pt_types.cpp @@ -1704,6 +1704,41 @@ std::unique_ptr SamplingHeapProfileSample::Create(con return samplingHeapProfileSample; } +std::unique_ptr SamplingHeapProfileSample::Create(const PtJson ¶ms) +{ + std::string error; + auto samplingHeapProfileSample = std::make_unique(); + Result ret; + + int32_t size; + ret = params.GetInt("size", &size); + if (ret == Result::SUCCESS) { + samplingHeapProfileSample->size_ = size; + } else { + error += "Unknown 'size';"; + } + int32_t nodeId; + ret = params.GetInt("nodeId", &nodeId); + if (ret == Result::SUCCESS) { + samplingHeapProfileSample->nodeId_ = nodeId; + } else { + error += "Unknown 'nodeId';"; + } + int32_t ordinal; + ret = params.GetInt("ordinal", &ordinal); + if (ret == Result::SUCCESS) { + samplingHeapProfileSample->ordinal_ = ordinal; + } else { + error += "Unknown 'ordinal';"; + } + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "SamplingHeapProfileSample::Create " << error; + return nullptr; + } + + return samplingHeapProfileSample; +} + Local SamplingHeapProfileSample::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -1718,6 +1753,17 @@ Local SamplingHeapProfileSample::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr SamplingHeapProfileSample::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("size", static_cast(size_)); + result->Add("nodeId", nodeId_); + result->Add("ordinal", static_cast(ordinal_)); + + return result; +} + std::unique_ptr RuntimeCallFrame::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -1791,6 +1837,59 @@ std::unique_ptr RuntimeCallFrame::Create(const EcmaVM *ecmaVm, return runtimeCallFrame; } +std::unique_ptr RuntimeCallFrame::Create(const PtJson ¶ms) +{ + std::string error; + auto runtimeCallFrame = std::make_unique(); + Result ret; + + std::string functionName; + ret = params.GetString("functionName", &functionName); + if (ret == Result::SUCCESS) { + runtimeCallFrame->functionName_ = std::move(functionName); + } else { + error += "Unknown 'functionName';"; + } + + std::string scriptId; + ret = params.GetString("scriptId", &scriptId); + if (ret == Result::SUCCESS) { + runtimeCallFrame->scriptId_ = std::move(scriptId); + } else { + error += "Unknown 'scriptId';"; + } + + std::string url; + ret = params.GetString("url", &url); + if (ret == Result::SUCCESS) { + runtimeCallFrame->url_ = std::move(url); + } else { + error += "Unknown 'url';"; + } + + int32_t lineNumber; + ret = params.GetInt("lineNumber", &lineNumber); + if (ret == Result::SUCCESS) { + runtimeCallFrame->lineNumber_ = lineNumber; + } else { + error += "Unknown 'lineNumber';"; + } + + int32_t columnNumber; + ret = params.GetInt("columnNumber", &columnNumber); + if (ret == Result::SUCCESS) { + runtimeCallFrame->columnNumber_ = columnNumber; + } else { + error += "Unknown 'columnNumber';"; + } + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "RuntimeCallFrame::Create " << error; + return nullptr; + } + + return runtimeCallFrame; +} + std::unique_ptr RuntimeCallFrame::FromFrameInfo(const FrameInfo &cpuFrameInfo) { auto runtimeCallFrame = std::make_unique(); @@ -1824,6 +1923,19 @@ Local RuntimeCallFrame::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr RuntimeCallFrame::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("functionName", functionName_.c_str()); + result->Add("scriptId", scriptId_.c_str()); + result->Add("url", url_.c_str()); + result->Add("lineNumber", lineNumber_); + result->Add("columnNumber", columnNumber_); + + return result; +} + std::unique_ptr SamplingHeapProfileNode::Create(const EcmaVM *ecmaVm, const Local ¶ms) { @@ -1904,6 +2016,70 @@ std::unique_ptr SamplingHeapProfileNode::Create(const E return samplingHeapProfileNode; } +std::unique_ptr SamplingHeapProfileNode::Create(const PtJson ¶ms) +{ + std::string error; + auto samplingHeapProfileNode = std::make_unique(); + Result ret; + + std::unique_ptr callFrame; + ret = params.GetObject("callFrame", &callFrame); + if (ret == Result::SUCCESS) { + std::unique_ptr runtimeCallFrame = RuntimeCallFrame::Create(*callFrame); + if (runtimeCallFrame == nullptr) { + error += "'callFrame' format invalid;"; + } else { + samplingHeapProfileNode->callFrame_ = std::move(runtimeCallFrame); + } + } else { + error += "Unknown 'callFrame';"; + } + + int32_t selfSize; + ret = params.GetInt("selfSize", &selfSize); + if (ret == Result::SUCCESS) { + samplingHeapProfileNode->selfSize_ = static_cast(selfSize); + } else { + error += "Unknown 'selfSize';"; + } + + int32_t id; + ret = params.GetInt("id", &id); + if (ret == Result::SUCCESS) { + samplingHeapProfileNode->id_ = id; + } else { + error += "Unknown 'id';"; + } + + std::unique_ptr children; + ret = params.GetArray("children", &children); + if (ret == Result::SUCCESS) { + int32_t len = children->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr arrayEle = children->Get(i); + if (arrayEle != nullptr) { + std::unique_ptr node = SamplingHeapProfileNode::Create(*arrayEle); + if (node == nullptr) { + error += "'children' format invalid;"; + } else { + samplingHeapProfileNode->children_.emplace_back(std::move(node)); + } + } else { + error += "Unknown 'children';"; + } + } + } else { + error += "Unknown 'children';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "SamplingHeapProfileNode::Create " << error; + return nullptr; + } + + return samplingHeapProfileNode; +} + Local SamplingHeapProfileNode::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -1932,6 +2108,25 @@ Local SamplingHeapProfileNode::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr SamplingHeapProfileNode::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + if (callFrame_ != nullptr) { + result->Add("callFrame", callFrame_->ToJson()); + } + + result->Add("selfSize", static_cast(selfSize_)); + result->Add("id", id_); + + std::unique_ptr childrens = PtJson::CreateArray(); + size_t len = children_.size(); + for (size_t i = 0; i < len; i++) { + childrens->Push(children_[i]->ToJson()); + } + result->Add("children", childrens); + return result; +} + std::unique_ptr SamplingHeapProfile::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -1989,6 +2184,54 @@ std::unique_ptr SamplingHeapProfile::Create(const EcmaVM *e return samplingHeapProfile; } +std::unique_ptr SamplingHeapProfile::Create(const PtJson ¶ms) +{ + std::string error; + auto samplingHeapProfile = std::make_unique(); + Result ret; + + std::unique_ptr head; + ret = params.GetObject("head", &head); + if (ret == Result::SUCCESS) { + std::unique_ptr pHead = SamplingHeapProfileNode::Create(*head); + if (pHead == nullptr) { + error += "'sample' format invalid;"; + } else { + samplingHeapProfile->head_ = std::move(pHead); + } + } else { + error += "Unknown 'head';"; + } + + std::unique_ptr samples; + ret = params.GetArray("samples", &samples); + if (ret == Result::SUCCESS) { + int32_t len = samples->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr arrayEle = samples->Get(i); + if (arrayEle != nullptr) { + std::unique_ptr pSample = SamplingHeapProfileSample::Create(*arrayEle); + if (pSample == nullptr) { + error += "'sample' format invalid;"; + } else { + samplingHeapProfile->samples_.emplace_back(std::move(pSample)); + } + } else { + error += "Unknown 'samples';"; + } + } + } else { + error += "Unknown 'samples';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "SamplingHeapProfile::Create " << error; + return nullptr; + } + + return samplingHeapProfile; +} + Local SamplingHeapProfile::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -2012,6 +2255,23 @@ Local SamplingHeapProfile::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr SamplingHeapProfile::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("head", head_->ToJson()); + + std::unique_ptr samples = PtJson::CreateArray(); + size_t len = samples_.size(); + for (size_t i = 0; i < len; i++) { + if (samples_[i] != nullptr) { + samples->Push(samples_[i]->ToJson()); + } + } + result->Add("samples", samples); + return result; +} + std::unique_ptr PositionTickInfo::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2049,6 +2309,36 @@ std::unique_ptr PositionTickInfo::Create(const EcmaVM *ecmaVm, return positionTicks; } +std::unique_ptr PositionTickInfo::Create(const PtJson ¶ms) +{ + std::string error; + auto positionTickInfo = std::make_unique(); + Result ret; + + int32_t line; + ret = params.GetInt("line", &line); + if (ret == Result::SUCCESS) { + positionTickInfo->line_ = line; + } else { + error += "Unknown 'line';"; + } + + int32_t ticks; + ret = params.GetInt("ticks", &ticks); + if (ret == Result::SUCCESS) { + positionTickInfo->ticks_ = ticks; + } else { + error += "Unknown 'ticks';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "PositionTickInfo::Create " << error; + return nullptr; + } + + return positionTickInfo; +} + Local PositionTickInfo::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -2062,6 +2352,16 @@ Local PositionTickInfo::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr PositionTickInfo::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("line", static_cast(line_)); + result->Add("ticks", static_cast(ticks_)); + + return result; +} + std::unique_ptr ProfileNode::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2161,6 +2461,90 @@ std::unique_ptr ProfileNode::Create(const EcmaVM *ecmaVm, const Loc return profileNode; } +std::unique_ptr ProfileNode::Create(const PtJson ¶ms) +{ + std::string error; + auto profileNode = std::make_unique(); + Result ret; + + int32_t id; + ret = params.GetInt("id", &id); + if (ret == Result::SUCCESS) { + profileNode->id_ = id; + } else { + error += "Unknown 'id';"; + } + + std::unique_ptr callFrame; + ret = params.GetObject("callFrame", &callFrame); + if (ret == Result::SUCCESS) { + std::unique_ptr runtimeCallFrame = RuntimeCallFrame::Create(*callFrame); + if (runtimeCallFrame == nullptr) { + error += "'callFrame' format invalid;"; + } else { + profileNode->callFrame_ = std::move(runtimeCallFrame); + } + } else { + error += "Unknown 'callFrame';"; + } + + int32_t hitCount; + ret = params.GetInt("hitCount", &hitCount); + if (ret == Result::SUCCESS) { + profileNode->hitCount_ = hitCount; + } else if (ret == Result::TYPE_ERROR) { + error += "Unknown 'hitCount';"; + } + + std::unique_ptr children; + ret = params.GetArray("children", &children); + if (ret == Result::SUCCESS) { + int32_t childrenLen = children->GetSize(); + for (int32_t i = 0; i < childrenLen; ++i) { + int32_t pChildren = children->Get(i)->GetInt(); + profileNode->children_.value().emplace_back(pChildren); + } + } else if (ret == Result::TYPE_ERROR) { + error += "Unknown 'children';"; + } + + std::unique_ptr positionTicks; + ret = params.GetArray("positionTicks", &positionTicks); + if (ret == Result::SUCCESS) { + int32_t positionTicksLen = positionTicks->GetSize(); + for (int32_t i = 0; i < positionTicksLen; ++i) { + std::unique_ptr arrayEle = positionTicks->Get(i); + if (arrayEle != nullptr) { + std::unique_ptr tmpPositionTicks = PositionTickInfo::Create(*arrayEle); + if (tmpPositionTicks == nullptr) { + error += "'positionTicks' format invalid;"; + } else { + profileNode->positionTicks_.value().emplace_back(std::move(tmpPositionTicks)); + } + } else { + error += "Unknown 'positionTicks';"; + } + } + } else if (ret == Result::TYPE_ERROR) { + error += "Unknown 'positionTicks';"; + } + + std::string deoptReason; + ret = params.GetString("deoptReason", &deoptReason); + if (ret == Result::SUCCESS) { + profileNode->deoptReason_ = std::move(deoptReason); + } else if (ret == Result::TYPE_ERROR) { + error += "Unknown 'deoptReason';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "ProfileNode::Create " << error; + return nullptr; + } + + return profileNode; +} + std::unique_ptr ProfileNode::FromCpuProfileNode(const CpuProfileNode &cpuProfileNode) { auto profileNode = std::make_unique(); @@ -2223,6 +2607,41 @@ Local ProfileNode::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr ProfileNode::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("id", id_); + result->Add("callFrame", callFrame_->ToJson()); + if (hitCount_) { + result->Add("hitCount", hitCount_.value()); + } + if (children_) { + std::unique_ptr childrens = PtJson::CreateArray(); + size_t len = children_->size(); + for (size_t i = 0; i < len; i++) { + childrens->Push(children_.value()[i]); + } + result->Add("children", childrens); + } + if (positionTicks_) { + std::unique_ptr positionTicks = PtJson::CreateArray(); + size_t len = positionTicks_->size(); + for (size_t i = 0; i < len; i++) { + if (positionTicks_.value()[i] != nullptr) { + positionTicks->Push(positionTicks_.value()[i]->ToJson()); + } + } + result->Add("positionTicks", positionTicks); + } + + if (deoptReason_) { + result->Add("deoptReason", deoptReason_.value().c_str()); + } + + return result; +} + std::unique_ptr Profile::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2316,17 +2735,92 @@ std::unique_ptr Profile::Create(const EcmaVM *ecmaVm, const Local Profile::FromProfileInfo(const ProfileInfo &profileInfo) +std::unique_ptr Profile::Create(const PtJson ¶ms) { + std::string error; auto profile = std::make_unique(); - profile->SetStartTime(static_cast(profileInfo.startTime)); - profile->SetEndTime(static_cast(profileInfo.stopTime)); - size_t samplesLen = profileInfo.samples.size(); - std::vector tmpSamples; - tmpSamples.reserve(samplesLen); - for (uint32_t i = 0; i < samplesLen; ++i) { - tmpSamples.push_back(profileInfo.samples[i]); - } + Result ret; + + std::unique_ptr nodes; + ret = params.GetArray("nodes", &nodes); + if (ret == Result::SUCCESS) { + int32_t nodesLen = nodes->GetSize(); + for (int32_t i = 0; i < nodesLen; ++i) { + std::unique_ptr arrayEle = nodes->Get(i); + if (arrayEle != nullptr) { + std::unique_ptr profileNode = ProfileNode::Create(*arrayEle); + if (profileNode == nullptr) { + error += "'nodes' format invalid;"; + } else { + profile->nodes_.emplace_back(std::move(profileNode)); + } + } else { + error += "Unknown 'nodes';"; + } + } + } else { + error += "Unknown 'nodes';"; + } + + int64_t startTime; + ret = params.GetInt64("startTime", &startTime); + if (ret == Result::SUCCESS) { + profile->startTime_ = startTime; + } else { + error += "Unknown 'startTime';"; + } + + int64_t endTime; + ret = params.GetInt64("endTime", &endTime); + if (ret == Result::SUCCESS) { + profile->endTime_ = endTime; + } else { + error += "Unknown 'endTime';"; + } + + std::unique_ptr samples; + ret = params.GetArray("samples", &samples); + if (ret == Result::SUCCESS) { + int32_t samplesLen = samples->GetSize(); + for (int32_t i = 0; i < samplesLen; ++i) { + int32_t pSamples = samples->Get(i)->GetInt(); + profile->samples_.value().emplace_back(pSamples); + } + } else if (ret == Result::TYPE_ERROR) { + error += "Unknown 'samples';"; + } + + std::unique_ptr timeDeltas; + ret = params.GetArray("timeDeltas", &timeDeltas); + if (ret == Result::SUCCESS) { + int32_t timeDeltasLen = timeDeltas->GetSize(); + for (int32_t i = 0; i < timeDeltasLen; ++i) { + int32_t pTimeDeltas = timeDeltas->Get(i)->GetInt(); + profile->timeDeltas_.value().emplace_back(pTimeDeltas); + } + } else if (ret == Result::TYPE_ERROR) { + error += "Unknown 'timeDeltas';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "Profile::Create " << error; + return nullptr; + } + + return profile; +} + +std::unique_ptr Profile::FromProfileInfo(const ProfileInfo &profileInfo) +{ + auto profile = std::make_unique(); + profile->SetStartTime(static_cast(profileInfo.startTime)); + profile->SetEndTime(static_cast(profileInfo.stopTime)); + size_t samplesLen = profileInfo.samples.size(); + std::vector tmpSamples; + tmpSamples.reserve(samplesLen); + for (uint32_t i = 0; i < samplesLen; ++i) { + tmpSamples.push_back(profileInfo.samples[i]); + } profile->SetSamples(tmpSamples); size_t timeDeltasLen = profileInfo.timeDeltas.size(); @@ -2387,6 +2881,43 @@ Local Profile::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr Profile::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("startTime", startTime_); + result->Add("endTime", endTime_); + + std::unique_ptr nodes = PtJson::CreateArray(); + size_t nodesLen = nodes_.size(); + for (size_t i = 0; i < nodesLen; i++) { + if (nodes_[i] != nullptr) { + nodes->Push(nodes_[i]->ToJson()); + } + } + result->Add("nodes", nodes); + + if (samples_) { + std::unique_ptr samples = PtJson::CreateArray(); + size_t samplesLen = samples_->size(); + for (size_t i = 0; i < samplesLen; i++) { + samples->Push(samples_.value()[i]); + } + result->Add("samples", samples); + } + + if (timeDeltas_) { + std::unique_ptr timeDeltas = PtJson::CreateArray(); + size_t timeDeltasLen = timeDeltas_->size(); + for (size_t i = 0; i < timeDeltasLen; i++) { + timeDeltas->Push(timeDeltas_.value()[i]); + } + result->Add("timeDeltas", timeDeltas); + } + + return result; +} + std::unique_ptr Coverage::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2434,6 +2965,44 @@ std::unique_ptr Coverage::Create(const EcmaVM *ecmaVm, const Local Coverage::Create(const PtJson ¶ms) +{ + std::string error; + auto coverage = std::make_unique(); + Result ret; + + int32_t startOffset; + ret = params.GetInt("startOffset", &startOffset); + if (ret == Result::SUCCESS) { + coverage->startOffset_ = startOffset; + } else { + error += "Unknown 'startOffset';"; + } + + int32_t endOffset; + ret = params.GetInt("endOffset", &endOffset); + if (ret == Result::SUCCESS) { + coverage->endOffset_ = endOffset; + } else { + error += "Unknown 'endOffset';"; + } + + int32_t count; + ret = params.GetInt("count", &count); + if (ret == Result::SUCCESS) { + coverage->count_ = count; + } else { + error += "Unknown 'count';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "Coverage::Create " << error; + return nullptr; + } + + return coverage; +} + Local Coverage::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -2446,6 +3015,17 @@ Local Coverage::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr Coverage::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("startOffset", startOffset_); + result->Add("endOffset", endOffset_); + result->Add("count", count_); + + return result; +} + std::unique_ptr FunctionCoverage::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2502,6 +3082,57 @@ std::unique_ptr FunctionCoverage::Create(const EcmaVM *ecmaVm, return functionCoverage; } +std::unique_ptr FunctionCoverage::Create(const PtJson ¶ms) +{ + std::string error; + auto functionCoverage = std::make_unique(); + Result ret; + + std::string functionName; + ret = params.GetString("functionName", &functionName); + if (ret == Result::SUCCESS) { + functionCoverage->functionName_ = std::move(functionName); + } else { + error += "Unknown 'functionName';"; + } + + std::unique_ptr ranges; + ret = params.GetArray("ranges", &ranges); + if (ret == Result::SUCCESS) { + int32_t len = ranges->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr arrayEle = ranges->Get(i); + if (arrayEle != nullptr) { + std::unique_ptr pRanges = Coverage::Create(*arrayEle); + if (pRanges == nullptr) { + error += "'ranges' format invalid;"; + } else { + functionCoverage->ranges_.emplace_back(std::move(pRanges)); + } + } else { + error += "Unknown 'ranges';"; + } + } + } else { + error += "Unknown 'ranges';"; + } + + bool isBlockCoverage; + ret = params.GetBool("isBlockCoverage", &isBlockCoverage); + if (ret == Result::SUCCESS) { + functionCoverage->isBlockCoverage_ = isBlockCoverage; + } else { + error += "Unknown 'isBlockCoverage';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "FunctionCoverage::Create " << error; + return nullptr; + } + + return functionCoverage; +} + Local FunctionCoverage::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -2524,6 +3155,26 @@ Local FunctionCoverage::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr FunctionCoverage::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("functionName", functionName_.c_str()); + + std::unique_ptr ranges = PtJson::CreateArray(); + size_t len = ranges_.size(); + for (size_t i = 0; i < len; i++) { + if (ranges_[i] != nullptr) { + ranges->Push(ranges_[i]->ToJson()); + } + } + result->Add("ranges", ranges); + + result->Add("isBlockCoverage", isBlockCoverage_); + + return result; +} + std::unique_ptr ScriptCoverage::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2579,6 +3230,57 @@ std::unique_ptr ScriptCoverage::Create(const EcmaVM *ecmaVm, con return scriptCoverage; } +std::unique_ptr ScriptCoverage::Create(const PtJson ¶ms) +{ + std::string error; + auto scriptCoverage = std::make_unique(); + Result ret; + + std::string scriptId; + ret = params.GetString("scriptId", &scriptId); + if (ret == Result::SUCCESS) { + scriptCoverage->scriptId_ = std::move(scriptId); + } else { + error += "Unknown 'scriptId';"; + } + + std::string url; + ret = params.GetString("url", &url); + if (ret == Result::SUCCESS) { + scriptCoverage->url_ = std::move(url); + } else { + error += "Unknown 'url';"; + } + + std::unique_ptr functions; + ret = params.GetArray("functions", &functions); + if (ret == Result::SUCCESS) { + int32_t len = functions->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr arrayEle = functions->Get(i); + if (arrayEle != nullptr) { + std::unique_ptr pFunctions = FunctionCoverage::Create(*arrayEle); + if (pFunctions == nullptr) { + error += "'functions' format invalid;"; + } else { + scriptCoverage->functions_.emplace_back(std::move(pFunctions)); + } + } else { + error += "Unknown 'functions';"; + } + } + } else { + error += "Unknown 'functions';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "ScriptCoverage::Create " << error; + return nullptr; + } + + return scriptCoverage; +} + Local ScriptCoverage::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -2598,6 +3300,25 @@ Local ScriptCoverage::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr ScriptCoverage::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("scriptId", scriptId_.c_str()); + result->Add("url", url_.c_str()); + + std::unique_ptr functions = PtJson::CreateArray(); + size_t len = functions_.size(); + for (size_t i = 0; i < len; i++) { + if (functions_[i] != nullptr) { + functions->Push(functions_[i]->ToJson()); + } + } + result->Add("functions", functions); + + return result; +} + std::unique_ptr TypeObject::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2625,6 +3346,28 @@ std::unique_ptr TypeObject::Create(const EcmaVM *ecmaVm, const Local return typeObject; } +std::unique_ptr TypeObject::Create(const PtJson ¶ms) +{ + std::string error; + auto typeObject = std::make_unique(); + Result ret; + + std::string name; + ret = params.GetString("name", &name); + if (ret == Result::SUCCESS) { + typeObject->name_ = std::move(name); + } else { + error += "Unknown 'name';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "TypeObject::Create " << error; + return nullptr; + } + + return typeObject; +} + Local TypeObject::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -2634,6 +3377,15 @@ Local TypeObject::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr TypeObject::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("name", name_.c_str()); + + return result; +} + std::unique_ptr TypeProfileEntry::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2678,6 +3430,49 @@ std::unique_ptr TypeProfileEntry::Create(const EcmaVM *ecmaVm, return typeProfileEntry; } +std::unique_ptr TypeProfileEntry::Create(const PtJson ¶ms) +{ + std::string error; + auto typeProfileEntry = std::make_unique(); + Result ret; + + int32_t offset; + ret = params.GetInt("offset", &offset); + if (ret == Result::SUCCESS) { + typeProfileEntry->offset_ = offset; + } else { + error += "Unknown 'offset';"; + } + + std::unique_ptr types; + ret = params.GetArray("types", &types); + if (ret == Result::SUCCESS) { + int32_t len = types->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr arrayEle = types->Get(i); + if (arrayEle != nullptr) { + std::unique_ptr pTypes = TypeObject::Create(*arrayEle); + if (pTypes == nullptr) { + error += "'types' format invalid;"; + } else { + typeProfileEntry->types_.emplace_back(std::move(pTypes)); + } + } else { + error += "Unknown 'types';"; + } + } + } else { + error += "Unknown 'types';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "TypeProfileEntry::Create " << error; + return nullptr; + } + + return typeProfileEntry; +} + Local TypeProfileEntry::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -2694,6 +3489,22 @@ Local TypeProfileEntry::ToObject(const EcmaVM *ecmaVm) const return params; } +std::unique_ptr TypeProfileEntry::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("offset", static_cast(offset_)); + + std::unique_ptr types = PtJson::CreateArray(); + size_t len = types_.size(); + for (size_t i = 0; i < len; i++) { + types->Push(types_[i]->ToJson()); + } + result->Add("types", types); + + return result; +} + std::unique_ptr ScriptTypeProfile::Create(const EcmaVM *ecmaVm, const Local ¶ms) { if (params.IsEmpty() || !params->IsObject()) { @@ -2750,6 +3561,57 @@ std::unique_ptr ScriptTypeProfile::Create(const EcmaVM *ecmaV return scriptTypeProfile; } +std::unique_ptr ScriptTypeProfile::Create(const PtJson ¶ms) +{ + std::string error; + auto scriptTypeProfile = std::make_unique(); + Result ret; + + std::string scriptId; + ret = params.GetString("scriptId", &scriptId); + if (ret == Result::SUCCESS) { + scriptTypeProfile->scriptId_ = std::move(scriptId); + } else { + error += "Unknown 'scriptId';"; + } + + std::string url; + ret = params.GetString("url", &url); + if (ret == Result::SUCCESS) { + scriptTypeProfile->url_ = std::move(url); + } else { + error += "Unknown 'url';"; + } + + std::unique_ptr entries; + ret = params.GetArray("entries", &entries); + if (ret == Result::SUCCESS) { + int32_t len = entries->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr arrayEle = entries->Get(i); + if (arrayEle != nullptr) { + std::unique_ptr pEntries = TypeProfileEntry::Create(*arrayEle); + if (pEntries == nullptr) { + error += "'entries' format invalid;"; + } else { + scriptTypeProfile->entries_.emplace_back(std::move(pEntries)); + } + } else { + error += "Unknown 'entries';"; + } + } + } else { + error += "Unknown 'entries';"; + } + + if (!error.empty()) { + LOG(ERROR, DEBUGGER) << "ScriptTypeProfile::Create " << error; + return nullptr; + } + + return scriptTypeProfile; +} + Local ScriptTypeProfile::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -2768,4 +3630,21 @@ Local ScriptTypeProfile::ToObject(const EcmaVM *ecmaVm) const params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "entries")), entriesValues); return params; } + +std::unique_ptr ScriptTypeProfile::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("scriptId", scriptId_.c_str()); + result->Add("url", url_.c_str()); + + std::unique_ptr entries = PtJson::CreateArray(); + size_t len = entries_.size(); + for (size_t i = 0; i < len; i++) { + entries->Push(entries_[i]->ToJson()); + } + result->Add("entries", entries); + + return result; +} } // namespace panda::ecmascript::tooling diff --git a/ecmascript/tooling/base/pt_types.h b/ecmascript/tooling/base/pt_types.h index 3e852693..487f7a25 100644 --- a/ecmascript/tooling/base/pt_types.h +++ b/ecmascript/tooling/base/pt_types.h @@ -1498,7 +1498,9 @@ public: SamplingHeapProfileSample() = default; ~SamplingHeapProfileSample() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; SamplingHeapProfileSample &SetSize(size_t size) { @@ -1547,8 +1549,10 @@ public: RuntimeCallFrame() = default; ~RuntimeCallFrame() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); static std::unique_ptr FromFrameInfo(const FrameInfo &cpuFrameInfo); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; RuntimeCallFrame &SetFunctionName(const std::string &functionName) { @@ -1621,7 +1625,9 @@ public: SamplingHeapProfileNode() = default; ~SamplingHeapProfileNode() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; SamplingHeapProfileNode &SetCallFrame(std::unique_ptr callFrame) { @@ -1682,7 +1688,9 @@ public: SamplingHeapProfile() = default; ~SamplingHeapProfile() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; SamplingHeapProfile &SetHead(std::unique_ptr head) { @@ -1722,7 +1730,10 @@ public: ~PositionTickInfo() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; + int32_t GetLine() const { return line_; @@ -1759,8 +1770,10 @@ public: ~ProfileNode() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); static std::unique_ptr FromCpuProfileNode(const CpuProfileNode &cpuProfileNode); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; int32_t GetId() const { @@ -1874,8 +1887,10 @@ public: ~Profile() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); static std::unique_ptr FromProfileInfo(const ProfileInfo &profileInfo); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; int64_t GetStartTime() const { @@ -1966,7 +1981,9 @@ public: ~Coverage() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; int32_t GetStartOffset() const { @@ -2005,9 +2022,9 @@ private: NO_COPY_SEMANTIC(Coverage); NO_MOVE_SEMANTIC(Coverage); - size_t startOffset_ {0}; - size_t endOffset_ {0}; - size_t count_ {0}; + int32_t startOffset_ {0}; + int32_t endOffset_ {0}; + int32_t count_ {0}; }; // Profiler.FunctionCoverage @@ -2017,7 +2034,9 @@ public: ~FunctionCoverage() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; const std::string &GetFunctionName() const { @@ -2069,7 +2088,9 @@ public: ~ScriptCoverage() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; const std::string &GetScriptId() const { @@ -2120,7 +2141,10 @@ public: ~TypeObject() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; + const std::string &GetName() const { return name_; @@ -2146,7 +2170,10 @@ public: ~TypeProfileEntry() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; + int32_t GetOffset() const { return offset_; @@ -2184,7 +2211,10 @@ public: ~ScriptTypeProfile() override = default; static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; + const std::string &GetScriptId() const { return scriptId_; diff --git a/ecmascript/tooling/test/debugger_types_test.cpp b/ecmascript/tooling/test/debugger_types_test.cpp index 235c2d69..9b100581 100644 --- a/ecmascript/tooling/test/debugger_types_test.cpp +++ b/ecmascript/tooling/test/debugger_types_test.cpp @@ -1824,39 +1824,39 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileSampleCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - object = SamplingHeapProfileSample::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - object = SamplingHeapProfileSample::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - object = SamplingHeapProfileSample::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - object = SamplingHeapProfileSample::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of params.sub-key = [ "size"="Test","nodeId"="Test","ordinal"="Test"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "size":"Test","nodeId":"Test","ordinal":"Test"}})"; - object = SamplingHeapProfileSample::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of params.sub-key = [ "size"={"xx":"yy"},"nodeId"={"xx":"yy"},"ordinal"={"xx":"yy"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "size":{"xx":"yy"},"nodeId":{"xx":"yy"},"ordinal":{"xx":"yy"}}})"; - object = SamplingHeapProfileSample::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of params.sub-key = [ "size"=100,"nodeId"=1,"ordinal"=10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"size":100,"nodeId":1,"ordinal":10}})"; - object = SamplingHeapProfileSample::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(object, nullptr); EXPECT_EQ(object->GetSize(), 100); EXPECT_EQ(object->GetNodeId(), 1); @@ -1894,6 +1894,31 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileSampleToObjectTest) EXPECT_EQ(Local(result)->Value(), 10); } +HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileSampleToJsonTest) +{ + std::string msg; + std::unique_ptr samplingHeapProfileSampleData; + std::string tmpStr; + int32_t tmpInt; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"size":100,"nodeId":1,"ordinal":10}})"; + samplingHeapProfileSampleData = + SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(samplingHeapProfileSampleData, nullptr); + auto json = samplingHeapProfileSampleData->ToJson(); + + ret = json->GetInt("size", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 100); + ret = json->GetInt("nodeId", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 1); + ret = json->GetInt("ordinal", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 10); +} + HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeCreateTest) { std::string msg; @@ -1901,22 +1926,22 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - object = SamplingHeapProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - object = SamplingHeapProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - object = SamplingHeapProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - object = SamplingHeapProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ @@ -1925,7 +1950,7 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeCreateTest) "id":5, "children":[] }})"; - object = SamplingHeapProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(object, nullptr); RuntimeCallFrame *runTimeCallFrame = object->GetCallFrame(); ASSERT_NE(runTimeCallFrame, nullptr); @@ -1998,6 +2023,50 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeToObjectTest) ASSERT_TRUE(result->IsArray(ecmaVm)); } +HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeToJsonTest) +{ + std::string msg; + std::unique_ptr samplingHeapProfileNode; + std::string tmpStr; + std::unique_ptr tmpJson; + int32_t tmpInt; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ + "callFrame": {"functionName":"Create", "scriptId":"10", "url":"url3", "lineNumber":100, "columnNumber":20}, + "selfSize":10, + "id":5, + "children":[] + }})"; + samplingHeapProfileNode = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(samplingHeapProfileNode, nullptr); + auto json = samplingHeapProfileNode->ToJson(); + + ret = json->GetObject("callFrame", &tmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(tmpJson, nullptr); + ret = tmpJson->GetString("functionName", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "Create"); + ret = tmpJson->GetString("scriptId", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "10"); + ret = tmpJson->GetString("url", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "url3"); + + ret = json->GetInt("selfSize", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 10); + ret = json->GetInt("id", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 5); + ret = json->GetArray("children", &tmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(tmpJson, nullptr); + EXPECT_EQ(tmpJson->GetSize(), 0); +} + HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileCreateTest) { std::string msg; @@ -2005,22 +2074,22 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - object = SamplingHeapProfile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - object = SamplingHeapProfile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - object = SamplingHeapProfile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - object = SamplingHeapProfile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(object, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ @@ -2032,7 +2101,7 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileCreateTest) }, "samples":[{"size":100, "nodeId":1, "ordinal":10}] }})"; - object = SamplingHeapProfile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(object, nullptr); SamplingHeapProfileNode *head = object->GetHead(); ASSERT_NE(head, nullptr); @@ -2151,6 +2220,64 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileToObjectTest) EXPECT_EQ(Local(result)->Value(), 10); } +HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileToJsonTest) +{ + std::string msg; + std::unique_ptr samplingHeapProfile; + std::string tmpStr; + int32_t tmpInt; + std::unique_ptr tmpJson; + std::unique_ptr varTmpJson; + std::unique_ptr exTmpJson; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ + "head": { + "callFrame": {"functionName":"Create", "scriptId":"10", "url":"url3", "lineNumber":100, "columnNumber":20}, + "selfSize":10, + "id":5, + "children":[] + }, + "samples":[{"size":100, "nodeId":1, "ordinal":10}] + }})"; + + samplingHeapProfile = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(samplingHeapProfile, nullptr); + auto json = samplingHeapProfile->ToJson(); + + ret = json->GetObject("head", &tmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(tmpJson, nullptr); + ret = tmpJson->GetObject("callFrame", &varTmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(varTmpJson, nullptr); + ret = varTmpJson->GetString("functionName", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "Create"); + ret = varTmpJson->GetString("scriptId", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "10"); + ret = varTmpJson->GetString("url", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "url3"); + + ret = tmpJson->GetInt("selfSize", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 10); + ret = tmpJson->GetInt("id", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 5); + ret = tmpJson->GetArray("children", &exTmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(exTmpJson, nullptr); + EXPECT_EQ(exTmpJson->GetSize(), 0); + + ret = json->GetArray("samples", &tmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(tmpJson, nullptr); + EXPECT_EQ(tmpJson->GetSize(), 1); +} + HWTEST_F_L0(DebuggerTypesTest, PositionTickInfoCreateTest) { std::string msg; @@ -2158,45 +2285,45 @@ HWTEST_F_L0(DebuggerTypesTest, PositionTickInfoCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of params.sub-key=["line":11,"ticks":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "line":"11","ticks":99}})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of params.sub-key=["line":"11","ticks":"99"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "line":"11","ticks":"99"}})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of params.sub-key=["line":[11],"ticks":[99]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "line":[11],"ticks":[99]}})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // normal params of params.sub-key=["line":11,"ticks":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"line":1,"ticks":0}})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(positionTickInfo, nullptr); EXPECT_EQ(positionTickInfo->GetLine(), 1); EXPECT_EQ(positionTickInfo->GetTicks(), 0); @@ -2227,6 +2354,27 @@ HWTEST_F_L0(DebuggerTypesTest, PositionTickInfoToObjectTest) EXPECT_EQ(Local(result)->Value(), 0); } +HWTEST_F_L0(DebuggerTypesTest, PositionTickInfoToJsonTest) +{ + std::string msg; + std::unique_ptr positionTickInfo; + int32_t tmpInt; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"line":1,"ticks":0}})"; + positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(positionTickInfo, nullptr); + auto json = positionTickInfo->ToJson(); + + ret = json->GetInt("line", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 1); + + ret = json->GetInt("ticks", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 0); +} + HWTEST_F_L0(DebuggerTypesTest, ProfileNodeCreateTest) { std::string msg; @@ -2234,22 +2382,22 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileNodeCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - profileNode = ProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(profileNode, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - profileNode = ProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(profileNode, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - profileNode = ProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(profileNode, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - profileNode = ProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(profileNode, nullptr); // normal params of params.sub-key=[..] @@ -2257,7 +2405,7 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileNodeCreateTest) "id":10, "callFrame": {"functionName":"name0", "scriptId":"12", "url":"url15", "lineNumber":11, "columnNumber":20}, "hitCount":15,"children":[],"positionTicks":[],"deoptReason":"yyy"}})"; - profileNode = ProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(profileNode, nullptr); EXPECT_EQ(profileNode->GetId(), 10); @@ -2338,6 +2486,55 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileNodeToObjectTest) EXPECT_EQ(DebuggerApi::ToStdString(result), "yyy"); } +HWTEST_F_L0(DebuggerTypesTest, ProfileNodeToJsonTest) +{ + std::string msg; + std::unique_ptr profilenode; + std::string tmpStr; + int32_t tmpInt; + std::unique_ptr tmpJson; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ + "id":10, + "callFrame": {"functionName":"name0", "scriptId":"12", "url":"url15", "lineNumber":11, "columnNumber":20}, + "hitCount":15,"children":[],"positionTicks":[],"deoptReason":"yyy"}})"; + profilenode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(profilenode, nullptr); + auto json = profilenode->ToJson(); + + ret = json->GetInt("id", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 10); + + ret = json->GetObject("callFrame", &tmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(tmpJson, nullptr); + ret = tmpJson->GetString("functionName", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "name0"); + ret = tmpJson->GetString("scriptId", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "12"); + ret = tmpJson->GetString("url", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "url15"); + ret = tmpJson->GetInt("lineNumber", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 11); + ret = tmpJson->GetInt("columnNumber", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 20); + + ret = json->GetInt("hitCount", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 15); + + ret = json->GetString("deoptReason", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "yyy"); +} + HWTEST_F_L0(DebuggerTypesTest, ProfileCreateTest) { std::string msg; @@ -2345,35 +2542,37 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - profile = Profile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(profile, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - profile = Profile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(profile, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - profile = Profile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(profile, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - profile = Profile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(profile, nullptr); // abnormal params of params.sub-key=[..] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "startTime":10,"endTime":25,"nodes":[],"samples":[],"timeDeltas":[]}})"; - profile = Profile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + "startTime":10, "endTime":25, "nodes":[{"id":12, + "callFrame": {"functionName":"Create", "scriptId":"10", "url":"url3", "lineNumber":100, "columnNumber":20}}], + "samples":[],"timeDeltas":[]}})"; + profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(profile, nullptr); EXPECT_EQ(profile->GetStartTime(), 10LL); EXPECT_EQ(profile->GetEndTime(), 25LL); const std::vector> *profileNode = profile->GetNodes(); ASSERT_NE(profileNode, nullptr); - EXPECT_EQ((int)profileNode->size(), 0); + EXPECT_EQ((int)profileNode->size(), 1); } HWTEST_F_L0(DebuggerTypesTest, ProfileToObjectTest) @@ -2406,6 +2605,32 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileToObjectTest) ASSERT_TRUE(result->IsArray(ecmaVm)); } +HWTEST_F_L0(DebuggerTypesTest, ProfileToJsonTest) +{ + std::string msg; + std::unique_ptr profile; + std::string tmpStr; + int32_t tmpInt; + std::unique_ptr tmpJson; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ + "startTime":10, "endTime":25, "nodes":[{"id":12, + "callFrame": {"functionName":"Create", "scriptId":"10", "url":"url3", "lineNumber":100, "columnNumber":20}}], + "samples":[],"timeDeltas":[]}})"; + profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(profile, nullptr); + auto json = profile->ToJson(); + + ret = json->GetInt("startTime", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 10); + + ret = json->GetInt("endTime", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 25); +} + HWTEST_F_L0(DebuggerTypesTest, CoverageCreateTest) { std::string msg; @@ -2413,28 +2638,28 @@ HWTEST_F_L0(DebuggerTypesTest, CoverageCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - coverage = Coverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(coverage, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - coverage = Coverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(coverage, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - coverage = Coverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(coverage, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - coverage = Coverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(coverage, nullptr); // normal params of params.sub-key=["startOffset":0,"endOffset":5,"count":13] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "startOffset":0,"endOffset":13,"count":13}})"; - coverage = Coverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(coverage, nullptr); EXPECT_EQ(coverage->GetStartOffset(), 0); EXPECT_EQ(coverage->GetEndOffset(), 13); @@ -2473,6 +2698,33 @@ HWTEST_F_L0(DebuggerTypesTest, CoverageToObjectTest) EXPECT_EQ(Local(result)->Value(), 13); } +HWTEST_F_L0(DebuggerTypesTest, CoverageToJsonTest) +{ + std::string msg; + std::unique_ptr coverage; + std::string tmpStr; + int32_t tmpInt; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ + "startOffset":0,"endOffset":13,"count":13}})"; + coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(coverage, nullptr); + auto json = coverage->ToJson(); + + ret = json->GetInt("startOffset", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 0); + + ret = json->GetInt("endOffset", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 13); + + ret = json->GetInt("count", &tmpInt); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpInt, 13); +} + HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageCreateTest) { std::string msg; @@ -2480,34 +2732,34 @@ HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - functionCoverage = FunctionCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(functionCoverage, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - functionCoverage = FunctionCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(functionCoverage, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - functionCoverage = FunctionCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(functionCoverage, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - functionCoverage = FunctionCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(functionCoverage, nullptr); // normal params of params.sub-key=[..] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "functionName":"Create0","ranges":[],"isBlockCoverage":true}})"; - functionCoverage = FunctionCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + "functionName":"Create0","ranges":[{"startOffset":0,"endOffset":13,"count":13}],"isBlockCoverage":true}})"; + functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(functionCoverage, nullptr); EXPECT_EQ(functionCoverage->GetFunctionName(), "Create0"); const std::vector> *ranges = functionCoverage->GetRanges(); ASSERT_NE(ranges, nullptr); - EXPECT_EQ((int)ranges->size(), 0); + EXPECT_EQ((int)ranges->size(), 1); ASSERT_TRUE(functionCoverage->GetIsBlockCoverage()); } @@ -2540,6 +2792,35 @@ HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageToObjectTest) ASSERT_TRUE(result->IsTrue()); } +HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageToJsonTest) +{ + std::string msg; + std::unique_ptr functionCoverage; + std::string tmpStr; + bool tmpBool; + std::unique_ptr tmpJson; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ + "functionName":"Create0","ranges":[{"startOffset":0,"endOffset":13,"count":13}],"isBlockCoverage":true}})"; + functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(functionCoverage, nullptr); + auto json = functionCoverage->ToJson(); + + ret = json->GetString("functionName", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "Create0"); + + ret = json->GetArray("ranges", &tmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(tmpJson, nullptr); + EXPECT_EQ(tmpJson->GetSize(), 1); + + ret = json->GetBool("isBlockCoverage", &tmpBool); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_TRUE(tmpBool); +} + HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageCreateTest) { std::string msg; @@ -2547,34 +2828,38 @@ HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - scriptCoverage = ScriptCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(scriptCoverage, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - scriptCoverage = ScriptCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(scriptCoverage, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - scriptCoverage = ScriptCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(scriptCoverage, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - scriptCoverage = ScriptCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(scriptCoverage, nullptr); // normal params of params.sub-key=[..] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "scriptId":"1001","url":"url17","functions":[]}})"; - scriptCoverage = ScriptCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + "scriptId":"1001", + "url":"url17", + "functions":[{"functionName":"Create0", + "ranges":[{"startOffset":0, "endOffset":13, "count":13}], + "isBlockCoverage":true}]}})"; + scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(scriptCoverage, nullptr); EXPECT_EQ(scriptCoverage->GetScriptId(), "1001"); EXPECT_EQ(scriptCoverage->GetUrl(), "url17"); const std::vector> *functions = scriptCoverage->GetFunctions(); ASSERT_NE(functions, nullptr); - EXPECT_EQ((int)functions->size(), 0); + EXPECT_EQ((int)functions->size(), 1); } HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageToObjectTest) @@ -2605,4 +2890,36 @@ HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageToObjectTest) ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); ASSERT_TRUE(result->IsArray(ecmaVm)); } + +HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageToJsonTest) +{ + std::string msg; + std::unique_ptr scriptCoverage; + std::string tmpStr; + std::unique_ptr tmpJson; + Result ret; + + msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ + "scriptId":"1001", + "url":"url17", + "functions": [{"functionName":"Create0", + "ranges": [{"startOffset":0, "endOffset":13, "count":13}], + "isBlockCoverage":true}]}})"; + scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + ASSERT_NE(scriptCoverage, nullptr); + auto json = scriptCoverage->ToJson(); + + ret = json->GetString("scriptId", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "1001"); + + ret = json->GetString("url", &tmpStr); + EXPECT_EQ(ret, Result::SUCCESS); + EXPECT_EQ(tmpStr, "url17"); + + ret = json->GetArray("functions", &tmpJson); + EXPECT_EQ(ret, Result::SUCCESS); + ASSERT_NE(tmpJson, nullptr); + EXPECT_EQ(tmpJson->GetSize(), 1); +} } // namespace panda::test -- Gitee From 74287cd45ab648bf8724644255796727cae2ba7f Mon Sep 17 00:00:00 2001 From: DaiHN Date: Tue, 14 Jun 2022 19:08:28 +0800 Subject: [PATCH 010/154] Remove JSArgument's unused accessor ------------------------------------- Remove JSArgument's unused accessor:set [[ParameterMap]] as undefined issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5C71F?from=project-issue Signed-off-by: DaiHN Change-Id: Ic96b8ff2797b76fb63c20d70461680afea992483 --- ecmascript/js_arguments.cpp | 105 +-------------------------- ecmascript/js_arguments.h | 5 -- ecmascript/object_factory.cpp | 2 - ecmascript/stubs/runtime_stubs-inl.h | 1 + ecmascript/tests/dump_test.cpp | 25 ++----- 5 files changed, 10 insertions(+), 128 deletions(-) diff --git a/ecmascript/js_arguments.cpp b/ecmascript/js_arguments.cpp index 96c8c8d1..a5a3d0d0 100644 --- a/ecmascript/js_arguments.cpp +++ b/ecmascript/js_arguments.cpp @@ -30,22 +30,6 @@ bool JSArguments::GetOwnProperty(JSThread *thread, const JSHandle & return true; } - // 4.Let map be the value of the [[ParameterMap]] internal slot of the arguments object. - JSHandle map(thread, args->GetParameterMap()); - - // 5.Let isMapped be HasOwnProperty(map, P). - bool isMapped = JSTaggedValue::HasOwnProperty(thread, map, key); - - // 6.Assert: isMapped is never an abrupt completion. - ASSERT(!thread->HasPendingException()); - - // 7.If the value of isMapped is true, then - // a.Set desc.[[Value]] to Get(map, P). - if (isMapped) { - auto prop = JSObject::GetProperty(thread, map, key).GetValue(); - desc.SetValue(prop); - } - // 8.If IsDataDescriptor(desc) is true and P is "caller" and desc.[[Value]] is a strict mode Function object, // throw a TypeError exception. JSHandle caller = thread->GetEcmaVM()->GetFactory()->NewFromASCII("caller"); @@ -60,46 +44,12 @@ bool JSArguments::GetOwnProperty(JSThread *thread, const JSHandle & bool JSArguments::DefineOwnProperty(JSThread *thread, const JSHandle &args, const JSHandle &key, const PropertyDescriptor &desc) { - // 1 ~ 2 Let args be the arguments object and get map. - JSHandle map(thread, args->GetParameterMap()); - - // 3.Let isMapped be HasOwnProperty(map, P). - bool isMapped = JSTaggedValue::HasOwnProperty(thread, map, key); - // 4.Let allowed be OrdinaryDefineOwnProperty(args, P, Desc). bool allowed = JSObject::OrdinaryDefineOwnProperty(thread, JSHandle(args), key, desc); // 5.ReturnIfAbrupt(allowed). RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, allowed); - // 6.If allowed is false, return false. - if (!allowed) { - return false; - } - - // 7.If the value of isMapped is true, then - // a.If IsAccessorDescriptor(Desc) is true, then - // i.Call map.[[Delete]](P). - // b.Else - // i.If Desc.[[Value]] is present, then - // 1.Let setStatus be Set(map, P, Desc.[[Value]], false). - // 2.Assert: setStatus is true because formal parameters mapped by argument objects are always writable. - // ii.If Desc.[[Writable]] is present and its value is false, then - // 1.Call map.[[Delete]](P). - if (isMapped) { - if (desc.IsAccessorDescriptor()) { - JSTaggedValue::DeleteProperty(thread, map, key); - } else { - if (desc.HasValue()) { - [[maybe_unused]] bool setStatus = JSTaggedValue::SetProperty(thread, map, key, desc.GetValue(), false); - ASSERT(setStatus == true); - } - if (desc.HasWritable() && !desc.IsWritable()) { - JSTaggedValue::DeleteProperty(thread, map, key); - } - } - } - // 8.Return true. return true; } @@ -107,53 +57,15 @@ bool JSArguments::DefineOwnProperty(JSThread *thread, const JSHandle &args, const JSHandle &key, const JSHandle &receiver) { - // 1 ~ 2 Let args be the arguments object and get map. - JSHandle map(thread, args->GetParameterMap()); - - // 3.Let isMapped be HasOwnProperty(map, P). - bool isMapped = JSTaggedValue::HasOwnProperty(thread, map, key); - - // 4.Assert: isMapped is not an abrupt completion. - ASSERT(!thread->HasPendingException()); - // 5.If the value of isMapped is false, then // a.Return the result of calling the default ordinary object [[Get]] internal method (9.1.8) // on args passing P and Receiver as the arguments. - if (!isMapped) { - return JSTaggedValue::GetProperty(thread, JSHandle::Cast(args), key, receiver); - } - - // 6.Else map contains a formal parameter mapping for P, - // a.Return Get(map, P). - return JSTaggedValue::GetProperty(thread, map, key); + return JSTaggedValue::GetProperty(thread, JSHandle::Cast(args), key, receiver); } bool JSArguments::SetProperty(JSThread *thread, const JSHandle &args, const JSHandle &key, const JSHandle &value, const JSHandle &receiver) { - // 1.Let args be the arguments object. - JSHandle map(thread, args->GetParameterMap()); - - // 2.If SameValue(args, Receiver) is false, then - // a.Let isMapped be false. - bool isMapped = false; - if (JSTaggedValue::SameValue(args.GetTaggedValue(), receiver.GetTaggedValue())) { - // 3.Else, - // a.Let map be the value of the [[ParameterMap]] internal slot of the arguments object. - // b.Let isMapped be HasOwnProperty(map, P). - // c.Assert: isMapped is not an abrupt completion. - isMapped = JSTaggedValue::HasOwnProperty(thread, map, key); - ASSERT(!thread->HasPendingException()); - } - - // 4.If isMapped is true, then - // a.Let setStatus be Set(map, P, V, false). - // b.Assert: setStatus is true because formal parameters mapped by argument objects are always writable. - if (isMapped) { - [[maybe_unused]] bool setStatus = JSTaggedValue::SetProperty(thread, map, key, value); - ASSERT(setStatus == true); - } - // 5.Return the result of calling the default ordinary object [[Set]] internal method (9.1.9) // on args passing P, V and Receiver as the arguments. return JSTaggedValue::SetProperty(thread, JSHandle::Cast(args), key, value, receiver); @@ -162,15 +74,6 @@ bool JSArguments::SetProperty(JSThread *thread, const JSHandle &arg bool JSArguments::DeleteProperty(JSThread *thread, const JSHandle &args, const JSHandle &key) { - // 1.Let map be the value of the [[ParameterMap]] internal slot of the arguments object. - JSHandle map(thread, args->GetParameterMap()); - - // 2.Let isMapped be HasOwnProperty(map, P). - bool isMapped = JSTaggedValue::HasOwnProperty(thread, map, key); - - // 3.Assert: isMapped is not an abrupt completion. - ASSERT(!thread->HasPendingException()); - // 4.Let result be the result of calling the default [[Delete]] internal method for ordinary objects (9.1.10) // on the arguments object passing P as the argument. bool result = JSTaggedValue::DeleteProperty(thread, JSHandle(args), key); @@ -178,12 +81,6 @@ bool JSArguments::DeleteProperty(JSThread *thread, const JSHandle & // 5.ReturnIfAbrupt(result). RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, result); - // 6.If result is true and the value of isMapped is true, then - // a.Call map.[[Delete]](P). - if (result && isMapped) { - JSTaggedValue::DeleteProperty(thread, map, key); - } - // 7.Return result. return result; } diff --git a/ecmascript/js_arguments.h b/ecmascript/js_arguments.h index c04ed12b..32819d58 100644 --- a/ecmascript/js_arguments.h +++ b/ecmascript/js_arguments.h @@ -58,11 +58,6 @@ public: static bool DeleteProperty(JSThread *thread, const JSHandle &args, const JSHandle &key); // 9.4.4.6 CreateUnmappedArgumentsObject(argumentsList) // 9.4.4.7 CreateMappedArgumentsObject ( func, formals, argumentsList, env ) - - static constexpr size_t PARAMETER_MAP_OFFSET = JSObject::SIZE; - ACCESSORS(ParameterMap, PARAMETER_MAP_OFFSET, SIZE) - - DECL_VISIT_OBJECT_FOR_JS_OBJECT(JSObject, PARAMETER_MAP_OFFSET, SIZE) }; } // namespace panda::ecmascript diff --git a/ecmascript/object_factory.cpp b/ecmascript/object_factory.cpp index fa29a520..9b7f14f6 100644 --- a/ecmascript/object_factory.cpp +++ b/ecmascript/object_factory.cpp @@ -781,7 +781,6 @@ JSHandle ObjectFactory::NewJSArguments() JSHandle env = vm_->GetGlobalEnv(); JSHandle dynclass = JSHandle::Cast(env->GetArgumentsClass()); JSHandle obj = JSHandle::Cast(NewJSObject(dynclass)); - obj->SetParameterMap(thread_, JSTaggedValue::Undefined()); return obj; } @@ -1163,7 +1162,6 @@ void ObjectFactory::InitializeJSObject(const JSHandle &obj, const JSHa JSBoundFunction::Cast(*obj)->SetBoundArguments(JSTaggedValue::Undefined()); break; case JSType::JS_ARGUMENTS: - JSArguments::Cast(*obj)->SetParameterMap(JSTaggedValue::Undefined()); break; case JSType::JS_FORIN_ITERATOR: case JSType::JS_MAP_ITERATOR: diff --git a/ecmascript/stubs/runtime_stubs-inl.h b/ecmascript/stubs/runtime_stubs-inl.h index 2cf45b15..36b663f0 100644 --- a/ecmascript/stubs/runtime_stubs-inl.h +++ b/ecmascript/stubs/runtime_stubs-inl.h @@ -1215,6 +1215,7 @@ JSTaggedValue RuntimeStubs::RuntimeGetUnmapedArgs(JSThread *thread, JSTaggedType uint32_t len = argumentsList->GetLength(); // 2. Let obj be ObjectCreate(%ObjectPrototype%, «[[ParameterMap]]»). // 3. Set obj’s [[ParameterMap]] internal slot to undefined. + // [[ParameterMap]] setted as undifined. JSHandle obj = factory->NewJSArguments(); // 4. Perform DefinePropertyOrThrow(obj, "length", PropertyDescriptor{[[Value]]: len, [[Writable]]: true, // [[Enumerable]]: false, [[Configurable]]: true}). diff --git a/ecmascript/tests/dump_test.cpp b/ecmascript/tests/dump_test.cpp index 174fd3d5..02873541 100644 --- a/ecmascript/tests/dump_test.cpp +++ b/ecmascript/tests/dump_test.cpp @@ -336,6 +336,7 @@ HWTEST_F_L0(EcmaDumpTest, HeapProfileDump) case JSType::JS_TYPE_ERROR: case JSType::JS_REFERENCE_ERROR: case JSType::JS_URI_ERROR: + case JSType::JS_ARGUMENTS: case JSType::JS_SYNTAX_ERROR: case JSType::JS_OBJECT: { CHECK_DUMP_FIELDS(ECMAObject::SIZE, JSObject::SIZE, 2U) @@ -491,9 +492,6 @@ HWTEST_F_L0(EcmaDumpTest, HeapProfileDump) DUMP_FOR_HANDLE(date) break; } - case JSType::JS_ITERATOR: - // JS Iterate is a tool class, so we don't need to check it. - break; case JSType::JS_FORIN_ITERATOR: { CHECK_DUMP_FIELDS(JSObject::SIZE, JSForInIterator::SIZE, 4U) JSHandle array(thread, factory->NewJSArray().GetTaggedValue()); @@ -598,11 +596,6 @@ HWTEST_F_L0(EcmaDumpTest, HeapProfileDump) NEW_OBJECT_AND_DUMP(JSDataView, JS_DATA_VIEW) break; } - case JSType::JS_ARGUMENTS: { - CHECK_DUMP_FIELDS(JSObject::SIZE, JSArguments::SIZE, 1U) - NEW_OBJECT_AND_DUMP(JSArguments, JS_ARGUMENTS) - break; - } case JSType::JS_GENERATOR_OBJECT: { CHECK_DUMP_FIELDS(JSObject::SIZE, JSGeneratorObject::SIZE, 3U) NEW_OBJECT_AND_DUMP(JSGeneratorObject, JS_GENERATOR_OBJECT) @@ -678,15 +671,6 @@ HWTEST_F_L0(EcmaDumpTest, HeapProfileDump) DUMP_FOR_HANDLE(dict) break; } - case JSType::FREE_OBJECT_WITH_ONE_FIELD: - case JSType::FREE_OBJECT_WITH_NONE_FIELD: - case JSType::FREE_OBJECT_WITH_TWO_FIELD: - { - break; - } - case JSType::JS_NATIVE_POINTER: { - break; - } case JSType::GLOBAL_ENV: { DUMP_FOR_HANDLE(globalEnv) break; @@ -1068,6 +1052,13 @@ HWTEST_F_L0(EcmaDumpTest, HeapProfileDump) DUMP_FOR_HANDLE(cjsRequire); break; } + case JSType::JS_ITERATOR: + case JSType::FREE_OBJECT_WITH_ONE_FIELD: + case JSType::FREE_OBJECT_WITH_NONE_FIELD: + case JSType::FREE_OBJECT_WITH_TWO_FIELD: + case JSType::JS_NATIVE_POINTER: { + break; + } default: LOG_ECMA_MEM(ERROR) << "JSType " << static_cast(type) << " cannot be dumped."; UNREACHABLE(); -- Gitee From 831018e66d818490de40e9fd14e09aad07ee19f2 Mon Sep 17 00:00:00 2001 From: xliu Date: Fri, 10 Jun 2022 15:33:31 +0800 Subject: [PATCH 011/154] add stub for TypedArray Description 1.add GetPrpertyByIndex stub for TypedArray. 2.add GetPrpertyByName stub for TypedArray. 3.add SetPrpertyByIndex stub for TypedArray. 4.add SetPrpertyByName stub for TypedArray. Issue: #I5BPJM:add stub for typedarray Signed-off-by: xliu Change-Id: Ic76834e5224e4b03fa96e167a61c7c0c0c36940c --- ecmascript/compiler/stub-inl.h | 12 +- ecmascript/compiler/stub.cpp | 290 ++++++++++++++++++++++++++++- ecmascript/compiler/stub.h | 5 + ecmascript/stubs/runtime_stubs.cpp | 20 ++ ecmascript/stubs/runtime_stubs.h | 4 +- 5 files changed, 326 insertions(+), 5 deletions(-) diff --git a/ecmascript/compiler/stub-inl.h b/ecmascript/compiler/stub-inl.h index 3ef80b73..ef8cce8b 100644 --- a/ecmascript/compiler/stub-inl.h +++ b/ecmascript/compiler/stub-inl.h @@ -1527,13 +1527,21 @@ inline GateRef Stub::IsSpecialIndexedObj(GateRef jsType) inline GateRef Stub::IsSpecialContainer(GateRef jsType) { - // arraylist and vector has fast pass now + // arraylist and vector has fast pass now return TruncInt32ToInt1(Int32And( ZExtInt1ToInt32( Int32GreaterThanOrEqual(jsType, Int32(static_cast(JSType::JS_API_ARRAY_LIST)))), ZExtInt1ToInt32(Int32LessThanOrEqual(jsType, Int32(static_cast(JSType::JS_API_QUEUE)))))); } +inline GateRef Stub::IsFastTypeArray(GateRef jsType) +{ + return TruncInt32ToInt1(Int32And( + ZExtInt1ToInt32( + Int32GreaterThanOrEqual(jsType, Int32(static_cast(JSType::JS_TYPED_ARRAY_BEGIN)))), + ZExtInt1ToInt32(Int32LessThanOrEqual(jsType, Int32(static_cast(JSType::JS_FLOAT64_ARRAY)))))); +} + inline GateRef Stub::IsAccessorInternal(GateRef value) { return Int32Equal(GetObjectType(LoadHClass(value)), @@ -2019,4 +2027,4 @@ inline GateRef Stub::HasPendingException(GateRef glue) return Int64NotEqual(exception, Int64(JSTaggedValue::VALUE_HOLE)); } } // namespace panda::ecmascript::kungfu -#endif // ECMASCRIPT_COMPILER_STUB_INL_H \ No newline at end of file +#endif // ECMASCRIPT_COMPILER_STUB_INL_H diff --git a/ecmascript/compiler/stub.cpp b/ecmascript/compiler/stub.cpp index ffcf0219..ff9b6a60 100644 --- a/ecmascript/compiler/stub.cpp +++ b/ecmascript/compiler/stub.cpp @@ -1877,6 +1877,18 @@ GateRef Stub::GetPropertyByIndex(GateRef glue, GateRef receiver, GateRef index) Branch(IsSpecialIndexedObj(jsType), &isSpecialIndexed, ¬SpecialIndexed); Bind(&isSpecialIndexed); { + // TypeArray + Label isFastTypeArray(env); + Label notFastTypeArray(env); + Branch(IsFastTypeArray(jsType), &isFastTypeArray, ¬FastTypeArray); + Bind(&isFastTypeArray); + { + result = CallRuntime(glue, RTSTUB_ID(GetTypeArrayPropertyByIndex), + { *holder, IntBuildTaggedTypeWithNoGC(index), IntBuildTaggedTypeWithNoGC(jsType)}); + Jump(&exit); + } + Bind(¬FastTypeArray); + Label isSpecialContainer(env); Label notSpecialContainer(env); // Add SpecialContainer @@ -1995,8 +2007,29 @@ GateRef Stub::GetPropertyByName(GateRef glue, GateRef receiver, GateRef key) Branch(IsSpecialIndexedObj(jsType), &isSIndexObj, ¬SIndexObj); Bind(&isSIndexObj); { - result = Hole(); - Jump(&exit); + // TypeArray + Label isFastTypeArray(env); + Label notFastTypeArray(env); + Branch(IsFastTypeArray(jsType), &isFastTypeArray, ¬FastTypeArray); + Bind(&isFastTypeArray); + { + result = GetTypeArrayPropertyByName(glue, receiver, *holder, key, jsType); + Label isNull(env); + Label notNull(env); + Branch(TaggedIsNull(*result), &isNull, ¬Null); + Bind(&isNull); + { + result = Hole(); + Jump(&exit); + } + Bind(¬Null); + Branch(TaggedIsHole(*result), ¬SIndexObj, &exit); + } + Bind(¬FastTypeArray); + { + result = Hole(); + Jump(&exit); + } } Bind(¬SIndexObj); { @@ -2220,6 +2253,17 @@ GateRef Stub::SetPropertyByIndex(GateRef glue, GateRef receiver, GateRef index, Branch(IsSpecialIndexedObj(jsType), &isSpecialIndex, ¬SpecialIndex); Bind(&isSpecialIndex); { + // TypeArray + Label isFastTypeArray(env); + Label notFastTypeArray(env); + Branch(IsFastTypeArray(jsType), &isFastTypeArray, ¬FastTypeArray); + Bind(&isFastTypeArray); + { + returnValue = ChangeTaggedPointerToInt64(CallRuntime(glue, RTSTUB_ID(SetTypeArrayPropertyByIndex), + { receiver, IntBuildTaggedTypeWithNoGC(index), value, IntBuildTaggedTypeWithNoGC(jsType)})); + Jump(&exit); + } + Bind(¬FastTypeArray); returnValue = Hole(VariableType::INT64()); Jump(&exit); } @@ -2345,6 +2389,26 @@ GateRef Stub::SetPropertyByName(GateRef glue, GateRef receiver, GateRef key, Gat Branch(IsSpecialIndexedObj(jsType), &isSIndexObj, ¬SIndexObj); Bind(&isSIndexObj); { + Label isFastTypeArray(env); + Label notFastTypeArray(env); + Branch(IsFastTypeArray(jsType), &isFastTypeArray, ¬FastTypeArray); + Bind(&isFastTypeArray); + { + result = + ChangeTaggedPointerToInt64(SetTypeArrayPropertyByName(glue, receiver, *holder, key, value, jsType)); + Label isNull(env); + Label notNull(env); + Branch(TaggedIsNull(*result), &isNull, ¬Null); + Bind(&isNull); + { + result = Hole(VariableType::INT64()); + Jump(&exit); + } + Bind(¬Null); + Branch(TaggedIsHole(*result), ¬SIndexObj, &exit); + } + Bind(¬FastTypeArray); + Label isSpecialContainer(env); Label notSpecialContainer(env); // Add SpecialContainer @@ -3926,4 +3990,226 @@ GateRef Stub::JSCallDispatch(GateRef glue, GateRef func, GateRef actualNumArgs, env->SubCfgExit(); return ret; } + +GateRef Stub::TryStringOrSymbelToElementIndex(GateRef key) +{ + auto env = GetEnvironment(); + Label entry(env); + env->SubCfgEntry(&entry); + Label exit(env); + DEFVARIABLE(result, VariableType::INT32(), Int32(-1)); + + Label keyNotSymbol(env); + Branch(IsSymbol(key), &exit, &keyNotSymbol); + Bind(&keyNotSymbol); + + Label greatThanZero(env); + Label inRange(env); + auto len = GetLengthFromString(key); + Branch(Int32Equal(len, Int32(0)), &exit, &greatThanZero); + Bind(&greatThanZero); + Branch(Int32GreaterThan(len, Int32(MAX_INDEX_LEN)), &exit, &inRange); + Bind(&inRange); + { + Label isUtf8(env); + Branch(IsUtf16String(key), &exit, &isUtf8); + Bind(&isUtf8); + + GateRef data = PtrAdd(key, IntPtr(EcmaString::DATA_OFFSET)); + DEFVARIABLE(c, VariableType::INT32(), Int32(0)); + c = ZExtInt8ToInt32(Load(VariableType::INT8(), data)); + Label isDigitZero(env); + Label notDigitZero(env); + Branch(Int32Equal(*c, Int32('0')), &isDigitZero, ¬DigitZero); + Bind(&isDigitZero); + { + Label lengthIsOne(env); + Branch(Int32Equal(len, Int32(1)), &lengthIsOne, &exit); + Bind(&lengthIsOne); + { + result = Int32(0); + Jump(&exit); + } + } + Bind(¬DigitZero); + { + Label isDigit(env); + Label notIsDigit(env); + DEFVARIABLE(i, VariableType::INT32(), Int32(1)); + DEFVARIABLE(n, VariableType::INT32(), Int32Sub(*c, Int32('0'))); + + Branch(IsDigit(*c), &isDigit, ¬IsDigit); + Label loopHead(env); + Label loopEnd(env); + Label afterLoop(env); + Bind(&isDigit); + Branch(Int32UnsignedLessThan(*i, len), &loopHead, &afterLoop); + LoopBegin(&loopHead); + { + c = ZExtInt8ToInt32(Load(VariableType::INT8(), data, ChangeInt32ToIntPtr(*i))); + Label isDigit2(env); + Label notDigit2(env); + Branch(IsDigit(*c), &isDigit2, ¬Digit2); + Bind(&isDigit2); + { + // 10 means the base of digit is 10. + n = Int32Add(Int32Mul(*n, Int32(10)), + Int32Sub(*c, Int32('0'))); + i = Int32Add(*i, Int32(1)); + Branch(Int32UnsignedLessThan(*i, len), &loopEnd, &afterLoop); + } + Bind(¬Digit2); + { + Label hasPoint(env); + Branch(Int32Equal(*c, Int32('.')), &hasPoint, &exit); + Bind(&hasPoint); + { + result = Int32(-2); // -2:return -2 means should goto slow path + Jump(&exit); + } + } + } + Bind(&loopEnd); + LoopEnd(&loopHead); + Bind(&afterLoop); + { + Label lessThanMaxIndex(env); + Branch(Int32UnsignedLessThan(*n, Int32(JSObject::MAX_ELEMENT_INDEX)), + &lessThanMaxIndex, &exit); + Bind(&lessThanMaxIndex); + { + result = *n; + Jump(&exit); + } + } + Bind(¬IsDigit); + { + Label isNegative(env); + Branch(Int32Equal(*c, Int32('-')), &isNegative, &exit); + Bind(&isNegative); + { + result = Int32(-2); // -2:return -2 means should goto slow path + Jump(&exit); + } + } + } + } + Bind(&exit); + auto ret = *result; + env->SubCfgExit(); + return ret; +} + +GateRef Stub::GetTypeArrayPropertyByName(GateRef glue, GateRef receiver, GateRef holder, GateRef key, GateRef jsType) +{ + auto env = GetEnvironment(); + Label entry(env); + env->SubCfgEntry(&entry); + Label exit(env); + DEFVARIABLE(result, VariableType::JS_ANY(), Hole()); + + Label notOnProtoChain(env); + Branch(Int64NotEqual(receiver, holder), &exit, ¬OnProtoChain); + Bind(¬OnProtoChain); + + auto negativeZero = GetGlobalConstantValue( + VariableType::JS_POINTER(), glue, ConstantIndex::NEGATIVE_ZERO_STRING_INDEX); + Label isNegativeZero(env); + Label notNegativeZero(env); + Branch(Int64Equal(negativeZero, key), &isNegativeZero, ¬NegativeZero); + Bind(&isNegativeZero); + { + result = Undefined(); + Jump(&exit); + } + Bind(¬NegativeZero); + { + GateRef index = TryStringOrSymbelToElementIndex(key); + Label validIndex(env); + Label notValidIndex(env); + Branch(Int32GreaterThanOrEqual(index, Int32(0)), &validIndex, ¬ValidIndex); + Bind(&validIndex); + { + result = CallRuntime(glue, RTSTUB_ID(GetTypeArrayPropertyByIndex), + { holder, IntBuildTaggedTypeWithNoGC(index), IntBuildTaggedTypeWithNoGC(jsType) }); + Jump(&exit); + } + Bind(¬ValidIndex); + { + Label returnNull(env); + Branch(Int32Equal(index, Int32(-2)), &returnNull, &exit); // -2:equal -2 means should goto slow path + Bind(&returnNull); + { + result = Null(); + Jump(&exit); + } + } + } + + Bind(&exit); + auto ret = *result; + env->SubCfgExit(); + return ret; +} + +GateRef Stub::SetTypeArrayPropertyByName(GateRef glue, GateRef receiver, GateRef holder, GateRef key, GateRef value, + GateRef jsType) +{ + auto env = GetEnvironment(); + Label entry(env); + env->SubCfgEntry(&entry); + Label exit(env); + DEFVARIABLE(result, VariableType::JS_ANY(), Hole()); + Label notOnProtoChain(env); + Branch(Int64NotEqual(receiver, holder), &exit, ¬OnProtoChain); + Bind(¬OnProtoChain); + + auto negativeZero = GetGlobalConstantValue( + VariableType::JS_POINTER(), glue, ConstantIndex::NEGATIVE_ZERO_STRING_INDEX); + Label isNegativeZero(env); + Label notNegativeZero(env); + Branch(Int64Equal(negativeZero, key), &isNegativeZero, ¬NegativeZero); + Bind(&isNegativeZero); + { + Label isObj(env); + Label notObj(env); + Branch(TaggedObjectIsEcmaObject(value), &isObj, ¬Obj); + Bind(&isObj); + { + result = Null(); + Jump(&exit); + } + Bind(¬Obj); + result = Undefined(); + Jump(&exit); + } + Bind(¬NegativeZero); + { + GateRef index = TryStringOrSymbelToElementIndex(key); + Label validIndex(env); + Label notValidIndex(env); + Branch(Int32GreaterThanOrEqual(index, Int32(0)), &validIndex, ¬ValidIndex); + Bind(&validIndex); + { + result = CallRuntime(glue, RTSTUB_ID(SetTypeArrayPropertyByIndex), + { receiver, IntBuildTaggedTypeWithNoGC(index), value, IntBuildTaggedTypeWithNoGC(jsType) }); + Jump(&exit); + } + Bind(¬ValidIndex); + { + Label returnNull(env); + Branch(Int32Equal(index, Int32(-2)), &returnNull, &exit); // -2:equal -2 means should goto slow path + Bind(&returnNull); + { + result = Null(); + Jump(&exit); + } + } + } + + Bind(&exit); + auto ret = *result; + env->SubCfgExit(); + return ret; +} } // namespace panda::ecmascript::kungfu diff --git a/ecmascript/compiler/stub.h b/ecmascript/compiler/stub.h index 9f74286d..6e4ec4d8 100644 --- a/ecmascript/compiler/stub.h +++ b/ecmascript/compiler/stub.h @@ -466,6 +466,11 @@ public: GateRef CallGetterHelper(GateRef glue, GateRef receiver, GateRef holder, GateRef accessor); GateRef JSCallDispatch(GateRef glue, GateRef func, GateRef actualNumArgs, JSCallMode mode, std::initializer_list args); + GateRef IsFastTypeArray(GateRef jsType); + GateRef GetTypeArrayPropertyByName(GateRef glue, GateRef receiver, GateRef holder, GateRef key, GateRef jsType); + GateRef SetTypeArrayPropertyByName(GateRef glue, GateRef receiver, GateRef holder, GateRef key, GateRef value, + GateRef jsType); + GateRef TryStringOrSymbelToElementIndex(GateRef string); private: using BinaryOperation = std::function; template diff --git a/ecmascript/stubs/runtime_stubs.cpp b/ecmascript/stubs/runtime_stubs.cpp index 2f06e8fd..0b40215e 100644 --- a/ecmascript/stubs/runtime_stubs.cpp +++ b/ecmascript/stubs/runtime_stubs.cpp @@ -32,6 +32,7 @@ #include "ecmascript/js_object.h" #include "ecmascript/js_proxy.h" #include "ecmascript/js_thread.h" +#include "ecmascript/js_typed_array.h" #include "ecmascript/jspandafile/program_object.h" #include "ecmascript/layout_info.h" #include "ecmascript/mem/space-inl.h" @@ -1584,6 +1585,25 @@ DEF_RUNTIME_STUBS(NewAotObjDynRange) return RuntimeNewAotObjDynRange(thread, argv, argc).GetRawData(); } +DEF_RUNTIME_STUBS(GetTypeArrayPropertyByIndex) +{ + RUNTIME_STUBS_HEADER(GetTypeArrayPropertyByIndex); + JSTaggedValue obj = GetArg(argv, argc, 0); + JSTaggedValue idx = GetArg(argv, argc, 1); + JSTaggedValue jsType = GetArg(argv, argc, 2); // 2:means the second parameter + return JSTypedArray::FastGetPropertyByIndex(thread, obj, idx.GetInt(), JSType(jsType.GetInt())).GetRawData(); +} + +DEF_RUNTIME_STUBS(SetTypeArrayPropertyByIndex) +{ + RUNTIME_STUBS_HEADER(SetTypeArrayPropertyByIndex); + JSTaggedValue obj = GetArg(argv, argc, 0); + JSTaggedValue idx = GetArg(argv, argc, 1); + JSTaggedValue value = GetArg(argv, argc, 2); // 2:means the second parameter + JSTaggedValue jsType = GetArg(argv, argc, 3); // 3:means the third parameter + return JSTypedArray::FastSetPropertyByIndex(thread, obj, idx.GetInt(), value, JSType(jsType.GetInt())).GetRawData(); +} + JSTaggedType RuntimeStubs::CreateArrayFromList([[maybe_unused]]uintptr_t argGlue, int32_t argc, JSTaggedValue *argvPtr) { auto thread = JSThread::GlueToJSThread(argGlue); diff --git a/ecmascript/stubs/runtime_stubs.h b/ecmascript/stubs/runtime_stubs.h index 10fb250d..1358e54c 100644 --- a/ecmascript/stubs/runtime_stubs.h +++ b/ecmascript/stubs/runtime_stubs.h @@ -220,7 +220,9 @@ using JSFunctionEntryType = uint64_t (*)(uintptr_t glue, uintptr_t prevFp, uint3 V(NewAotLexicalEnvDyn) \ V(NewAotLexicalEnvWithNameDyn) \ V(SuspendAotGenerator) \ - V(NewAotObjDynRange) + V(NewAotObjDynRange) \ + V(GetTypeArrayPropertyByIndex) \ + V(SetTypeArrayPropertyByIndex) #define RUNTIME_STUB_LIST(V) \ RUNTIME_ASM_STUB_LIST(V) \ -- Gitee From 4d18ed01b07ca990e0d433ca4fdbcf7640564796 Mon Sep 17 00:00:00 2001 From: "yingguofeng@huawei.com" Date: Thu, 9 Jun 2022 19:22:45 +0800 Subject: [PATCH 012/154] Description:Native Memory Leak or error Issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5C883?from=project-issue Change-Id: I3cdf41f9292fccb9a7e1164babc30cf77e6ac163 Signed-off-by: yingguofeng@huawei.com --- ecmascript/builtins.cpp | 6 ++---- ecmascript/dfx/vmstat/runtime_stat.cpp | 6 ++---- ecmascript/ecma_vm.cpp | 3 +-- ecmascript/interpreter/interpreter-inl.h | 4 ++-- ecmascript/mem/concurrent_marker.cpp | 3 +-- ecmascript/mem/full_gc.cpp | 2 +- ecmascript/mem/linear_space.h | 2 ++ ecmascript/mem/mem_map_allocator.cpp | 8 ++++---- ecmascript/mem/mem_map_allocator.h | 1 + ecmascript/mem/partial_gc.cpp | 3 +-- ecmascript/mem/work_manager.cpp | 16 +++++++++++----- ecmascript/mem/work_manager.h | 2 +- 12 files changed, 29 insertions(+), 27 deletions(-) diff --git a/ecmascript/builtins.cpp b/ecmascript/builtins.cpp index 38242dcb..8d2b5ef0 100644 --- a/ecmascript/builtins.cpp +++ b/ecmascript/builtins.cpp @@ -372,8 +372,7 @@ void Builtins::InitializeForSnapshot(JSThread *thread) InitializeIcuData(); // Initialize ArkTools - JSRuntimeOptions options = vm_->GetJSOptions(); - if (options.EnableArkTools()) { + if (vm_->GetJSOptions().EnableArkTools()) { auto env = vm_->GetGlobalEnv(); auto globalObject = JSHandle::Cast(env->GetJSGlobalObject()); JSHandle arkTools(InitializeArkTools(env)); @@ -392,8 +391,7 @@ void Builtins::InitializeGlobalObject(const JSHandle &env, const JSHa SetFunction(env, globalObject, "stopRuntimeStat", Global::StopRuntimeStat, 0); #endif - JSRuntimeOptions options = vm_->GetJSOptions(); - if (options.EnableArkTools()) { + if (vm_->GetJSOptions().EnableArkTools()) { JSHandle arkTools(InitializeArkTools(env)); SetConstantObject(globalObject, "ArkTools", arkTools); } diff --git a/ecmascript/dfx/vmstat/runtime_stat.cpp b/ecmascript/dfx/vmstat/runtime_stat.cpp index 6b4e8592..bdfc2791 100644 --- a/ecmascript/dfx/vmstat/runtime_stat.cpp +++ b/ecmascript/dfx/vmstat/runtime_stat.cpp @@ -108,16 +108,14 @@ void EcmaRuntimeStat::PrintAllStats() const EcmaRuntimeStatScope::EcmaRuntimeStatScope(EcmaVM *vm) : vm_(vm) { - JSRuntimeOptions options = vm_->GetJSOptions(); - if (options.IsEnableRuntimeStat()) { + if (vm_->GetJSOptions().IsEnableRuntimeStat()) { vm_->SetRuntimeStatEnable(true); } } EcmaRuntimeStatScope::~EcmaRuntimeStatScope() { - JSRuntimeOptions options = vm_->GetJSOptions(); - if (options.IsEnableRuntimeStat()) { + if (vm_->GetJSOptions().IsEnableRuntimeStat()) { vm_->SetRuntimeStatEnable(false); } vm_ = nullptr; diff --git a/ecmascript/ecma_vm.cpp b/ecmascript/ecma_vm.cpp index 793e8957..ddd3d437 100644 --- a/ecmascript/ecma_vm.cpp +++ b/ecmascript/ecma_vm.cpp @@ -332,8 +332,7 @@ JSHandle EcmaVM::GetMicroJobQueue() const EcmaVM::CpuProfilingScope::CpuProfilingScope(EcmaVM* vm) : vm_(vm), profiler_(nullptr) { #if defined(ECMASCRIPT_SUPPORT_CPUPROFILER) - JSRuntimeOptions options = vm_->GetJSOptions(); - if (options.EnableCpuProfiler()) { + if (vm_->GetJSOptions().EnableCpuProfiler()) { profiler_ = CpuProfiler::GetInstance(); profiler_->CpuProfiler::StartCpuProfilerForFile(vm, ""); } diff --git a/ecmascript/interpreter/interpreter-inl.h b/ecmascript/interpreter/interpreter-inl.h index ab8b13dc..5215a2ca 100644 --- a/ecmascript/interpreter/interpreter-inl.h +++ b/ecmascript/interpreter/interpreter-inl.h @@ -668,11 +668,11 @@ NO_UB_SANITIZE void EcmaInterpreter::RunInternal(JSThread *thread, ConstantPool ObjectFactory *factory = ecmaVm->GetFactory(); constexpr size_t numOps = 0x100; - static thread_local std::array instDispatchTable { + static std::array instDispatchTable { #include "templates/instruction_dispatch.inl" }; - static thread_local std::array debugDispatchTable { + static std::array debugDispatchTable { #include "templates/debugger_instruction_dispatch.inl" }; diff --git a/ecmascript/mem/concurrent_marker.cpp b/ecmascript/mem/concurrent_marker.cpp index df40e0a5..0794788b 100644 --- a/ecmascript/mem/concurrent_marker.cpp +++ b/ecmascript/mem/concurrent_marker.cpp @@ -68,8 +68,7 @@ void ConcurrentMarker::Mark() void ConcurrentMarker::Finish() { - size_t aliveSize = 0; - workManager_->Finish(aliveSize); + workManager_->Finish(); } void ConcurrentMarker::ReMark() diff --git a/ecmascript/mem/full_gc.cpp b/ecmascript/mem/full_gc.cpp index 5360eab5..fc088ea5 100644 --- a/ecmascript/mem/full_gc.cpp +++ b/ecmascript/mem/full_gc.cpp @@ -141,7 +141,7 @@ void FullGC::Finish() { ECMA_BYTRACE_NAME(HITRACE_TAG_ARK, "FullGC::Finish"); heap_->Resume(FULL_GC); - workManager_->Finish(youngAndOldAliveSize_); + youngAndOldAliveSize_ = workManager_->Finish(); heap_->GetSweeper()->TryFillSweptRegion(); } } // namespace panda::ecmascript diff --git a/ecmascript/mem/linear_space.h b/ecmascript/mem/linear_space.h index ed98e7c7..ce2e6584 100644 --- a/ecmascript/mem/linear_space.h +++ b/ecmascript/mem/linear_space.h @@ -22,6 +22,8 @@ namespace panda::ecmascript { class LinearSpace : public Space { public: explicit LinearSpace(Heap *heap, MemSpaceType type, size_t initialCapacity, size_t maximumCapacity); + NO_COPY_SEMANTIC(LinearSpace); + NO_MOVE_SEMANTIC(LinearSpace); uintptr_t Allocate(size_t size, bool isPromoted = false); bool Expand(bool isPromoted); void Stop(); diff --git a/ecmascript/mem/mem_map_allocator.cpp b/ecmascript/mem/mem_map_allocator.cpp index 360450aa..a61173a7 100644 --- a/ecmascript/mem/mem_map_allocator.cpp +++ b/ecmascript/mem/mem_map_allocator.cpp @@ -107,9 +107,9 @@ void MemMapAllocator::AdapterSuitablePoolCapacity() { #ifdef PANDA_TARGET_WINDOWS MEMORYSTATUSEX status; - status.dwLength = sizeof(status); + status.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&status); - long physSize = status.ullTotalPhys; + DWORDLONG physSize = status.ullTotalPhys; #elif PANDA_TARGET_MACOS static constexpr int MIB_LENGTH = 2; int mib[2]; @@ -120,11 +120,11 @@ void MemMapAllocator::AdapterSuitablePoolCapacity() if (sysctl(mib, MIB_LENGTH, &size, &bufferLength, NULL, 0) != 0) { LOG(FATAL, RUNTIME) << "sysctl error"; } - long physSize = static_cast(size); + size_t physSize = static_cast(size); #else auto pages = sysconf(_SC_PHYS_PAGES); auto pageSize = sysconf(_SC_PAGE_SIZE); - long physSize = pages * pageSize; + size_t physSize = pages * pageSize; #endif capacity_ = std::max(physSize / PHY_SIZE_MULTIPLE, MIN_MEM_POOL_CAPACITY); LOG(INFO, RUNTIME) << "Auto adapter memory pool capacity:" << capacity_; diff --git a/ecmascript/mem/mem_map_allocator.h b/ecmascript/mem/mem_map_allocator.h index 77a0013d..36dd9f18 100644 --- a/ecmascript/mem/mem_map_allocator.h +++ b/ecmascript/mem/mem_map_allocator.h @@ -127,6 +127,7 @@ public: void InsertMemMap(MemMap memMap) { + os::memory::LockHolder lock(lock_); memMapVector_.emplace_back(memMap); } diff --git a/ecmascript/mem/partial_gc.cpp b/ecmascript/mem/partial_gc.cpp index 271a0baf..0361cbab 100644 --- a/ecmascript/mem/partial_gc.cpp +++ b/ecmascript/mem/partial_gc.cpp @@ -79,8 +79,7 @@ void PartialGC::Finish() auto marker = heap_->GetConcurrentMarker(); marker->Reset(false); } else { - size_t aliveSize = 0; - workManager_->Finish(aliveSize); + workManager_->Finish(); } if (heap_->IsFullMark()) { heap_->GetSweeper()->TryFillSweptRegion(); diff --git a/ecmascript/mem/work_manager.cpp b/ecmascript/mem/work_manager.cpp index eeaf7cdd..d88a9f1b 100644 --- a/ecmascript/mem/work_manager.cpp +++ b/ecmascript/mem/work_manager.cpp @@ -39,11 +39,13 @@ WorkManager::WorkManager(Heap *heap, uint32_t threadNum) WorkManager::~WorkManager() { + Finish(); for (uint32_t i = 0; i < threadNum_; i++) { continuousQueue_[i]->Destroy(); delete continuousQueue_[i]; continuousQueue_[i] = nullptr; } + heap_->GetNativeAreaAllocator()->FreeBuffer( reinterpret_cast(workSpace_)); } @@ -103,13 +105,16 @@ bool WorkManager::PopWorkNodeFromGlobal(uint32_t threadId) return workStack_.Pop(&works_[threadId].outNode_); } -void WorkManager::Finish(size_t &aliveSize) +size_t WorkManager::Finish() { + size_t aliveSize = 0; for (uint32_t i = 0; i < threadNum_; i++) { WorkNodeHolder &holder = works_[i]; - holder.weakQueue_->FinishMarking(continuousQueue_[i]); - delete holder.weakQueue_; - holder.weakQueue_ = nullptr; + if (holder.weakQueue_ != nullptr) { + holder.weakQueue_->FinishMarking(continuousQueue_[i]); + delete holder.weakQueue_; + holder.weakQueue_ = nullptr; + } if (holder.allocator_ != nullptr) { holder.allocator_->Finalize(); delete holder.allocator_; @@ -124,11 +129,12 @@ void WorkManager::Finish(size_t &aliveSize) agedSpaces_.back())); agedSpaces_.pop_back(); } + return aliveSize; } void WorkManager::Finish(size_t &aliveSize, size_t &promotedSize) { - Finish(aliveSize); + aliveSize = Finish(); for (uint32_t i = 0; i < threadNum_; i++) { WorkNodeHolder &holder = works_[i]; promotedSize += holder.promotedSize_; diff --git a/ecmascript/mem/work_manager.h b/ecmascript/mem/work_manager.h index c4365301..a2b08ca6 100644 --- a/ecmascript/mem/work_manager.h +++ b/ecmascript/mem/work_manager.h @@ -146,7 +146,7 @@ public: ~WorkManager(); void Initialize(TriggerGCType gcType, ParallelGCTaskPhase taskPhase); - void Finish(size_t &aliveSize); + size_t Finish(); void Finish(size_t &aliveSize, size_t &promotedSize); bool Push(uint32_t threadId, TaggedObject *object); -- Gitee From b16a444a9cd6754e73dee2cca89f73dc2ed616e3 Mon Sep 17 00:00:00 2001 From: zhangyukun8 Date: Wed, 15 Jun 2022 09:31:15 +0800 Subject: [PATCH 013/154] Fix newobjdynrange 1. add is heap object check 2. use assembler to deal with newobjreturn Signed-off-by: zhangyukun8 Change-Id: I9fc6d4b3e3b7af8a916d7059a8eff6a3c9a2086a --- ecmascript/compiler/bc_call_signature.h | 2 +- ecmascript/compiler/interpreter_stub.cpp | 54 +++------------- .../trampoline/aarch64/assembler_stubs.cpp | 63 ++++++++++++++++--- .../trampoline/x64/assembler_stubs_x64.cpp | 51 +++++++++++++-- 4 files changed, 110 insertions(+), 60 deletions(-) diff --git a/ecmascript/compiler/bc_call_signature.h b/ecmascript/compiler/bc_call_signature.h index 4a4245e6..69baeba1 100644 --- a/ecmascript/compiler/bc_call_signature.h +++ b/ecmascript/compiler/bc_call_signature.h @@ -181,7 +181,7 @@ namespace panda::ecmascript::kungfu { V(HandleOverflow) \ V(BCDebuggerEntry) \ V(BCDebuggerExceptionEntry) \ - V(NewObjectDynRangeReturn) \ + V(NewObjectDynRangeThrowException) \ V(InterpreterGetPropertyByName) \ #define INTERPRETER_IGNORED_BC_STUB_LIST(V) \ diff --git a/ecmascript/compiler/interpreter_stub.cpp b/ecmascript/compiler/interpreter_stub.cpp index db20829a..8822bc01 100644 --- a/ecmascript/compiler/interpreter_stub.cpp +++ b/ecmascript/compiler/interpreter_stub.cpp @@ -380,12 +380,12 @@ DECLARE_ASM_HANDLER(HandleNewObjDynRangePrefImm16V8) Branch(isBase, &ctorIsBase, &ctorNotBase); Bind(&ctorIsBase); { - Label notHole(env); + Label isHeapObject(env); Label checkJSObject(env); auto protoOrHclass = Load(VariableType::JS_ANY(), ctor, IntPtr(JSFunction::PROTO_OR_DYNCLASS_OFFSET)); - Branch(TaggedIsHole(protoOrHclass), &callRuntime, ¬Hole); - Bind(¬Hole); + Branch(TaggedIsHeapObject(protoOrHclass), &isHeapObject, &callRuntime); + Bind(&isHeapObject); Branch(IsJSHClass(protoOrHclass), &checkJSObject, &callRuntime); Bind(&checkJSObject); auto objectType = GetObjectType(protoOrHclass); @@ -5110,48 +5110,6 @@ DECLARE_ASM_HANDLER(HandleNewLexEnvWithNameDynPrefImm16Imm16) DISPATCH_WITH_ACC(PREF_IMM16_IMM16); } -DECLARE_ASM_HANDLER(NewObjectDynRangeReturn) -{ - auto env = GetEnvironment(); - DEFVARIABLE(varAcc, VariableType::JS_ANY(), acc); - - Label isHeapObject(env); - Label isEcmaObject(env); - Label notEcmaObject(env); - Label throwError(env); - Label returnObject(env); - Label dispatch(env); - - auto frame = GetFrame(sp); - auto newSp = Load(VariableType::NATIVE_POINTER(), frame, IntPtr(AsmInterpretedFrame::GetBaseOffset(env->IsArch32Bit()))); - - Branch(TaggedIsHeapObject(*varAcc), &isHeapObject, ¬EcmaObject); - Bind(&isHeapObject); - Branch(TaggedObjectIsEcmaObject(*varAcc), &dispatch, ¬EcmaObject); - Bind(¬EcmaObject); - { - // default acc is not undefined - auto constructor = GetFunctionFromFrame(frame); - Branch(IsBase(constructor), &returnObject, &throwError); - Bind(&throwError); - { - CallRuntime(glue, RTSTUB_ID(ThrowDerivedMustReturnException), {}); - DispatchLast(glue, newSp, pc, constpool, profileTypeInfo, acc, hotnessCounter); - } - Bind(&returnObject); - { - auto fp = Load(VariableType::JS_POINTER(), frame, - IntPtr(AsmInterpretedFrame::GetFpOffset(GetEnvironment()->IsArch32Bit()))); - auto thisObj = GetThisObjectFromFastNewFrame(fp); - varAcc = thisObj; - Jump(&dispatch); - } - } - Bind(&dispatch); - Dispatch(glue, newSp, pc, constpool, profileTypeInfo, *varAcc, hotnessCounter, - IntPtr(BytecodeInstruction::Size(BytecodeInstruction::Format::PREF_IMM16_V8))); -} - DECLARE_ASM_HANDLER(InterpreterGetPropertyByName) { auto env = GetEnvironment(); @@ -5188,6 +5146,12 @@ DECLARE_ASM_HANDLER(InterpreterGetPropertyByName) varAcc = *result; DISPATCH_WITH_ACC(PREF_ID32_V8); } + +DECLARE_ASM_HANDLER(NewObjectDynRangeThrowException) +{ + CallRuntime(glue, RTSTUB_ID(ThrowDerivedMustReturnException), {}); + DISPATCH_LAST(); +} #undef DECLARE_ASM_HANDLER #undef DISPATCH #undef DISPATCH_WITH_ACC diff --git a/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp b/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp index 1cd2cede..27ebc25f 100644 --- a/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp +++ b/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp @@ -1161,10 +1161,13 @@ void AssemblerStubs::ResumeRspAndDispatch(ExtendedAssembler *assembler) Register glueRegister = __ GlueRegister(); Register sp(FP); + Register rsp(SP); Register pc(X20); Register jumpSizeRegister(X25); + Register ret(X23); Register opcode(X6, W); + Register temp(X7); Register bcStub(X7); int64_t fpOffset = static_cast(AsmInterpretedFrame::GetFpOffset(false)) @@ -1173,7 +1176,8 @@ void AssemblerStubs::ResumeRspAndDispatch(ExtendedAssembler *assembler) - static_cast(AsmInterpretedFrame::GetSize(false)); ASSERT(fpOffset < 0); ASSERT(spOffset < 0); - __ Ldur(Register(SP), MemoryOperand(sp, fpOffset)); // resume rsp + __ Ldur(temp, MemoryOperand(sp, fpOffset)); + __ Mov(rsp, temp); // resume rsp Label newObjectDynRangeReturn; Label dispatch; @@ -1191,31 +1195,69 @@ void AssemblerStubs::ResumeRspAndDispatch(ExtendedAssembler *assembler) } auto jumpSize = kungfu::AssemblerModule::GetJumpSizeFromJSCallMode(JSCallMode::CALL_CONSTRUCTOR_WITH_ARGV); + Label getHiddenThis; Label notUndefined; __ Bind(&newObjectDynRangeReturn); { - Register ret(X0); __ Cmp(ret, Immediate(JSTaggedValue::VALUE_UNDEFINED)); __ B(Condition::NE, ¬Undefined); auto index = AsmInterpretedFrame::ReverseIndex::THIS_OBJECT_REVERSE_INDEX; auto thisOffset = index * 8; // 8: byte size ASSERT(thisOffset < 0); - __ Ldur(ret, MemoryOperand(sp, thisOffset)); // update acc + __ Bind(&getHiddenThis); + __ Ldur(ret, MemoryOperand(rsp, thisOffset)); // update acc __ Ldur(sp, MemoryOperand(sp, spOffset)); // update sp __ Add(pc, pc, Immediate(jumpSize)); __ Ldrb(opcode, MemoryOperand(pc, 0)); __ B(&dispatch); - - __ Bind(¬Undefined); - __ Mov(opcode, kungfu::BytecodeStubCSigns::ID_NewObjectDynRangeReturn); + } + __ Bind(¬Undefined); + { + Label notEcmaObject; + __ Mov(temp, Immediate(JSTaggedValue::TAG_HEAPOBJECT_BOOLEAN)); + __ And(temp, temp, ret); + __ Cmp(temp, Immediate(0)); + __ B(Condition::NE, ¬EcmaObject); + // acc is heap object + __ Ldr(temp, MemoryOperand(ret, 0)); // hclass + __ Ldr(temp, MemoryOperand(temp, JSHClass::BIT_FIELD_OFFSET)); + __ And(temp.W(), temp.W(), LogicalImmediate::Create(0xFF, RegWSize)); + __ Cmp(temp.W(), Immediate(static_cast(JSType::ECMA_OBJECT_END))); + __ B(Condition::HI, ¬EcmaObject); + __ Cmp(temp.W(), Immediate(static_cast(JSType::ECMA_OBJECT_BEGIN))); + __ B(Condition::LO, ¬EcmaObject); + // acc is ecma object + __ Ldur(sp, MemoryOperand(sp, spOffset)); // update sp + __ Add(pc, pc, Immediate(jumpSize)); + __ Ldrb(opcode, MemoryOperand(pc, 0)); __ B(&dispatch); + + __ Bind(¬EcmaObject); + { + int64_t constructorOffset = static_cast(AsmInterpretedFrame::GetFunctionOffset(false)) + - static_cast(AsmInterpretedFrame::GetSize(false)); + ASSERT(constructorOffset < 0); + __ Ldur(temp, MemoryOperand(sp, constructorOffset)); // load constructor + __ Ldr(temp, MemoryOperand(temp, JSFunction::BIT_FIELD_OFFSET)); + __ Lsr(temp.W(), temp.W(), JSFunction::FunctionKindBits::START_BIT); + __ And(temp.W(), temp.W(), + LogicalImmediate::Create((1LU << JSFunction::FunctionKindBits::SIZE) - 1, RegWSize)); + __ Cmp(temp.W(), Immediate(static_cast(FunctionKind::CLASS_CONSTRUCTOR))); + __ B(Condition::LS, &getHiddenThis); // constructor is base + // exception branch + { + __ Mov(opcode, kungfu::BytecodeStubCSigns::ID_NewObjectDynRangeThrowException); + __ Ldur(sp, MemoryOperand(sp, spOffset)); // update sp + __ B(&dispatch); + } + } } } void AssemblerStubs::ResumeRspAndReturn(ExtendedAssembler *assembler) { __ BindAssemblerStub(RTSTUB_ID(ResumeRspAndReturn)); - Register sp(SP); + Register rsp(SP); Register lr(X30); [[maybe_unused]] TempRegister1Scope scope1(assembler); @@ -1224,7 +1266,7 @@ void AssemblerStubs::ResumeRspAndReturn(ExtendedAssembler *assembler) - static_cast(AsmInterpretedFrame::GetSize(false)); ASSERT(offset < 0); __ Ldur(fpRegister, MemoryOperand(Register(FP), offset)); - __ Mov(sp, fpRegister); + __ Mov(rsp, fpRegister); // return { @@ -1257,7 +1299,10 @@ void AssemblerStubs::ResumeCaughtFrameAndDispatch(ExtendedAssembler *assembler) Label dispatch; __ Ldr(fp, MemoryOperand(glue, JSThread::GlueData::GetLastFpOffset(false))); __ Cmp(fp, Immediate(0)); - __ CMov(Register(SP), Register(SP), fp, Condition::EQ); + __ B(Condition::EQ, &dispatch); + // up frame + __ Mov(Register(SP), fp); + // fall through __ Bind(&dispatch); { __ Ldrb(opcode, MemoryOperand(pc, 0)); diff --git a/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp b/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp index 4681e17f..a461d213 100644 --- a/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp +++ b/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp @@ -1836,6 +1836,7 @@ void AssemblerStubsX64::ResumeRspAndDispatch(ExtendedAssembler *assembler) Register glueRegister = __ GlueRegister(); Register spRegister = rbp; Register pcRegister = r12; + Register ret = rsi; Register jumpSizeRegister = r8; Register frameStateBaseRegister = r11; @@ -1849,6 +1850,7 @@ void AssemblerStubsX64::ResumeRspAndDispatch(ExtendedAssembler *assembler) __ Movq(Operand(frameStateBaseRegister, AsmInterpretedFrame::GetBaseOffset(false)), spRegister); // update sp __ Addq(jumpSizeRegister, pcRegister); // newPc + Register temp = rax; Register opcodeRegister = rax; __ Movzbq(Operand(pcRegister, 0), opcodeRegister); Register bcStubRegister = r11; @@ -1858,13 +1860,15 @@ void AssemblerStubsX64::ResumeRspAndDispatch(ExtendedAssembler *assembler) auto jumpSize = kungfu::AssemblerModule::GetJumpSizeFromJSCallMode( JSCallMode::CALL_CONSTRUCTOR_WITH_ARGV); + Label getHiddenThis; Label notUndefined; __ Bind(&newObjectDynRangeReturn); - __ Cmpq(JSTaggedValue::Undefined().GetRawData(), rsi); + __ Cmpq(JSTaggedValue::Undefined().GetRawData(), ret); __ Jne(¬Undefined); auto index = AsmInterpretedFrame::ReverseIndex::THIS_OBJECT_REVERSE_INDEX; - __ Movq(Operand(rsp, index * 8), rsi); // 8: byte size, update acc + __ Bind(&getHiddenThis); + __ Movq(Operand(rsp, index * 8), ret); // 8: byte size, update acc __ Movq(Operand(frameStateBaseRegister, AsmInterpretedFrame::GetBaseOffset(false)), spRegister); // update sp __ Addq(jumpSize, pcRegister); // newPc __ Movzbq(Operand(pcRegister, 0), opcodeRegister); @@ -1873,10 +1877,47 @@ void AssemblerStubsX64::ResumeRspAndDispatch(ExtendedAssembler *assembler) __ Jmp(bcStubRegister); __ Bind(¬Undefined); - __ Movq(kungfu::BytecodeStubCSigns::ID_NewObjectDynRangeReturn, opcodeRegister); - __ Movq(Operand(glueRegister, opcodeRegister, Times8, JSThread::GlueData::GetBCStubEntriesOffset(false)), + { + Label notEcmaObject; + __ Movabs(JSTaggedValue::TAG_HEAPOBJECT_BOOLEAN, temp); + __ And(ret, temp); + __ Cmpq(0, temp); + __ Jne(¬EcmaObject); + // acc is heap object + __ Movq(Operand(ret, 0), temp); // hclass + __ Movl(Operand(temp, JSHClass::BIT_FIELD_OFFSET), temp); + __ Cmpb(static_cast(JSType::ECMA_OBJECT_END), temp); + __ Ja(¬EcmaObject); + __ Cmpb(static_cast(JSType::ECMA_OBJECT_BEGIN), temp); + __ Jb(¬EcmaObject); + // acc is ecma object + __ Movq(Operand(frameStateBaseRegister, AsmInterpretedFrame::GetBaseOffset(false)), spRegister); // update sp + __ Addq(jumpSize, pcRegister); // newPc + __ Movzbq(Operand(pcRegister, 0), opcodeRegister); + __ Movq(Operand(glueRegister, opcodeRegister, Times8, JSThread::GlueData::GetBCStubEntriesOffset(false)), bcStubRegister); - __ Jmp(bcStubRegister); + __ Jmp(bcStubRegister); + + __ Bind(¬EcmaObject); + { + // load constructor + __ Movq(Operand(frameStateBaseRegister, AsmInterpretedFrame::GetFunctionOffset(false)), temp); + __ Movl(Operand(temp, JSFunction::BIT_FIELD_OFFSET), temp); + __ Shr(JSFunction::FunctionKindBits::START_BIT, temp); + __ Andl((1LU << JSFunction::FunctionKindBits::SIZE) - 1, temp); + __ Cmpl(static_cast(FunctionKind::CLASS_CONSTRUCTOR), temp); + __ Jbe(&getHiddenThis); // constructor is base + // fall through + } + // exception branch + { + __ Movq(Operand(frameStateBaseRegister, AsmInterpretedFrame::GetBaseOffset(false)), spRegister); + __ Movq(kungfu::BytecodeStubCSigns::ID_NewObjectDynRangeThrowException, opcodeRegister); + __ Movq(Operand(glueRegister, opcodeRegister, Times8, JSThread::GlueData::GetBCStubEntriesOffset(false)), + bcStubRegister); + __ Jmp(bcStubRegister); + } + } } // c++ calling convention -- Gitee From 0226887986ff31f9a42dea8585c25fafd485865e Mon Sep 17 00:00:00 2001 From: lifansheng Date: Tue, 14 Jun 2022 16:35:53 +0800 Subject: [PATCH 014/154] issue:I5C5EG modify newobjDynrange to remove the flag "IsBuiltinsConstructor" Signed-off-by: lifansheng Change-Id: Ic94b8ba77a0ebaf121f2942238435a9da5917287 --- ecmascript/builtins.cpp | 11 -------- ecmascript/compiler/stub-inl.h | 27 ------------------ ecmascript/compiler/stub.h | 2 -- ecmascript/interpreter/interpreter-inl.h | 4 +-- .../interpreter/slow_runtime_helper.cpp | 15 ++-------- ecmascript/js_function.cpp | 6 ++-- ecmascript/js_function.h | 8 ++++-- ecmascript/js_function_kind.h | 6 ++-- ecmascript/js_hclass.h | 28 ++++++------------- ecmascript/js_object-inl.h | 10 ------- ecmascript/js_object.h | 2 -- 11 files changed, 23 insertions(+), 96 deletions(-) diff --git a/ecmascript/builtins.cpp b/ecmascript/builtins.cpp index 38242dcb..a56cb2aa 100644 --- a/ecmascript/builtins.cpp +++ b/ecmascript/builtins.cpp @@ -281,7 +281,6 @@ void Builtins::Initialize(const JSHandle &env, JSThread *thread) // Object = new Function() JSHandle objectFunction( NewBuiltinConstructor(env, objFuncPrototype, Object::ObjectConstructor, "Object", FunctionLength::ONE)); - objectFunction.GetObject()->SetBuiltinsCtorMode(); objectFunction.GetObject()->SetFunctionPrototype(thread_, objFuncDynclass.GetTaggedValue()); // initialize object method. env->SetObjectFunction(thread_, objectFunction); @@ -439,8 +438,6 @@ void Builtins::InitializeFunction(const JSHandle &env, const JSHandle JSHandle funcFuncIntanceDynclass = factory_->NewEcmaDynClass(JSFunction::SIZE, JSType::JS_FUNCTION, funcFuncPrototypeValue); funcFuncIntanceDynclass->SetConstructor(true); - JSHandle function = JSHandle::Cast(factory_->NewJSObjectWithInit(funcFuncIntanceDynclass)); - function->SetBuiltinsCtorMode(); // Function = new Function() (forbidden use NewBuiltinConstructor) JSHandle funcFunc = @@ -466,9 +463,6 @@ void Builtins::InitializeFunction(const JSHandle &env, const JSHandle JSHandle constructorFunctionClass = factory_->NewEcmaDynClass(JSFunction::SIZE, JSType::JS_FUNCTION, env->GetFunctionPrototype()); constructorFunctionClass->SetConstructor(true); - JSHandle functionConstructor = - JSHandle::Cast(factory_->NewJSObjectWithInit(constructorFunctionClass)); - functionConstructor->SetBuiltinsCtorMode(); env->SetConstructorFunctionClass(thread_, constructorFunctionClass); StrictModeForbiddenAccessCallerArguments(env, funcFuncPrototypeObj); @@ -1015,8 +1009,6 @@ void Builtins::InitializeAllTypeError(const JSHandle &env, const JSHa JSHandle nativeErrorFuncClass = factory_->NewEcmaDynClass(JSFunction::SIZE, JSType::JS_FUNCTION, env->GetErrorFunction()); nativeErrorFuncClass->SetConstructor(true); - JSHandle function = JSHandle::Cast(factory_->NewJSObjectWithInit(nativeErrorFuncClass)); - function->SetBuiltinsCtorMode(); env->SetNativeErrorFunctionClass(thread_, nativeErrorFuncClass); JSHandle errorNativeFuncInstanceDynclass = @@ -2026,9 +2018,6 @@ void Builtins::InitializeTypedArray(const JSHandle &env, const JSHand JSHandle specificTypedArrayFuncClass = factory_->NewEcmaDynClass(JSFunction::SIZE, JSType::JS_FUNCTION, env->GetTypedArrayFunction()); specificTypedArrayFuncClass->SetConstructor(true); - JSHandle function = - JSHandle::Cast(factory_->NewJSObjectWithInit(specificTypedArrayFuncClass)); - function->SetBuiltinsCtorMode(); env->SetSpecificTypedArrayFunctionClass(thread_, specificTypedArrayFuncClass); InitializeInt8Array(env, typedArrFuncInstanceDynclass); diff --git a/ecmascript/compiler/stub-inl.h b/ecmascript/compiler/stub-inl.h index e8672f88..b16904f9 100644 --- a/ecmascript/compiler/stub-inl.h +++ b/ecmascript/compiler/stub-inl.h @@ -999,20 +999,6 @@ inline GateRef Stub::IsDictionaryElement(GateRef hClass) Int32(0)); } -inline GateRef Stub::NotBuiltinsConstructor(GateRef object) -{ - GateRef hclass = LoadHClass(object); - GateRef bitfieldOffset = IntPtr(JSHClass::BIT_FIELD_OFFSET); - - GateRef bitfield = Load(VariableType::INT32(), hclass, bitfieldOffset); - // decode - return Int32Equal( - Int32And( - Int32LSR(bitfield, Int32(JSHClass::BuiltinsCtorBit::START_BIT)), - Int32((1LU << JSHClass::BuiltinsCtorBit::SIZE) - 1)), - Int32(0)); -} - inline GateRef Stub::IsClassConstructorFromBitField(GateRef bitfield) { // decode @@ -1119,19 +1105,6 @@ inline GateRef Stub::IsConstructor(GateRef object) Int32(0)); } -inline GateRef Stub::IsBuiltinsConstructor(GateRef object) -{ - GateRef hClass = LoadHClass(object); - GateRef bitfieldOffset = IntPtr(JSHClass::BIT_FIELD_OFFSET); - - GateRef bitfield = Load(VariableType::INT32(), hClass, bitfieldOffset); - // decode - return Int32NotEqual( - Int32And(Int32LSR(bitfield, Int32(JSHClass::BuiltinsCtorBit::START_BIT)), - Int32((1LU << JSHClass::BuiltinsCtorBit::SIZE) - 1)), - Int32(0)); -} - inline GateRef Stub::IsBase(GateRef func) { GateRef bitfieldOffset = IntPtr(JSFunction::BIT_FIELD_OFFSET); diff --git a/ecmascript/compiler/stub.h b/ecmascript/compiler/stub.h index 33678217..89628375 100644 --- a/ecmascript/compiler/stub.h +++ b/ecmascript/compiler/stub.h @@ -240,7 +240,6 @@ public: GateRef IsDictionaryMode(GateRef object); GateRef IsDictionaryModeByHClass(GateRef hClass); GateRef IsDictionaryElement(GateRef hClass); - GateRef NotBuiltinsConstructor(GateRef object); GateRef IsClassConstructorFromBitField(GateRef bitfield); GateRef IsClassConstructor(GateRef object); GateRef IsClassPrototype(GateRef object); @@ -253,7 +252,6 @@ public: GateRef IsJsProxy(GateRef obj); GateRef IsJSFunctionBase(GateRef obj); GateRef IsConstructor(GateRef object); - GateRef IsBuiltinsConstructor(GateRef object); GateRef IsBase(GateRef func); GateRef IsJsArray(GateRef obj); GateRef IsJSObject(GateRef obj); diff --git a/ecmascript/interpreter/interpreter-inl.h b/ecmascript/interpreter/interpreter-inl.h index ab8b13dc..d948d00f 100644 --- a/ecmascript/interpreter/interpreter-inl.h +++ b/ecmascript/interpreter/interpreter-inl.h @@ -1933,7 +1933,7 @@ NO_UB_SANITIZE void EcmaInterpreter::RunInternal(JSThread *thread, ConstantPool if (ctor.IsJSFunction() && ctor.IsConstructor()) { JSFunction *ctorFunc = JSFunction::Cast(ctor.GetTaggedObject()); JSMethod *ctorMethod = ctorFunc->GetMethod(); - if (ctorFunc->IsBuiltinsConstructor()) { + if (ctorFunc->IsBuiltinConstructor()) { ASSERT(ctorMethod->GetNumVregsWithCallField() == 0); size_t frameSize = INTERPRETER_FRAME_STATE_SIZE + numArgs + 1; // +1 for this // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) @@ -3472,7 +3472,7 @@ NO_UB_SANITIZE void EcmaInterpreter::RunInternal(JSThread *thread, ConstantPool if (superCtor.IsJSFunction() && superCtor.IsConstructor() && !newTarget.IsUndefined()) { JSFunction *superCtorFunc = JSFunction::Cast(superCtor.GetTaggedObject()); JSMethod *superCtorMethod = superCtorFunc->GetMethod(); - if (superCtorFunc->IsBuiltinsConstructor()) { + if (superCtorFunc->IsBuiltinConstructor()) { ASSERT(superCtorMethod->GetNumVregsWithCallField() == 0); size_t frameSize = INTERPRETER_FRAME_STATE_SIZE + range + NUM_MANDATORY_JSFUNC_ARGS; // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) diff --git a/ecmascript/interpreter/slow_runtime_helper.cpp b/ecmascript/interpreter/slow_runtime_helper.cpp index 609c7823..e516baca 100644 --- a/ecmascript/interpreter/slow_runtime_helper.cpp +++ b/ecmascript/interpreter/slow_runtime_helper.cpp @@ -73,17 +73,6 @@ JSTaggedValue SlowRuntimeHelper::NewObject(EcmaRuntimeCallInfo *info) THROW_TYPE_ERROR_AND_RETURN(thread, "Constructed NonConstructable", JSTaggedValue::Exception()); } - JSHandle jsFunc = JSHandle::Cast(func); - ASSERT(jsFunc->GetCallTarget() != nullptr); - ASSERT(JSFunction::Cast(info->GetNewTarget()->GetTaggedObject())->GetCallTarget() != nullptr); - - if (jsFunc->GetCallTarget()->IsNativeWithCallField()) { - if (jsFunc->IsBuiltinsConstructor()) { - return EcmaInterpreter::Execute(info); - } - THROW_TYPE_ERROR_AND_RETURN(thread, "Constructed NonConstructable", JSTaggedValue::Exception()); - } - JSTaggedValue result = JSFunction::ConstructInternal(info); RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread); return result; @@ -116,7 +105,7 @@ JSTaggedValue ConstructGeneric(JSThread *thread, JSHandle ctor, JSHa } JSHandle obj(thread, JSTaggedValue::Undefined()); - if (!ctor->IsBuiltinsConstructor() && ctor->IsBase()) { + if (ctor->IsBase()) { ObjectFactory *factory = thread->GetEcmaVM()->GetFactory(); obj = JSHandle(factory->NewJSObjectByConstructor(ctor, newTgt)); } @@ -155,7 +144,7 @@ JSTaggedValue ConstructGeneric(JSThread *thread, JSHandle ctor, JSHa JSTaggedValue resultValue = EcmaInterpreter::Execute(&info); RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread); // 9.3.2 [[Construct]] (argumentsList, newTarget) - if (ctor->IsBuiltinsConstructor() || resultValue.IsECMAObject()) { + if (resultValue.IsECMAObject()) { return resultValue; } diff --git a/ecmascript/js_function.cpp b/ecmascript/js_function.cpp index 8f3db64a..402a8600 100644 --- a/ecmascript/js_function.cpp +++ b/ecmascript/js_function.cpp @@ -264,7 +264,7 @@ JSTaggedValue JSFunction::Call(EcmaRuntimeCallInfo *info) } auto *hclass = func->GetTaggedObject()->GetClass(); - if (!hclass->IsBuiltinsCtor() && hclass->IsClassConstructor()) { + if (hclass->IsClassConstructor()) { THROW_TYPE_ERROR_AND_RETURN(thread, "class constructor cannot call", JSTaggedValue::Exception()); } return EcmaInterpreter::Execute(info); @@ -320,7 +320,7 @@ JSTaggedValue JSFunction::ConstructInternal(EcmaRuntimeCallInfo *info) } JSHandle obj(thread, JSTaggedValue::Undefined()); - if (!func->IsBuiltinsConstructor() && func->IsBase()) { + if (func->IsBase()) { ObjectFactory *factory = thread->GetEcmaVM()->GetFactory(); obj = JSHandle(factory->NewJSObjectByConstructor(func, newTarget)); } @@ -329,7 +329,7 @@ JSTaggedValue JSFunction::ConstructInternal(EcmaRuntimeCallInfo *info) JSTaggedValue resultValue = EcmaInterpreter::Execute(info); RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread); // 9.3.2 [[Construct]] (argumentsList, newTarget) - if (func->IsBuiltinsConstructor() || resultValue.IsECMAObject()) { + if (resultValue.IsECMAObject()) { return resultValue; } diff --git a/ecmascript/js_function.h b/ecmascript/js_function.h index d9c25f82..83d81f9d 100644 --- a/ecmascript/js_function.h +++ b/ecmascript/js_function.h @@ -161,17 +161,19 @@ public: inline static bool IsConstructorKind(FunctionKind kind) { - return (kind >= FunctionKind::BUILTIN_PROXY_CONSTRUCTOR) && (kind <= FunctionKind::DERIVED_CONSTRUCTOR); + return (kind >= FunctionKind::BASE_CONSTRUCTOR) && (kind <= FunctionKind::DERIVED_CONSTRUCTOR); } - inline static bool IsBuiltinConstructor(FunctionKind kind) + inline bool IsBuiltinConstructor() { + FunctionKind kind = GetFunctionKind(); return kind >= FunctionKind::BUILTIN_PROXY_CONSTRUCTOR && kind <= FunctionKind::BUILTIN_CONSTRUCTOR; } inline static bool HasPrototype(FunctionKind kind) { - return kind >= FunctionKind::BUILTIN_CONSTRUCTOR && kind <= FunctionKind::GENERATOR_FUNCTION; + return (kind >= FunctionKind::BASE_CONSTRUCTOR) && (kind <= FunctionKind::GENERATOR_FUNCTION) + && (kind != FunctionKind::BUILTIN_PROXY_CONSTRUCTOR); } inline static bool HasAccessor(FunctionKind kind) diff --git a/ecmascript/js_function_kind.h b/ecmascript/js_function_kind.h index bfb424bb..4dd64b8f 100644 --- a/ecmascript/js_function_kind.h +++ b/ecmascript/js_function_kind.h @@ -28,9 +28,6 @@ enum class FunctionKind : uint8_t { // END arrow functions ASYNC_FUNCTION, // END async functions - // BEGIN constructable functions - BUILTIN_PROXY_CONSTRUCTOR, - BUILTIN_CONSTRUCTOR, // BEGIN base constructors BASE_CONSTRUCTOR, // BEGIN default constructors @@ -38,6 +35,9 @@ enum class FunctionKind : uint8_t { // BEGIN class constructors CLASS_CONSTRUCTOR, // END base constructors + // BEGIN constructable functions + BUILTIN_PROXY_CONSTRUCTOR, + BUILTIN_CONSTRUCTOR, // END default constructors DERIVED_CONSTRUCTOR, // END class constructors diff --git a/ecmascript/js_hclass.h b/ecmascript/js_hclass.h index 9bf24151..39f3a869 100644 --- a/ecmascript/js_hclass.h +++ b/ecmascript/js_hclass.h @@ -243,17 +243,16 @@ public: using ObjectTypeBits = BitField; // 7 using CallableBit = ObjectTypeBits::NextFlag; using ConstructorBit = CallableBit::NextFlag; // 9 - using BuiltinsCtorBit = ConstructorBit::NextFlag; // 10 - using ExtensibleBit = BuiltinsCtorBit::NextFlag; + using ExtensibleBit = ConstructorBit::NextFlag; using IsPrototypeBit = ExtensibleBit::NextFlag; using ElementRepresentationBits = IsPrototypeBit::NextField; // 3 means next 3 bit - using DictionaryElementBits = ElementRepresentationBits::NextFlag; // 16 - using IsDictionaryBit = DictionaryElementBits::NextFlag; // 17 - using IsStableElementsBit = IsDictionaryBit::NextFlag; // 18 - using HasConstructorBits = IsStableElementsBit::NextFlag; // 19 - using IsLiteralBit = HasConstructorBits::NextFlag; // 20 - using ClassConstructorBit = IsLiteralBit::NextFlag; // 21 - using ClassPrototypeBit = ClassConstructorBit::NextFlag; // 22 + using DictionaryElementBits = ElementRepresentationBits::NextFlag; // 15 + using IsDictionaryBit = DictionaryElementBits::NextFlag; // 16 + using IsStableElementsBit = IsDictionaryBit::NextFlag; // 17 + using HasConstructorBits = IsStableElementsBit::NextFlag; // 18 + using IsLiteralBit = HasConstructorBits::NextFlag; // 19 + using ClassConstructorBit = IsLiteralBit::NextFlag; // 20 + using ClassPrototypeBit = ClassConstructorBit::NextFlag; // 21 static constexpr int DEFAULT_CAPACITY_OF_IN_OBJECTS = 4; static constexpr int MAX_CAPACITY_OF_OUT_OBJECTS = @@ -346,11 +345,6 @@ public: ConstructorBit::Set(flag, GetBitFieldAddr()); } - inline void SetBuiltinsCtor(bool flag) const - { - BuiltinsCtorBit::Set(flag, GetBitFieldAddr()); - } - inline void SetExtensible(bool flag) const { ExtensibleBit::Set(flag, GetBitFieldAddr()); @@ -895,12 +889,6 @@ public: return ConstructorBit::Decode(bits); } - inline bool IsBuiltinsCtor() const - { - uint32_t bits = GetBitField(); - return BuiltinsCtorBit::Decode(bits); - } - inline bool IsExtensible() const { uint32_t bits = GetBitField(); diff --git a/ecmascript/js_object-inl.h b/ecmascript/js_object-inl.h index aceba78b..9782a2ad 100644 --- a/ecmascript/js_object-inl.h +++ b/ecmascript/js_object-inl.h @@ -23,16 +23,6 @@ #include "ecmascript/tagged_array-inl.h" namespace panda::ecmascript { -inline void ECMAObject::SetBuiltinsCtorMode() -{ - GetClass()->SetBuiltinsCtor(true); -} - -inline bool ECMAObject::IsBuiltinsConstructor() const -{ - return GetClass()->IsBuiltinsCtor(); -} - inline void ECMAObject::SetCallable(bool flag) { GetClass()->SetCallable(flag); diff --git a/ecmascript/js_object.h b/ecmascript/js_object.h index ffe8c978..ccc13160 100644 --- a/ecmascript/js_object.h +++ b/ecmascript/js_object.h @@ -326,8 +326,6 @@ class ECMAObject : public TaggedObject { public: CAST_CHECK(ECMAObject, IsECMAObject); - void SetBuiltinsCtorMode(); - bool IsBuiltinsConstructor() const; void SetCallable(bool flag); bool IsCallable() const; JSMethod *GetCallTarget() const; -- Gitee From 8d7114840708bb0675ed474399375b6fd57dc108 Mon Sep 17 00:00:00 2001 From: wengchangcheng Date: Wed, 15 Jun 2022 17:58:33 +0800 Subject: [PATCH 015/154] Descriptor: fix device UT error details: add resource file for debugger testcases issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5CGVW Signed-off-by: wengchangcheng Change-Id: Iee27e961411cebed0f843f6557dde7f05f4b5248 --- test/resource/js_runtime/ohos_test.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/resource/js_runtime/ohos_test.xml b/test/resource/js_runtime/ohos_test.xml index 2f36dbc6..5fbbb608 100755 --- a/test/resource/js_runtime/ohos_test.xml +++ b/test/resource/js_runtime/ohos_test.xml @@ -17,6 +17,8 @@ -- Gitee From 5d635bd956875badd84d89968fb743ea626222cc Mon Sep 17 00:00:00 2001 From: hjzhangcm Date: Wed, 15 Jun 2022 18:34:09 +0800 Subject: [PATCH 016/154] fix test case bug issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CH61 Signed-off-by: hjzhangcm --- ecmascript/tests/object_operator_test.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ecmascript/tests/object_operator_test.cpp b/ecmascript/tests/object_operator_test.cpp index 5fad3cd8..9c620f1a 100644 --- a/ecmascript/tests/object_operator_test.cpp +++ b/ecmascript/tests/object_operator_test.cpp @@ -240,12 +240,13 @@ JSTaggedValue TestDefinedSetter([[maybe_unused]] EcmaRuntimeCallInfo *argv) return JSTaggedValue(12); } -JSTaggedValue TestBoolSetter([[maybe_unused]] EcmaRuntimeCallInfo *argv) +bool TestBoolSetter([[maybe_unused]] JSThread *thread, + [[maybe_unused]] JSHandle &jsObject, + [[maybe_unused]] JSHandle &value, + [[maybe_unused]] bool success) { - // 12 : test case - return JSTaggedValue(JSTaggedValue::True()); + return true; } - static JSFunction *JSObjectTestCreate(JSThread *thread) { JSHandle globalEnv = thread->GetEcmaVM()->GetGlobalEnv(); -- Gitee From bd650c241fc3f16fcd28de9579b9857b597633b9 Mon Sep 17 00:00:00 2001 From: wengchangcheng Date: Sat, 11 Jun 2022 21:36:43 +0800 Subject: [PATCH 017/154] Descriptor: debugger refactor of independent js_runtime [ part-3 ] details: modify Params::Create to cJson issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5BUI2 Signed-off-by: wengchangcheng Change-Id: I7a89ef24a0c8e999fc76429cda34f5f0e05f4946 --- ecmascript/tooling/agent/debugger_impl.cpp | 24 +- .../tooling/agent/heapprofiler_impl.cpp | 20 +- ecmascript/tooling/agent/profiler_impl.cpp | 6 +- ecmascript/tooling/agent/runtime_impl.cpp | 6 +- ecmascript/tooling/base/pt_json.cpp | 11 + ecmascript/tooling/base/pt_json.h | 1 + ecmascript/tooling/base/pt_params.cpp | 1083 +++++++---------- ecmascript/tooling/base/pt_params.h | 69 +- ecmascript/tooling/base/pt_types.cpp | 258 +--- ecmascript/tooling/base/pt_types.h | 70 +- .../tooling/test/debugger_params_test.cpp | 162 +-- 11 files changed, 608 insertions(+), 1102 deletions(-) diff --git a/ecmascript/tooling/agent/debugger_impl.cpp b/ecmascript/tooling/agent/debugger_impl.cpp index d46f1461..a6927a4e 100644 --- a/ecmascript/tooling/agent/debugger_impl.cpp +++ b/ecmascript/tooling/agent/debugger_impl.cpp @@ -286,8 +286,7 @@ void DebuggerImpl::DispatcherImpl::Disable(const DispatchRequest &request) void DebuggerImpl::DispatcherImpl::EvaluateOnCallFrame(const DispatchRequest &request) { - std::unique_ptr params = - EvaluateOnCallFrameParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = EvaluateOnCallFrameParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -301,8 +300,7 @@ void DebuggerImpl::DispatcherImpl::EvaluateOnCallFrame(const DispatchRequest &re void DebuggerImpl::DispatcherImpl::GetPossibleBreakpoints(const DispatchRequest &request) { - std::unique_ptr params = - GetPossibleBreakpointsParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = GetPossibleBreakpointsParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -315,8 +313,7 @@ void DebuggerImpl::DispatcherImpl::GetPossibleBreakpoints(const DispatchRequest void DebuggerImpl::DispatcherImpl::GetScriptSource(const DispatchRequest &request) { - std::unique_ptr params = - GetScriptSourceParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = GetScriptSourceParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -335,8 +332,7 @@ void DebuggerImpl::DispatcherImpl::Pause(const DispatchRequest &request) void DebuggerImpl::DispatcherImpl::RemoveBreakpoint(const DispatchRequest &request) { - std::unique_ptr params = - RemoveBreakpointParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = RemoveBreakpointParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -347,7 +343,7 @@ void DebuggerImpl::DispatcherImpl::RemoveBreakpoint(const DispatchRequest &reque void DebuggerImpl::DispatcherImpl::Resume(const DispatchRequest &request) { - std::unique_ptr params = ResumeParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = ResumeParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -364,8 +360,7 @@ void DebuggerImpl::DispatcherImpl::SetAsyncCallStackDepth(const DispatchRequest void DebuggerImpl::DispatcherImpl::SetBreakpointByUrl(const DispatchRequest &request) { - std::unique_ptr params = - SetBreakpointByUrlParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = SetBreakpointByUrlParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -380,8 +375,7 @@ void DebuggerImpl::DispatcherImpl::SetBreakpointByUrl(const DispatchRequest &req void DebuggerImpl::DispatcherImpl::SetPauseOnExceptions(const DispatchRequest &request) { - std::unique_ptr params = - SetPauseOnExceptionsParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = SetPauseOnExceptionsParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -393,7 +387,7 @@ void DebuggerImpl::DispatcherImpl::SetPauseOnExceptions(const DispatchRequest &r void DebuggerImpl::DispatcherImpl::StepInto(const DispatchRequest &request) { - std::unique_ptr params = StepIntoParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = StepIntoParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -410,7 +404,7 @@ void DebuggerImpl::DispatcherImpl::StepOut(const DispatchRequest &request) void DebuggerImpl::DispatcherImpl::StepOver(const DispatchRequest &request) { - std::unique_ptr params = StepOverParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = StepOverParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; diff --git a/ecmascript/tooling/agent/heapprofiler_impl.cpp b/ecmascript/tooling/agent/heapprofiler_impl.cpp index b88e8272..cd99f1e8 100644 --- a/ecmascript/tooling/agent/heapprofiler_impl.cpp +++ b/ecmascript/tooling/agent/heapprofiler_impl.cpp @@ -45,8 +45,7 @@ void HeapProfilerImpl::DispatcherImpl::Dispatch(const DispatchRequest &request) void HeapProfilerImpl::DispatcherImpl::AddInspectedHeapObject(const DispatchRequest &request) { - std::unique_ptr params = - AddInspectedHeapObjectParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = AddInspectedHeapObjectParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -75,8 +74,7 @@ void HeapProfilerImpl::DispatcherImpl::Disable(const DispatchRequest &request) void HeapProfilerImpl::DispatcherImpl::GetHeapObjectId(const DispatchRequest &request) { - std::unique_ptr params = - GetHeapObjectIdParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = GetHeapObjectIdParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -90,8 +88,7 @@ void HeapProfilerImpl::DispatcherImpl::GetHeapObjectId(const DispatchRequest &re void HeapProfilerImpl::DispatcherImpl::GetObjectByHeapObjectId(const DispatchRequest &request) { - std::unique_ptr params = - GetObjectByHeapObjectIdParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = GetObjectByHeapObjectIdParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -114,8 +111,7 @@ void HeapProfilerImpl::DispatcherImpl::GetSamplingProfile(const DispatchRequest void HeapProfilerImpl::DispatcherImpl::StartSampling(const DispatchRequest &request) { - std::unique_ptr params = - StartSamplingParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = StartSamplingParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -127,7 +123,7 @@ void HeapProfilerImpl::DispatcherImpl::StartSampling(const DispatchRequest &requ void HeapProfilerImpl::DispatcherImpl::StartTrackingHeapObjects(const DispatchRequest &request) { std::unique_ptr params = - StartTrackingHeapObjectsParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + StartTrackingHeapObjectsParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -147,8 +143,7 @@ void HeapProfilerImpl::DispatcherImpl::StopSampling(const DispatchRequest &reque void HeapProfilerImpl::DispatcherImpl::StopTrackingHeapObjects(const DispatchRequest &request) { - std::unique_ptr params = - StopTrackingHeapObjectsParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = StopTrackingHeapObjectsParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -159,8 +154,7 @@ void HeapProfilerImpl::DispatcherImpl::StopTrackingHeapObjects(const DispatchReq void HeapProfilerImpl::DispatcherImpl::TakeHeapSnapshot(const DispatchRequest &request) { - std::unique_ptr params = - StopTrackingHeapObjectsParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = StopTrackingHeapObjectsParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; diff --git a/ecmascript/tooling/agent/profiler_impl.cpp b/ecmascript/tooling/agent/profiler_impl.cpp index 022030a0..78f59f21 100644 --- a/ecmascript/tooling/agent/profiler_impl.cpp +++ b/ecmascript/tooling/agent/profiler_impl.cpp @@ -76,8 +76,7 @@ void ProfilerImpl::DispatcherImpl::Stop(const DispatchRequest &request) void ProfilerImpl::DispatcherImpl::SetSamplingInterval(const DispatchRequest &request) { - std::unique_ptr params = - SetSamplingIntervalParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = SetSamplingIntervalParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -106,8 +105,7 @@ void ProfilerImpl::DispatcherImpl::TakePreciseCoverage(const DispatchRequest &re void ProfilerImpl::DispatcherImpl::StartPreciseCoverage(const DispatchRequest &request) { - std::unique_ptr params = - StartPreciseCoverageParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = StartPreciseCoverageParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; diff --git a/ecmascript/tooling/agent/runtime_impl.cpp b/ecmascript/tooling/agent/runtime_impl.cpp index ded0e698..885b3ba8 100644 --- a/ecmascript/tooling/agent/runtime_impl.cpp +++ b/ecmascript/tooling/agent/runtime_impl.cpp @@ -65,8 +65,7 @@ void RuntimeImpl::DispatcherImpl::RunIfWaitingForDebugger(const DispatchRequest void RuntimeImpl::DispatcherImpl::GetProperties(const DispatchRequest &request) { - std::unique_ptr params = - GetPropertiesParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = GetPropertiesParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; @@ -90,8 +89,7 @@ void RuntimeImpl::DispatcherImpl::GetProperties(const DispatchRequest &request) void RuntimeImpl::DispatcherImpl::CallFunctionOn(const DispatchRequest &request) { - std::unique_ptr params = - CallFunctionOnParams::Create(request.GetEcmaVM(), request.GetParamsObj()); + std::unique_ptr params = CallFunctionOnParams::Create(request.GetParams()); if (params == nullptr) { SendResponse(request, DispatchResponse::Fail("wrong params")); return; diff --git a/ecmascript/tooling/base/pt_json.cpp b/ecmascript/tooling/base/pt_json.cpp index 967206a9..2943e98b 100644 --- a/ecmascript/tooling/base/pt_json.cpp +++ b/ecmascript/tooling/base/pt_json.cpp @@ -418,4 +418,15 @@ Result PtJson::GetArray(const char *key, std::unique_ptr *value) const *value = std::make_unique(item); return Result::SUCCESS; } + +Result PtJson::GetAny(const char *key, std::unique_ptr *value) const +{ + cJSON *item = cJSON_GetObjectItem(object_, key); + if (item == nullptr) { + return Result::NOT_EXIST; + } + + *value = std::make_unique(item); + return Result::SUCCESS; +} } // namespace panda::ecmascript diff --git a/ecmascript/tooling/base/pt_json.h b/ecmascript/tooling/base/pt_json.h index d38eb3cd..88f6cc15 100644 --- a/ecmascript/tooling/base/pt_json.h +++ b/ecmascript/tooling/base/pt_json.h @@ -99,6 +99,7 @@ public: Result GetString(const char *key, std::string *value) const; Result GetObject(const char *key, std::unique_ptr *value) const; Result GetArray(const char *key, std::unique_ptr *value) const; + Result GetAny(const char *key, std::unique_ptr *value) const; private: cJSON *object_ = nullptr; diff --git a/ecmascript/tooling/base/pt_params.cpp b/ecmascript/tooling/base/pt_params.cpp index 2118cc12..1ebfe9e3 100644 --- a/ecmascript/tooling/base/pt_params.cpp +++ b/ecmascript/tooling/base/pt_params.cpp @@ -16,43 +16,16 @@ #include "ecmascript/tooling/base/pt_params.h" namespace panda::ecmascript::tooling { -std::unique_ptr EnableParams::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "EnableParams::Create params is nullptr"; - return nullptr; - } - std::string error; - auto paramsObject = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "maxScriptsCacheSize"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - paramsObject->maxScriptsCacheSize_ = Local(result)->Value(); - } else { - error += "'maxScriptsCacheSize' should be a Number;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "EnableParams::Create " << error; - return nullptr; - } - - return paramsObject; -} - std::unique_ptr EnableParams::Create(const PtJson ¶ms) { auto paramsObject = std::make_unique(); std::string error; Result ret; - double result; - ret = params.GetDouble("maxScriptsCacheSize", &result); + double maxScriptsCacheSize; + ret = params.GetDouble("maxScriptsCacheSize", &maxScriptsCacheSize); if (ret == Result::SUCCESS) { - paramsObject->maxScriptsCacheSize_ = result; + paramsObject->maxScriptsCacheSize_ = maxScriptsCacheSize; } else if (ret == Result::TYPE_ERROR) { // optional value error += "Unknown 'maxScriptsCacheSize';"; } @@ -65,71 +38,67 @@ std::unique_ptr EnableParams::Create(const PtJson ¶ms) return paramsObject; } -std::unique_ptr EvaluateOnCallFrameParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr EvaluateOnCallFrameParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "EvaluateOnCallFrameParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "callFrameId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->callFrameId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'callframeid' should be a String;"; - } + std::string callFrameId; + ret = params.GetString("callFrameId", &callFrameId); + if (ret == Result::SUCCESS) { + paramsObject->callFrameId_ = std::stoi(callFrameId); } else { - error += "should contain 'callframeid';"; + error += "Unknown 'callFrameId';"; } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "expression"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->expression_ = DebuggerApi::ToStdString(result); - } else { - error += "'expression' should be a String;"; - } + std::string expression; + ret = params.GetString("expression", &expression); + if (ret == Result::SUCCESS) { + paramsObject->expression_ = std::move(expression); } else { - error += "should contain 'expression';"; + error += "Unknown 'expression';"; } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "objectGroup"))); - if (!result.IsEmpty() && result->IsString()) { - paramsObject->objectGroup_ = DebuggerApi::ToStdString(result); + std::string objectGroup; + ret = params.GetString("objectGroup", &objectGroup); + if (ret == Result::SUCCESS) { + paramsObject->objectGroup_ = std::move(objectGroup); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'objectGroup';"; } - - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "includeCommandLineAPI"))); - if (!result.IsEmpty() && result->IsBoolean()) { - paramsObject->includeCommandLineApi_ = result->IsTrue(); + bool includeCommandLineAPI; + ret = params.GetBool("includeCommandLineAPI", &includeCommandLineAPI); + if (ret == Result::SUCCESS) { + paramsObject->includeCommandLineAPI_ = includeCommandLineAPI; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'includeCommandLineAPI';"; } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "silent"))); - if (!result.IsEmpty() && result->IsBoolean()) { - paramsObject->silent_ = result->IsTrue(); + bool silent; + ret = params.GetBool("silent", &silent); + if (ret == Result::SUCCESS) { + paramsObject->silent_ = silent; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'silent';"; } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "returnByValue"))); - if (!result.IsEmpty() && result->IsBoolean()) { - paramsObject->returnByValue_ = result->IsTrue(); + bool returnByValue; + ret = params.GetBool("returnByValue", &returnByValue); + if (ret == Result::SUCCESS) { + paramsObject->returnByValue_ = returnByValue; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'returnByValue';"; } - - result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "generatePreview"))); - if (!result.IsEmpty() && result->IsBoolean()) { - paramsObject->generatePreview_ = result->IsTrue(); + bool generatePreview; + ret = params.GetBool("generatePreview", &generatePreview); + if (ret == Result::SUCCESS) { + paramsObject->generatePreview_ = generatePreview; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'generatePreview';"; } - - result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "throwOnSideEffect"))); - if (!result.IsEmpty() && result->IsBoolean()) { - paramsObject->throwOnSideEffect_ = result->IsTrue(); + bool throwOnSideEffect; + ret = params.GetBool("throwOnSideEffect", &throwOnSideEffect); + if (ret == Result::SUCCESS) { + paramsObject->throwOnSideEffect_ = throwOnSideEffect; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'throwOnSideEffect';"; } if (!error.empty()) { @@ -139,55 +108,44 @@ std::unique_ptr EvaluateOnCallFrameParams::Create(con return paramsObject; } -std::unique_ptr GetPossibleBreakpointsParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr GetPossibleBreakpointsParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "start"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = Location::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'start' format error;"; - } else { - paramsObject->start_ = std::move(obj); - } + std::unique_ptr start; + ret = params.GetObject("start", &start); + if (ret == Result::SUCCESS) { + std::unique_ptr location = Location::Create(*start); + if (location == nullptr) { + error += "Unknown 'start';"; } else { - error += "'start' should be an Object;"; + paramsObject->start_ = std::move(location); } } else { - error += "should contain 'start';"; + error += "Unknown 'start';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "end"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = Location::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'end' format error;"; - } else { - paramsObject->end_ = std::move(obj); - } + std::unique_ptr end; + ret = params.GetObject("start", &end); + if (ret == Result::SUCCESS) { + std::unique_ptr location = Location::Create(*end); + if (location == nullptr) { + error += "Unknown 'end';"; } else { - error += "'end' should be an Object;"; + paramsObject->end_ = std::move(location); } + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'end';"; } - result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "restrictToFunction"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->restrictToFunction_ = result->IsTrue(); - } else { - error += "'restrictToFunction' should be a Boolean;"; - } + bool restrictToFunction; + ret = params.GetBool("restrictToFunction", &restrictToFunction); + if (ret == Result::SUCCESS) { + paramsObject->restrictToFunction_ = restrictToFunction; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'restrictToFunction';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "GetPossibleBreakpointsParams::Create " << error; return nullptr; @@ -196,28 +154,20 @@ std::unique_ptr GetPossibleBreakpointsParams::Crea return paramsObject; } -std::unique_ptr GetScriptSourceParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr GetScriptSourceParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->scriptId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'scriptId' should be a String;"; - } + std::string scriptId; + ret = params.GetString("scriptId", &scriptId); + if (ret == Result::SUCCESS) { + paramsObject->scriptId_ = std::stoi(scriptId); } else { - error += "should contain 'scriptId';"; + error += "Unknown 'scriptId';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "GetScriptSourceParams::Create " << error; return nullptr; @@ -226,28 +176,20 @@ std::unique_ptr GetScriptSourceParams::Create(const EcmaV return paramsObject; } -std::unique_ptr RemoveBreakpointParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr RemoveBreakpointParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "breakpointId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->breakpointId_ = DebuggerApi::ToStdString(result); - } else { - error += "'breakpointId' should be a String;"; - } + std::string breakpointId; + ret = params.GetString("breakpointId", &breakpointId); + if (ret == Result::SUCCESS) { + paramsObject->breakpointId_ = std::move(breakpointId); } else { - error += "should contain 'breakpointId';"; + error += "Unknown 'breakpointId';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "RemoveBreakpointParams::Create " << error; return nullptr; @@ -256,25 +198,20 @@ std::unique_ptr RemoveBreakpointParams::Create(const Ecm return paramsObject; } -std::unique_ptr ResumeParams::Create(const EcmaVM *ecmaVm, const Local ¶ms) +std::unique_ptr ResumeParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "terminateOnResume"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->terminateOnResume_ = result->IsTrue(); - } else { - error += "'terminateOnResume' should be a Boolean;"; - } + bool terminateOnResume; + ret = params.GetBool("terminateOnResume", &terminateOnResume); + if (ret == Result::SUCCESS) { + paramsObject->terminateOnResume_ = terminateOnResume; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'terminateOnResume';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "ResumeParams::Create " << error; return nullptr; @@ -283,28 +220,20 @@ std::unique_ptr ResumeParams::Create(const EcmaVM *ecmaVm, const L return paramsObject; } -std::unique_ptr SetAsyncCallStackDepthParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr SetAsyncCallStackDepthParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "maxDepth"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - paramsObject->maxDepth_ = static_cast(Local(result)->Value()); - } else { - error += "'maxDepth' should be a Number;"; - } + int32_t maxDepth; + ret = params.GetInt("maxDepth", &maxDepth); + if (ret == Result::SUCCESS) { + paramsObject->maxDepth_ = maxDepth; } else { - error += "should contain 'maxDepth';"; + error += "Unknown 'maxDepth';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "SetAsyncCallStackDepthParams::Create " << error; return nullptr; @@ -313,40 +242,28 @@ std::unique_ptr SetAsyncCallStackDepthParams::Crea return paramsObject; } -std::unique_ptr SetBlackboxPatternsParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr SetBlackboxPatternsParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "patterns"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - Local array = Local(result); - int32_t len = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < len; i++) { - key = IntegerRef::New(ecmaVm, i); - Local value = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - if (value->IsString()) { - paramsObject->patterns_.emplace_back( - DebuggerApi::ToStdString(value)); - } else { + std::unique_ptr patterns; + ret = params.GetArray("patterns", &patterns); + if (ret == Result::SUCCESS) { + int32_t len = patterns->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr item = patterns->Get(i); + if (item->IsString()) { + paramsObject->patterns_.emplace_back(item->GetString()); + } else { error += "'patterns' items should be a String;"; - } } - } else { - error += "'patterns' should be an Array;"; } } else { - error += "should contain 'patterns';"; + error += "Unknown 'patterns';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "SetBlackboxPatternsParams::Create " << error; return nullptr; @@ -355,67 +272,53 @@ std::unique_ptr SetBlackboxPatternsParams::Create(con return paramsObject; } -std::unique_ptr SetBreakpointByUrlParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr SetBreakpointByUrlParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - paramsObject->line_ = static_cast(Local(result)->Value()); - } else { - error += "'lineNumber' should be a Number;"; - } + int32_t lineNumber; + ret = params.GetInt("lineNumber", &lineNumber); + if (ret == Result::SUCCESS) { + paramsObject->lineNumber_ = lineNumber; } else { - error += "should contain 'lineNumber';"; + error += "Unknown 'lineNumber';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "url"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->url_ = DebuggerApi::ToStdString(result); - } else { - error += "'url' should be a String;"; - } + std::string url; + ret = params.GetString("url", &url); + if (ret == Result::SUCCESS) { + paramsObject->url_ = std::move(url); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'url';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "urlRegex"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->urlRegex_ = DebuggerApi::ToStdString(result); - } else { - error += "'urlRegex' should be a String;"; - } + std::string urlRegex; + ret = params.GetString("urlRegex", &urlRegex); + if (ret == Result::SUCCESS) { + paramsObject->urlRegex_ = std::move(urlRegex); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'urlRegex';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptHash"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->scriptHash_ = DebuggerApi::ToStdString(result); - } else { - error += "'scriptHash' should be a String;"; - } + std::string scriptHash; + ret = params.GetString("scriptHash", &scriptHash); + if (ret == Result::SUCCESS) { + paramsObject->scriptHash_ = std::move(scriptHash); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'scriptHash';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - paramsObject->column_ = static_cast(Local(result)->Value()); - } else { - error += "'columnNumber' should be a Number;"; - } + int32_t columnNumber; + ret = params.GetInt("columnNumber", &columnNumber); + if (ret == Result::SUCCESS) { + paramsObject->columnNumber_ = columnNumber; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'columnNumber';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "condition"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->condition_ = DebuggerApi::ToStdString(result); - } else { - error += "'condition' should be a String;"; - } + std::string condition; + ret = params.GetString("condition", &condition); + if (ret == Result::SUCCESS) { + paramsObject->condition_ = std::move(condition); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'condition';"; } if (!error.empty()) { LOG(ERROR, DEBUGGER) << "SetBreakpointByUrlParams::Create " << error; @@ -425,30 +328,20 @@ std::unique_ptr SetBreakpointByUrlParams::Create(const return paramsObject; } -std::unique_ptr SetPauseOnExceptionsParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr SetPauseOnExceptionsParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "state"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - if (!paramsObject->StoreState(DebuggerApi::ToStdString(result))) { - error += "'state' is invalid;"; - } - } else { - error += "'state' should be a String;"; - } + std::string state; + ret = params.GetString("state", &state); + if (ret == Result::SUCCESS) { + paramsObject->StoreState(state); } else { - error += "should contain 'state';"; + error += "Unknown 'state';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "SetPauseOnExceptionsParams::Create " << error; return nullptr; @@ -457,49 +350,35 @@ std::unique_ptr SetPauseOnExceptionsParams::Create(c return paramsObject; } -std::unique_ptr StepIntoParams::Create(const EcmaVM *ecmaVm, const Local ¶ms) +std::unique_ptr StepIntoParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "breakOnAsyncCall"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->breakOnAsyncCall_ = result->IsTrue(); - } else { - error += "'terminateOnResume' should be a Boolean;"; - } + bool breakOnAsyncCall; + ret = params.GetBool("breakOnAsyncCall", &breakOnAsyncCall); + if (ret == Result::SUCCESS) { + paramsObject->breakOnAsyncCall_ = breakOnAsyncCall; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'breakOnAsyncCall';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "skipList"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - Local array = Local(result); - int32_t len = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < len; i++) { - key = IntegerRef::New(ecmaVm, i); - Local value = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - if (value->IsObject()) { - std::unique_ptr obj = LocationRange::Create(ecmaVm, value); - if (obj != nullptr) { - paramsObject->skipList_->emplace_back(std::move(obj)); - } else { - error += "'skipList' items LocationRange is invalid;"; - } - } else { - error += "'skipList' items should be an Object;"; - } + std::unique_ptr skipList; + ret = params.GetArray("skipList", &skipList); + if (ret == Result::SUCCESS) { + int32_t len = skipList->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr obj = LocationRange::Create(*skipList->Get(i)); + if (obj == nullptr) { + error += "'skipList' items LocationRange is invalid;"; + } else { + paramsObject->skipList_->emplace_back(std::move(obj)); } - } else { - error += "'skipList' should be an Array;"; } + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'skipList';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "StepIntoParams::Create " << error; return nullptr; @@ -508,41 +387,28 @@ std::unique_ptr StepIntoParams::Create(const EcmaVM *ecmaVm, con return paramsObject; } -std::unique_ptr StepOverParams::Create(const EcmaVM *ecmaVm, const Local ¶ms) +std::unique_ptr StepOverParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "skipList"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - Local array = Local(result); - int32_t len = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < len; i++) { - key = IntegerRef::New(ecmaVm, i); - Local value = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - if (value->IsObject()) { - std::unique_ptr obj = LocationRange::Create(ecmaVm, value); - if (obj != nullptr) { - paramsObject->skipList_->emplace_back(std::move(obj)); - } else { - error += "'skipList' items LocationRange is invalid;"; - } - } else { - error += "'skipList' items should be an Object;"; - } + std::unique_ptr skipList; + ret = params.GetArray("skipList", &skipList); + if (ret == Result::SUCCESS) { + int32_t len = skipList->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr obj = LocationRange::Create(*skipList->Get(i)); + if (obj == nullptr) { + error += "'skipList' items LocationRange is invalid;"; + } else { + paramsObject->skipList_->emplace_back(std::move(obj)); } - } else { - error += "'skipList' should be an Array;"; } + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'skipList';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "StepOverParams::Create " << error; return nullptr; @@ -551,52 +417,39 @@ std::unique_ptr StepOverParams::Create(const EcmaVM *ecmaVm, con return paramsObject; } -std::unique_ptr GetPropertiesParams::Create(const EcmaVM *ecmaVm, const Local ¶ms) +std::unique_ptr GetPropertiesParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "GetPropertiesParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "objectId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->objectId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'objectId' should be a String;"; - } + std::string objectId; + ret = params.GetString("objectId", &objectId); + if (ret == Result::SUCCESS) { + paramsObject->objectId_ = std::stoi(objectId); } else { - error += "should contain 'objectId';"; + error += "Unknown 'objectId';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "ownProperties"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->ownProperties_ = result->IsTrue(); - } else { - error += "'ownProperties' should be a Boolean;"; - } + bool ownProperties; + ret = params.GetBool("ownProperties", &ownProperties); + if (ret == Result::SUCCESS) { + paramsObject->ownProperties_ = ownProperties; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'ownProperties';"; } - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "accessorPropertiesOnly"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->accessorPropertiesOnly_ = result->IsTrue(); - } else { - error += "'accessorPropertiesOnly' should be a Boolean;"; - } + bool accessorPropertiesOnly; + ret = params.GetBool("accessorPropertiesOnly", &accessorPropertiesOnly); + if (ret == Result::SUCCESS) { + paramsObject->accessorPropertiesOnly_ = accessorPropertiesOnly; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'accessorPropertiesOnly';"; } - result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "generatePreview"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->generatePreview_ = result->IsTrue(); - } else { - error += "'generatePreview' should be a Boolean;"; - } + bool generatePreview; + ret = params.GetBool("generatePreview", &generatePreview); + if (ret == Result::SUCCESS) { + paramsObject->generatePreview_ = generatePreview; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'generatePreview';"; } if (!error.empty()) { LOG(ERROR, DEBUGGER) << "GetPropertiesParams::Create " << error; @@ -606,138 +459,109 @@ std::unique_ptr GetPropertiesParams::Create(const EcmaVM *e return paramsObject; } -std::unique_ptr CallFunctionOnParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr CallFunctionOnParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "CallFunctionOnParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; // paramsObject->functionDeclaration_ - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "functionDeclaration"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->functionDeclaration_ = DebuggerApi::ToStdString(result); - } else { - error += "'functionDeclaration' should be a String;"; - } + std::string functionDeclaration; + ret = params.GetString("functionDeclaration", &functionDeclaration); + if (ret == Result::SUCCESS) { + paramsObject->functionDeclaration_ = std::move(functionDeclaration); } else { - error += "should contain 'functionDeclaration';"; + error += "Unknown 'functionDeclaration';"; } // paramsObject->objectId_ - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "objectId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->objectId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'objectId' should be a String;"; - } + std::string objectId; + ret = params.GetString("objectId", &objectId); + if (ret == Result::SUCCESS) { + paramsObject->objectId_ = std::stoi(objectId); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'objectId';"; } // paramsObject->arguments_ - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "arguments"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - Local array = Local(result); - int32_t len = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < len; i++) { - key = IntegerRef::New(ecmaVm, i); - Local value = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - if (value->IsObject()) { - std::unique_ptr obj = CallArgument::Create(ecmaVm, value); - if (obj != nullptr) { - paramsObject->arguments_->emplace_back(std::move(obj)); - } else { - error += "'arguments' items CallArgument is invaild;"; - } - } else { - error += "'arguments' items should be an Object;"; - } + std::unique_ptr arguments; + ret = params.GetArray("arguments", &arguments); + if (ret == Result::SUCCESS) { + int32_t len = arguments->GetSize(); + for (int32_t i = 0; i < len; ++i) { + std::unique_ptr obj = CallArgument::Create(*arguments->Get(i)); + if (obj == nullptr) { + error += "'arguments' items CallArgument is invaild;"; + } else { + paramsObject->arguments_->emplace_back(std::move(obj)); } - } else { - error += "'arguments' should be an Array;"; } + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'arguments';"; } // paramsObject->silent_ - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "silent"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->silent_ = result->IsTrue(); - } else { - error += "'silent' should be a Boolean;"; - } + bool silent; + ret = params.GetBool("silent", &silent); + if (ret == Result::SUCCESS) { + paramsObject->silent_ = silent; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'silent';"; } // paramsObject->returnByValue_ - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "returnByValue"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->returnByValue_ = result->IsTrue(); - } else { - error += "'returnByValue' should be a Boolean;"; - } + bool returnByValue; + ret = params.GetBool("returnByValue", &returnByValue); + if (ret == Result::SUCCESS) { + paramsObject->returnByValue_ = returnByValue; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'returnByValue';"; } // paramsObject->generatePreview_ - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "generatePreview"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->generatePreview_ = result->IsTrue(); - } else { - error += "'generatePreview' should be a Boolean;"; - } + bool generatePreview; + ret = params.GetBool("generatePreview", &generatePreview); + if (ret == Result::SUCCESS) { + paramsObject->generatePreview_ = generatePreview; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'generatePreview';"; } // paramsObject->userGesture_ - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "userGesture"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->userGesture_ = result->IsTrue(); - } else { - error += "'userGesture' should be a Boolean;"; - } + bool userGesture; + ret = params.GetBool("userGesture", &userGesture); + if (ret == Result::SUCCESS) { + paramsObject->userGesture_ = userGesture; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'userGesture';"; } // paramsObject->awaitPromise_ - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "awaitPromise"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->awaitPromise_ = result->IsTrue(); - } else { - error += "'awaitPromise' should be a Boolean;"; - } + bool awaitPromise; + ret = params.GetBool("awaitPromise", &awaitPromise); + if (ret == Result::SUCCESS) { + paramsObject->awaitPromise_ = awaitPromise; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'awaitPromise';"; } // paramsObject->executionContextId_ - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "executionContextId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - paramsObject->executionContextId_ = static_cast(Local(result)->Value()); - } else { - error += "'executionContextId' should be a Number;"; - } + int32_t executionContextId; + ret = params.GetInt("executionContextId", &executionContextId); + if (ret == Result::SUCCESS) { + paramsObject->executionContextId_ = executionContextId; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'executionContextId';"; } // paramsObject->objectGroup_ - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "objectGroup"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->objectGroup_ = DebuggerApi::ToStdString(result); - } else { - error += "'objectGroup' should be a String;"; - } + std::string objectGroup; + ret = params.GetString("objectGroup", &objectGroup); + if (ret == Result::SUCCESS) { + paramsObject->objectGroup_ = std::move(objectGroup); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'objectGroup';"; } // paramsObject->throwOnSideEffect_ - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "throwOnSideEffect"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->throwOnSideEffect_ = result->IsTrue(); - } else { - error += "'throwOnSideEffect' should be a Boolean;"; - } + bool throwOnSideEffect; + ret = params.GetBool("throwOnSideEffect", &throwOnSideEffect); + if (ret == Result::SUCCESS) { + paramsObject->throwOnSideEffect_ = throwOnSideEffect; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'throwOnSideEffect';"; } + // Check whether the error is empty. if (!error.empty()) { LOG(ERROR, DEBUGGER) << "CallFunctionOnParams::Create " << error; @@ -747,25 +571,18 @@ std::unique_ptr CallFunctionOnParams::Create(const EcmaVM return paramsObject; } -std::unique_ptr StartSamplingParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr StartSamplingParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "StartSamplingParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "samplingInterval"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - paramsObject->samplingInterval_ = static_cast(Local(result)->Value()); - } else { - error += "'samplingInterval' should be a Number;"; - } + int32_t samplingInterval; + ret = params.GetInt("samplingInterval", &samplingInterval); + if (ret == Result::SUCCESS) { + paramsObject->samplingInterval_ = samplingInterval; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'samplingInterval';"; } if (!error.empty()) { @@ -775,26 +592,20 @@ std::unique_ptr StartSamplingParams::Create(const EcmaVM *e return paramsObject; } -std::unique_ptr StartTrackingHeapObjectsParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr StartTrackingHeapObjectsParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "StartTrackingHeapObjectsParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "trackAllocations"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->trackAllocations_ = result->IsTrue(); - } else { - error += "'trackAllocations' should be a boolean;"; - } + bool trackAllocations; + ret = params.GetBool("trackAllocations", &trackAllocations); + if (ret == Result::SUCCESS) { + paramsObject->trackAllocations_ = trackAllocations; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'trackAllocations';"; } + if (!error.empty()) { LOG(ERROR, DEBUGGER) << "StartTrackingHeapObjectsParams::Create " << error; return nullptr; @@ -802,45 +613,34 @@ std::unique_ptr StartTrackingHeapObjectsParams:: return paramsObject; } -std::unique_ptr StopTrackingHeapObjectsParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr StopTrackingHeapObjectsParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "StopTrackingHeapObjectsParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "reportProgress"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->reportProgress_ = result->IsTrue(); - } else { - error += "'reportProgress' should be a boolean;"; - } + bool reportProgress; + ret = params.GetBool("reportProgress", &reportProgress); + if (ret == Result::SUCCESS) { + paramsObject->reportProgress_ = reportProgress; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'reportProgress';"; } - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "treatGlobalObjectsAsRoots"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->treatGlobalObjectsAsRoots_ = result->IsTrue(); - } else { - error += "'treatGlobalObjectsAsRoots' should be a boolean;"; - } + bool treatGlobalObjectsAsRoots; + ret = params.GetBool("treatGlobalObjectsAsRoots", &treatGlobalObjectsAsRoots); + if (ret == Result::SUCCESS) { + paramsObject->treatGlobalObjectsAsRoots_ = treatGlobalObjectsAsRoots; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'treatGlobalObjectsAsRoots';"; } - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "captureNumericValue"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->captureNumericValue_ = result->IsTrue(); - } else { - error += "'captureNumericValue' should be a boolean;"; - } + bool captureNumericValue; + ret = params.GetBool("captureNumericValue", &captureNumericValue); + if (ret == Result::SUCCESS) { + paramsObject->captureNumericValue_ = captureNumericValue; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'captureNumericValue';"; } if (!error.empty()) { @@ -850,27 +650,18 @@ std::unique_ptr StopTrackingHeapObjectsParams::Cr return paramsObject; } -std::unique_ptr AddInspectedHeapObjectParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr AddInspectedHeapObjectParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "AddInspectedHeapObjectParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "heapObjectId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->heapObjectId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'heapObjectId' should be a String;"; - } + std::string heapObjectId; + ret = params.GetString("heapObjectId", &heapObjectId); + if (ret == Result::SUCCESS) { + paramsObject->heapObjectId_ = std::stoi(heapObjectId); } else { - error += "should contain 'heapObjectId';"; + error += "Unknown 'heapObjectId';"; } if (!error.empty()) { @@ -880,27 +671,18 @@ std::unique_ptr AddInspectedHeapObjectParams::Crea return paramsObject; } -std::unique_ptr GetHeapObjectIdParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr GetHeapObjectIdParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "GetHeapObjectIdParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "objectId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->objectId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'objectId' should be a String;"; - } - } else { - error += "should contain 'objectId';"; + std::string objectId; + ret = params.GetString("objectId", &objectId); + if (ret == Result::SUCCESS) { + paramsObject->objectId_ = std::stoi(objectId); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'objectId';"; } if (!error.empty()) { @@ -910,37 +692,26 @@ std::unique_ptr GetHeapObjectIdParams::Create(const EcmaV return paramsObject; } -std::unique_ptr GetObjectByHeapObjectIdParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr GetObjectByHeapObjectIdParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "GetObjectByHeapObjectIdParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "objectId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->objectId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'objectId' should be a String;"; - } - } else { - error += "should contain 'objectId';"; + std::string objectId; + ret = params.GetString("objectId", &objectId); + if (ret == Result::SUCCESS) { + paramsObject->objectId_ = std::stoi(objectId); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'objectId';"; } - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "objectGroup"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - paramsObject->objectGroup_ = DebuggerApi::ToStdString(result); - } else { - error += "'objectGroup' should be a String;"; - } + std::string objectGroup; + ret = params.GetString("objectGroup", &objectGroup); + if (ret == Result::SUCCESS) { + paramsObject->objectGroup_ = std::move(objectGroup); + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'objectGroup';"; } if (!error.empty()) { @@ -950,45 +721,34 @@ std::unique_ptr GetObjectByHeapObjectIdParams::Cr return paramsObject; } -std::unique_ptr StartPreciseCoverageParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr StartPreciseCoverageParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "StartPreciseCoverageParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "callCount"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->callCount_ = result->IsTrue(); - } else { - error += "'callCount' should be a boolean;"; - } + bool callCount; + ret = params.GetBool("callCount", &callCount); + if (ret == Result::SUCCESS) { + paramsObject->callCount_ = callCount; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'callCount';"; } - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "detailed"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->detailed_ = result->IsTrue(); - } else { - error += "'detailed' should be a boolean;"; - } + bool detailed; + ret = params.GetBool("detailed", &detailed); + if (ret == Result::SUCCESS) { + paramsObject->detailed_ = detailed; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'detailed';"; } - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "allowTriggeredUpdates"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - paramsObject->allowTriggeredUpdates_ = result->IsTrue(); - } else { - error += "'allowTriggeredUpdates' should be a boolean;"; - } + bool allowTriggeredUpdates; + ret = params.GetBool("allowTriggeredUpdates", &allowTriggeredUpdates); + if (ret == Result::SUCCESS) { + paramsObject->allowTriggeredUpdates_ = allowTriggeredUpdates; + } else if (ret == Result::TYPE_ERROR) { // optional value + error += "Unknown 'allowTriggeredUpdates';"; } if (!error.empty()) { @@ -998,27 +758,18 @@ std::unique_ptr StartPreciseCoverageParams::Create(c return paramsObject; } -std::unique_ptr SetSamplingIntervalParams::Create(const EcmaVM *ecmaVm, - const Local ¶ms) +std::unique_ptr SetSamplingIntervalParams::Create(const PtJson ¶ms) { - ASSERT(ecmaVm); - if (params.IsEmpty()) { - LOG(ERROR, DEBUGGER) << "SetSamplingIntervalParams::Create params is nullptr"; - return nullptr; - } - std::string error; auto paramsObject = std::make_unique(); + std::string error; + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "interval"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - paramsObject->interval_ = static_cast(Local(result)->Value()); - } else { - error += "'interval' should be a Number;"; - } + int32_t interval; + ret = params.GetInt("interval", &interval); + if (ret == Result::SUCCESS) { + paramsObject->interval_ = interval; } else { - error += "should contain 'interval';"; + error += "Unknown 'interval';"; } if (!error.empty()) { diff --git a/ecmascript/tooling/base/pt_params.h b/ecmascript/tooling/base/pt_params.h index a160040a..7fe6278c 100644 --- a/ecmascript/tooling/base/pt_params.h +++ b/ecmascript/tooling/base/pt_params.h @@ -39,7 +39,6 @@ public: EnableParams() = default; ~EnableParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); double GetMaxScriptsCacheSize() const @@ -64,7 +63,7 @@ public: EvaluateOnCallFrameParams() = default; ~EvaluateOnCallFrameParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); CallFrameId GetCallFrameId() const { @@ -83,7 +82,7 @@ private: CallFrameId callFrameId_ {}; std::string expression_ {}; std::optional objectGroup_ {}; - std::optional includeCommandLineApi_ {}; + std::optional includeCommandLineAPI_ {}; std::optional silent_ {}; std::optional returnByValue_ {}; std::optional generatePreview_ {}; @@ -95,7 +94,7 @@ public: GetPossibleBreakpointsParams() = default; ~GetPossibleBreakpointsParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); Location *GetStart() const { @@ -139,7 +138,7 @@ public: GetScriptSourceParams() = default; ~GetScriptSourceParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); ScriptId GetScriptId() const { @@ -158,7 +157,7 @@ public: RemoveBreakpointParams() = default; ~RemoveBreakpointParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); BreakpointId GetBreakpointId() const { @@ -177,7 +176,7 @@ public: ResumeParams() = default; ~ResumeParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); bool GetTerminateOnResume() const { @@ -201,9 +200,9 @@ public: SetAsyncCallStackDepthParams() = default; ~SetAsyncCallStackDepthParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); - uint32_t GetMaxDepth() const + int32_t GetMaxDepth() const { return maxDepth_; } @@ -212,14 +211,14 @@ private: NO_COPY_SEMANTIC(SetAsyncCallStackDepthParams); NO_MOVE_SEMANTIC(SetAsyncCallStackDepthParams); - uint32_t maxDepth_ {0}; + int32_t maxDepth_ {0}; }; class SetBlackboxPatternsParams : public PtBaseParams { public: SetBlackboxPatternsParams() = default; ~SetBlackboxPatternsParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); std::list GetPatterns() const { @@ -238,11 +237,11 @@ public: SetBreakpointByUrlParams() = default; ~SetBreakpointByUrlParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); int32_t GetLine() const { - return line_; + return lineNumber_; } const std::string &GetUrl() const @@ -280,12 +279,12 @@ public: int32_t GetColumn() const { - return column_.value_or(0); + return columnNumber_.value_or(0); } bool HasColumn() const { - return column_.has_value(); + return columnNumber_.has_value(); } const std::string &GetCondition() const @@ -303,11 +302,11 @@ private: NO_COPY_SEMANTIC(SetBreakpointByUrlParams); NO_MOVE_SEMANTIC(SetBreakpointByUrlParams); - int32_t line_ {0}; + int32_t lineNumber_ {0}; std::optional url_ {}; std::optional urlRegex_ {}; std::optional scriptHash_ {}; - std::optional column_ {0}; + std::optional columnNumber_ {0}; std::optional condition_ {}; }; @@ -317,7 +316,7 @@ class SetPauseOnExceptionsParams : public PtBaseParams { public: SetPauseOnExceptionsParams() = default; ~SetPauseOnExceptionsParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); PauseOnExceptionsState GetState() const { @@ -353,7 +352,7 @@ public: StepIntoParams() = default; ~StepIntoParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); bool GetBreakOnAsyncCall() const { @@ -391,7 +390,7 @@ public: StepOverParams() = default; ~StepOverParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); const std::list> *GetSkipList() const { @@ -418,7 +417,7 @@ public: GetPropertiesParams() = default; ~GetPropertiesParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); RemoteObjectId GetObjectId() const { @@ -470,7 +469,7 @@ public: CallFunctionOnParams() = default; ~CallFunctionOnParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); const std::string &GetFunctionDeclaration() { @@ -615,7 +614,7 @@ public: StartSamplingParams() = default; ~StartSamplingParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); int32_t GetSamplingInterval() const { @@ -626,7 +625,7 @@ private: NO_COPY_SEMANTIC(StartSamplingParams); NO_MOVE_SEMANTIC(StartSamplingParams); - std::optional samplingInterval_ {32768}; + std::optional samplingInterval_ {32768}; }; class StartTrackingHeapObjectsParams : public PtBaseParams { @@ -634,8 +633,7 @@ public: StartTrackingHeapObjectsParams() = default; ~StartTrackingHeapObjectsParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, - const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); bool GetTrackAllocations() const { @@ -659,7 +657,7 @@ public: StopTrackingHeapObjectsParams() = default; ~StopTrackingHeapObjectsParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); bool GetReportProgress() const { @@ -705,7 +703,7 @@ public: AddInspectedHeapObjectParams() = default; ~AddInspectedHeapObjectParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); HeapSnapshotObjectId GetHeapObjectId() const { @@ -724,7 +722,7 @@ public: GetHeapObjectIdParams() = default; ~GetHeapObjectIdParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); RemoteObjectId GetObjectId() const { @@ -743,7 +741,7 @@ public: GetObjectByHeapObjectIdParams() = default; ~GetObjectByHeapObjectIdParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); HeapSnapshotObjectId GetObjectId() const { @@ -774,8 +772,7 @@ public: StartPreciseCoverageParams() = default; ~StartPreciseCoverageParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, - const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); bool GetCallCount() const { @@ -821,14 +818,14 @@ public: SetSamplingIntervalParams() = default; ~SetSamplingIntervalParams() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr Create(const PtJson ¶ms); - int GetInterval() const + int32_t GetInterval() const { return interval_; } - SetSamplingIntervalParams &SetInterval(int interval) + SetSamplingIntervalParams &SetInterval(int32_t interval) { interval_ = interval; return *this; @@ -838,7 +835,7 @@ private: NO_COPY_SEMANTIC(SetSamplingIntervalParams); NO_MOVE_SEMANTIC(SetSamplingIntervalParams); - int interval_ {0}; + int32_t interval_ {0}; }; } // namespace panda::ecmascript::tooling #endif \ No newline at end of file diff --git a/ecmascript/tooling/base/pt_types.cpp b/ecmascript/tooling/base/pt_types.cpp index 457b9de3..5cb250de 100644 --- a/ecmascript/tooling/base/pt_types.cpp +++ b/ecmascript/tooling/base/pt_types.cpp @@ -557,7 +557,7 @@ std::unique_ptr ExceptionDetails::Create(const EcmaVM *ecmaVm, result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); if (!result.IsEmpty() && !result->IsUndefined()) { if (result->IsNumber()) { - exceptionDetails->line_ = static_cast(Local(result)->Value()); + exceptionDetails->lineNumber_ = static_cast(Local(result)->Value()); } else { error += "'lineNumber' should be a Number;"; } @@ -567,7 +567,7 @@ std::unique_ptr ExceptionDetails::Create(const EcmaVM *ecmaVm, result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); if (!result.IsEmpty() && !result->IsUndefined()) { if (result->IsNumber()) { - exceptionDetails->column_ = static_cast(Local(result)->Value()); + exceptionDetails->columnNumber_ = static_cast(Local(result)->Value()); } else { error += "'columnNumber' should be a Number;"; } @@ -643,18 +643,18 @@ std::unique_ptr ExceptionDetails::Create(const PtJson ¶ms) error += "Unknown 'text';"; } - int32_t line; - ret = params.GetInt("lineNumber", &line); + int32_t lineNumber; + ret = params.GetInt("lineNumber", &lineNumber); if (ret == Result::SUCCESS) { - exceptionDetails->line_ = line; + exceptionDetails->lineNumber_ = lineNumber; } else { error += "Unknown 'lineNumber';"; } - int32_t column; - ret = params.GetInt("columnNumber", &column); + int32_t columnNumber; + ret = params.GetInt("columnNumber", &columnNumber); if (ret == Result::SUCCESS) { - exceptionDetails->column_ = column; + exceptionDetails->columnNumber_ = columnNumber; } else { error += "Unknown 'columnNumber';"; } @@ -715,9 +715,9 @@ Local ExceptionDetails::ToObject(const EcmaVM *ecmaVm) const Local(StringRef::NewFromUtf8(ecmaVm, "text")), Local(StringRef::NewFromUtf8(ecmaVm, text_.c_str()))); params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, line_)); + IntegerRef::New(ecmaVm, lineNumber_)); params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, column_)); + IntegerRef::New(ecmaVm, columnNumber_)); if (scriptId_) { params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), @@ -749,8 +749,8 @@ std::unique_ptr ExceptionDetails::ToJson() const result->Add("exceptionId", exceptionId_); result->Add("text", text_.c_str()); - result->Add("lineNumber", line_); - result->Add("columnNumber", column_); + result->Add("lineNumber", lineNumber_); + result->Add("columnNumber", columnNumber_); if (scriptId_) { result->Add("scriptId", std::to_string(scriptId_.value()).c_str()); @@ -1412,64 +1412,24 @@ std::unique_ptr PropertyDescriptor::ToJson() const return result; } -std::unique_ptr CallArgument::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "CallArgument::Create params is nullptr"; - return nullptr; - } - std::string error; - auto callArgument = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "value"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - callArgument->value_ = result; - } - result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "unserializableValue"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - callArgument->unserializableValue_ = DebuggerApi::ToStdString(result); - } else { - error += "'unserializableValue' should be a String;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "objectId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - callArgument->objectId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'objectId' should be a String;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "CallArgument::Create " << error; - return nullptr; - } - - return callArgument; -} - std::unique_ptr CallArgument::Create(const PtJson ¶ms) { - std::string error; auto callArgument = std::make_unique(); + std::string error; Result ret; std::string unserializableValue; ret = params.GetString("unserializableValue", &unserializableValue); if (ret == Result::SUCCESS) { callArgument->unserializableValue_ = std::move(unserializableValue); - } else if (ret == Result::TYPE_ERROR) { + } else if (ret == Result::TYPE_ERROR) { // optional value error += "Unknown 'unserializableValue';"; } - std::string objectId; ret = params.GetString("objectId", &objectId); if (ret == Result::SUCCESS) { callArgument->objectId_ = std::stoi(objectId); - } else if (ret == Result::TYPE_ERROR) { + } else if (ret == Result::TYPE_ERROR) { // optional value error += "Unknown 'objectId';"; } @@ -1481,27 +1441,6 @@ std::unique_ptr CallArgument::Create(const PtJson ¶ms) return callArgument; } -Local CallArgument::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - if (value_) { - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "value")), value_.value()); - } - if (unserializableValue_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "unserializableValue")), - Local(StringRef::NewFromUtf8(ecmaVm, unserializableValue_->c_str()))); - } - if (objectId_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "objectId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(objectId_.value()).c_str()))); - } - - return params; -} - std::unique_ptr CallArgument::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -1539,7 +1478,7 @@ std::unique_ptr Location::Create(const EcmaVM *ecmaVm, const Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); if (!result.IsEmpty() && !result->IsUndefined()) { if (result->IsNumber()) { - location->line_ = static_cast(Local(result)->Value()); + location->lineNumber_ = static_cast(Local(result)->Value()); } else { error += "'lineNumber' should be a Number;"; } @@ -1549,7 +1488,7 @@ std::unique_ptr Location::Create(const EcmaVM *ecmaVm, const Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); if (!result.IsEmpty() && !result->IsUndefined()) { if (result->IsNumber()) { - location->column_ = static_cast(Local(result)->Value()); + location->columnNumber_ = static_cast(Local(result)->Value()); } else { error += "'columnNumber' should be a Number;"; } @@ -1575,17 +1514,17 @@ std::unique_ptr Location::Create(const PtJson ¶ms) } else { error += "Unknown 'scriptId';"; } - int32_t line; - ret = params.GetInt("lineNumber", &line); + int32_t lineNumber; + ret = params.GetInt("lineNumber", &lineNumber); if (ret == Result::SUCCESS) { - location->line_ = line; + location->lineNumber_ = lineNumber; } else { error += "Unknown 'lineNumber';"; } - int32_t column; - ret = params.GetInt("columnNumber", &column); + int32_t columnNumber; + ret = params.GetInt("columnNumber", &columnNumber); if (ret == Result::SUCCESS) { - location->column_ = column; + location->columnNumber_ = columnNumber; } else if (ret == Result::TYPE_ERROR) { // optional value error += "Unknown 'columnNumber';"; } @@ -1606,11 +1545,11 @@ Local Location::ToObject(const EcmaVM *ecmaVm) const Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(scriptId_).c_str()))); params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, line_)); - if (column_) { + IntegerRef::New(ecmaVm, lineNumber_)); + if (columnNumber_) { params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, column_.value())); + IntegerRef::New(ecmaVm, columnNumber_.value())); } return params; @@ -1621,70 +1560,31 @@ std::unique_ptr Location::ToJson() const std::unique_ptr result = PtJson::CreateObject(); result->Add("scriptId", std::to_string(scriptId_).c_str()); - result->Add("lineNumber", line_); - if (column_) { - result->Add("columnNumber", column_.value()); + result->Add("lineNumber", lineNumber_); + if (columnNumber_) { + result->Add("columnNumber", columnNumber_.value()); } return result; } -std::unique_ptr ScriptPosition::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "ScriptPosition::Create params is nullptr"; - return nullptr; - } - std::string error; - auto scriptPosition = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - scriptPosition->line_ = static_cast(Local(result)->Value()); - } else { - error += "'lineNumber' should be a Number;"; - } - } else { - error += "should contain 'lineNumber';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - scriptPosition->column_ = static_cast(Local(result)->Value()); - } else { - error += "'columnNumber' should be a Number;"; - } - } else { - error += "should contain 'columnNumber';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "ScriptPosition::Create " << error; - return nullptr; - } - - return scriptPosition; -} - std::unique_ptr ScriptPosition::Create(const PtJson ¶ms) { - std::string error; auto scriptPosition = std::make_unique(); + std::string error; Result ret; - int32_t line; - ret = params.GetInt("lineNumber", &line); + int32_t lineNumber; + ret = params.GetInt("lineNumber", &lineNumber); if (ret == Result::SUCCESS) { - scriptPosition->line_ = line; + scriptPosition->lineNumber_ = lineNumber; } else { error += "Unknown 'lineNumber';"; } - - int32_t column; - ret = params.GetInt("columnNumber", &column); + int32_t columnNumber; + ret = params.GetInt("columnNumber", &columnNumber); if (ret == Result::SUCCESS) { - scriptPosition->column_ = column; + scriptPosition->columnNumber_ = columnNumber; } else { error += "Unknown 'columnNumber';"; } @@ -1702,9 +1602,9 @@ Local ScriptPosition::ToObject(const EcmaVM *ecmaVm) const Local params = NewObject(ecmaVm); params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, line_)); + IntegerRef::New(ecmaVm, lineNumber_)); params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, column_)); + IntegerRef::New(ecmaVm, columnNumber_)); return params; } @@ -1713,8 +1613,8 @@ std::unique_ptr ScriptPosition::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - result->Add("lineNumber", line_); - result->Add("columnNumber", column_); + result->Add("lineNumber", lineNumber_); + result->Add("columnNumber", columnNumber_); return result; } @@ -1811,64 +1711,6 @@ std::unique_ptr SearchMatch::ToJson() const return result; } -std::unique_ptr LocationRange::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "BreakLocation::Create params is nullptr"; - return nullptr; - } - std::string error; - auto locationRange = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - locationRange->scriptId_ = DebuggerApi::StringToInt(result); - } else { - error += "'scriptId' should be a String;"; - } - } else { - error += "should contain 'scriptId';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "start"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = ScriptPosition::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'start' format error;"; - } else { - locationRange->start_ = std::move(obj); - } - } else { - error += "'start' should be an Object;"; - } - } else { - error += "should contain 'start';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "end"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = ScriptPosition::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'end' format error;"; - } else { - locationRange->end_ = std::move(obj); - } - } else { - error += "'end' should be an Object;"; - } - } else { - error += "should contain 'end';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "LocationRange::Create " << error; - return nullptr; - } - - return locationRange; -} - std::unique_ptr LocationRange::Create(const PtJson ¶ms) { std::string error; @@ -1974,7 +1816,7 @@ std::unique_ptr BreakLocation::Create(const EcmaVM *ecmaVm, const result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); if (!result.IsEmpty() && !result->IsUndefined()) { if (result->IsNumber()) { - breakLocation->line_ = static_cast(Local(result)->Value()); + breakLocation->lineNumber_ = static_cast(Local(result)->Value()); } else { error += "'lineNumber' should be a Number;"; } @@ -1984,7 +1826,7 @@ std::unique_ptr BreakLocation::Create(const EcmaVM *ecmaVm, const result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); if (!result.IsEmpty() && !result->IsUndefined()) { if (result->IsNumber()) { - breakLocation->column_ = static_cast(Local(result)->Value()); + breakLocation->columnNumber_ = static_cast(Local(result)->Value()); } else { error += "'columnNumber' should be a Number;"; } @@ -2027,7 +1869,7 @@ std::unique_ptr BreakLocation::Create(const PtJson ¶ms) int32_t lineNumber; ret = params.GetInt("lineNumber", &lineNumber); if (ret == Result::SUCCESS) { - breakLocation->line_ = lineNumber; + breakLocation->lineNumber_ = lineNumber; } else { error += "Unknown 'lineNumber';"; } @@ -2035,7 +1877,7 @@ std::unique_ptr BreakLocation::Create(const PtJson ¶ms) int32_t columnNumber; ret = params.GetInt("columnNumber", &columnNumber); if (ret == Result::SUCCESS) { - breakLocation->column_ = columnNumber; + breakLocation->columnNumber_ = columnNumber; } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'columnNumber';"; } @@ -2068,11 +1910,11 @@ Local BreakLocation::ToObject(const EcmaVM *ecmaVm) const Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(scriptId_).c_str()))); params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, line_)); - if (column_) { + IntegerRef::New(ecmaVm, lineNumber_)); + if (columnNumber_) { params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, column_.value())); + IntegerRef::New(ecmaVm, columnNumber_.value())); } if (type_) { params->Set(ecmaVm, @@ -2088,9 +1930,9 @@ std::unique_ptr BreakLocation::ToJson() const std::unique_ptr result = PtJson::CreateObject(); result->Add("scriptId", std::to_string(scriptId_).c_str()); - result->Add("lineNumber", line_); - if (column_) { - result->Add("columnNumber", column_.value()); + result->Add("lineNumber", lineNumber_); + if (columnNumber_) { + result->Add("columnNumber", columnNumber_.value()); } if (type_) { result->Add("type", type_->c_str()); diff --git a/ecmascript/tooling/base/pt_types.h b/ecmascript/tooling/base/pt_types.h index 3913c8e5..c752210c 100644 --- a/ecmascript/tooling/base/pt_types.h +++ b/ecmascript/tooling/base/pt_types.h @@ -440,23 +440,23 @@ public: int32_t GetLine() const { - return line_; + return lineNumber_; } - ExceptionDetails &SetLine(int32_t line) + ExceptionDetails &SetLine(int32_t lineNumber) { - line_ = line; + lineNumber_ = lineNumber; return *this; } int32_t GetColumn() const { - return column_; + return columnNumber_; } - ExceptionDetails &SetColumn(int32_t column) + ExceptionDetails &SetColumn(int32_t columnNumber) { - column_ = column; + columnNumber_ = columnNumber; return *this; } @@ -534,8 +534,8 @@ private: int32_t exceptionId_ {0}; std::string text_ {}; - int32_t line_ {0}; - int32_t column_ {0}; + int32_t lineNumber_ {0}; + int32_t columnNumber_ {0}; std::optional scriptId_ {}; std::optional url_ {}; std::optional> exception_ {}; @@ -872,9 +872,11 @@ public: CallArgument() = default; ~CallArgument() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; + Local ToObject([[maybe_unused]] const EcmaVM *ecmaVm) const override + { + return Local(); + } std::unique_ptr ToJson() const override; Local GetValue() const @@ -976,29 +978,29 @@ public: int32_t GetLine() const { - return line_; + return lineNumber_; } Location &SetLine(int32_t line) { - line_ = line; + lineNumber_ = line; return *this; } int32_t GetColumn() const { - return column_.value_or(-1); + return columnNumber_.value_or(-1); } Location &SetColumn(int32_t column) { - column_ = column; + columnNumber_ = column; return *this; } bool HasColumn() const { - return column_.has_value(); + return columnNumber_.has_value(); } private: @@ -1006,8 +1008,8 @@ private: NO_MOVE_SEMANTIC(Location); ScriptId scriptId_ {}; - int32_t line_ {0}; - std::optional column_ {}; + int32_t lineNumber_ {0}; + std::optional columnNumber_ {}; }; // Debugger.ScriptPosition @@ -1016,30 +1018,29 @@ public: ScriptPosition() = default; ~ScriptPosition() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; int32_t GetLine() const { - return line_; + return lineNumber_; } ScriptPosition &SetLine(int32_t line) { - line_ = line; + lineNumber_ = line; return *this; } int32_t GetColumn() const { - return column_; + return columnNumber_; } ScriptPosition &SetColumn(int32_t column) { - column_ = column; + columnNumber_ = column; return *this; } @@ -1047,8 +1048,8 @@ private: NO_COPY_SEMANTIC(ScriptPosition); NO_MOVE_SEMANTIC(ScriptPosition); - int32_t line_ {0}; - int32_t column_ {0}; + int32_t lineNumber_ {0}; + int32_t columnNumber_ {0}; }; // Debugger.SearchMatch @@ -1075,7 +1076,6 @@ public: LocationRange() = default; ~LocationRange() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; @@ -1146,29 +1146,29 @@ public: int32_t GetLine() const { - return line_; + return lineNumber_; } - BreakLocation &SetLine(int32_t line) + BreakLocation &SetLine(int32_t lineNumber) { - line_ = line; + lineNumber_ = lineNumber; return *this; } int32_t GetColumn() const { - return column_.value_or(-1); + return columnNumber_.value_or(-1); } - BreakLocation &SetColumn(int32_t column) + BreakLocation &SetColumn(int32_t columnNumber) { - column_ = column; + columnNumber_ = columnNumber; return *this; } bool HasColumn() const { - return column_.has_value(); + return columnNumber_.has_value(); } /* @@ -1215,8 +1215,8 @@ private: NO_MOVE_SEMANTIC(BreakLocation); ScriptId scriptId_ {}; - int32_t line_ {0}; - std::optional column_ {}; + int32_t lineNumber_ {0}; + std::optional columnNumber_ {}; std::optional type_ {}; }; using BreakType = BreakLocation::Type; @@ -1515,7 +1515,7 @@ private: // ========== Heapprofiler types begin -using HeapSnapshotObjectId = uint32_t; +using HeapSnapshotObjectId = int32_t; class SamplingHeapProfileSample final : public PtBaseTypes { public: diff --git a/ecmascript/tooling/test/debugger_params_test.cpp b/ecmascript/tooling/test/debugger_params_test.cpp index b9802d05..61825046 100644 --- a/ecmascript/tooling/test/debugger_params_test.cpp +++ b/ecmascript/tooling/test/debugger_params_test.cpp @@ -88,41 +88,31 @@ HWTEST_F_L0(DebuggerParamsTest, StartSamplingParamsCreateTest) std::string msg; std::unique_ptr startSamplingData; - // abnormal params of null msg - msg = std::string() + R"({})"; - startSamplingData = StartSamplingParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(startSamplingData, nullptr); - - // abnormal params of unexist key params - msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - startSamplingData = StartSamplingParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(startSamplingData, nullptr); - // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - startSamplingData = StartSamplingParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(startSamplingData, nullptr); EXPECT_EQ(startSamplingData->GetSamplingInterval(), 32768); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - startSamplingData = StartSamplingParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(startSamplingData, nullptr); EXPECT_EQ(startSamplingData->GetSamplingInterval(), 32768); // abnormal params of params.sub-key=["samplingInterval":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"samplingInterval":true}})"; - startSamplingData = StartSamplingParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(startSamplingData, nullptr); // abnormal params of params.sub-key=["samplingInterval":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"samplingInterval":"Test"}})"; - startSamplingData = StartSamplingParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(startSamplingData, nullptr); // abnormal params of params.sub-key = [ "size"=100,"nodeId"=1,"ordinal"=10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"samplingInterval":1000}})"; - startSamplingData = StartSamplingParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(startSamplingData, nullptr); EXPECT_EQ(startSamplingData->GetSamplingInterval(), 1000); } @@ -132,41 +122,31 @@ HWTEST_F_L0(DebuggerParamsTest, StartTrackingHeapObjectsParamsCreateTest) std::string msg; std::unique_ptr objectData; - // abnormal params of null msg - msg = std::string() + R"({})"; - objectData = StartTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of unexist key params - msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = StartTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = StartTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_FALSE(objectData->GetTrackAllocations()); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = StartTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_FALSE(objectData->GetTrackAllocations()); // abnormal params of params.sub-key=["trackAllocations":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"trackAllocations":10}})"; - objectData = StartTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["trackAllocations":"Test"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"trackAllocations":"Test"}})"; - objectData = StartTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["trackAllocations":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"trackAllocations":true}})"; - objectData = StartTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_TRUE(objectData->GetTrackAllocations()); } @@ -176,19 +156,9 @@ HWTEST_F_L0(DebuggerParamsTest, StopTrackingHeapObjectsParamsCreateTest) std::string msg; std::unique_ptr objectData; - // abnormal params of null msg - msg = std::string() + R"({})"; - objectData = StopTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of unexist key params - msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = StopTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = StopTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_FALSE(objectData->GetReportProgress()); ASSERT_FALSE(objectData->GetTreatGlobalObjectsAsRoots()); @@ -196,7 +166,7 @@ HWTEST_F_L0(DebuggerParamsTest, StopTrackingHeapObjectsParamsCreateTest) // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = StopTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_FALSE(objectData->GetReportProgress()); ASSERT_FALSE(objectData->GetTreatGlobalObjectsAsRoots()); @@ -206,21 +176,21 @@ HWTEST_F_L0(DebuggerParamsTest, StopTrackingHeapObjectsParamsCreateTest) "reportProgress":10, "treatGlobalObjectsAsRoots":10, "captureNumericValue":10}})"; - objectData = StopTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "reportProgress":"Test", "treatGlobalObjectsAsRoots":"Test", "captureNumericValue":"Test"}})"; - objectData = StopTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "reportProgress":true, "treatGlobalObjectsAsRoots":true, "captureNumericValue":true}})"; - objectData = StopTrackingHeapObjectsParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_TRUE(objectData->GetReportProgress()); ASSERT_TRUE(objectData->GetTreatGlobalObjectsAsRoots()); @@ -234,39 +204,39 @@ HWTEST_F_L0(DebuggerParamsTest, AddInspectedHeapObjectParamsCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - objectData = AddInspectedHeapObjectParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = AddInspectedHeapObjectParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = AddInspectedHeapObjectParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = AddInspectedHeapObjectParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["heapObjectId":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"heapObjectId":10}})"; - objectData = AddInspectedHeapObjectParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["heapObjectId":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"heapObjectId":true}})"; - objectData = AddInspectedHeapObjectParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["heapObjectId":“10”] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"heapObjectId":"10"}})"; - objectData = AddInspectedHeapObjectParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); - EXPECT_EQ((int)objectData->GetHeapObjectId(), 10); + EXPECT_EQ(objectData->GetHeapObjectId(), 10); } HWTEST_F_L0(DebuggerParamsTest, GetHeapObjectIdParamsCreateTest) @@ -274,39 +244,19 @@ HWTEST_F_L0(DebuggerParamsTest, GetHeapObjectIdParamsCreateTest) std::string msg; std::unique_ptr objectData; - // abnormal params of null msg - msg = std::string() + R"({})"; - objectData = GetHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of unexist key params - msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = GetHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of null params.sub-key - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = GetHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of unknown params.sub-key - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = GetHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - // abnormal params of params.sub-key=["objectId":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":10}})"; - objectData = GetHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = GetHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["objectId":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":true}})"; - objectData = GetHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = GetHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["objectId":“10”] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":"10"}})"; - objectData = GetHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = GetHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ((int)objectData->GetObjectId(), 10); } @@ -316,45 +266,25 @@ HWTEST_F_L0(DebuggerParamsTest, GetObjectByHeapObjectIdParamsCreateTest) std::string msg; std::unique_ptr objectData; - // abnormal params of null msg - msg = std::string() + R"({})"; - objectData = GetObjectByHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of unexist key params - msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = GetObjectByHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of null params.sub-key - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = GetObjectByHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of unknown params.sub-key - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = GetObjectByHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - // abnormal params of params.sub-key=["objectId":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":10}})"; - objectData = GetObjectByHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["objectId":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":"10", "objectGroup":10}})"; - objectData = GetObjectByHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["objectId":“10”] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":"10"}})"; - objectData = GetObjectByHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ((int)objectData->GetObjectId(), 10); ASSERT_FALSE(objectData->HasObjectGroup()); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":"10", "objectGroup":"groupname"}})"; - objectData = GetObjectByHeapObjectIdParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ((int)objectData->GetObjectId(), 10); EXPECT_EQ(objectData->GetObjectGroup(), "groupname"); @@ -365,45 +295,35 @@ HWTEST_F_L0(DebuggerParamsTest, StartPreciseCoverageParamCreateTest) std::string msg; std::unique_ptr objectData; - // abnormal params of null msg - msg = std::string() + R"({})"; - objectData = StartPreciseCoverageParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - - // abnormal params of unexist key params - msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = StartPreciseCoverageParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - EXPECT_EQ(objectData, nullptr); - // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = StartPreciseCoverageParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = StartPreciseCoverageParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "callCount":8, "detailed":8, "allowTriggeredUpdates":8}})"; - objectData = StartPreciseCoverageParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "callCount":"Test", "detailed":"Test", "allowTriggeredUpdates":"Test"}})"; - objectData = StartPreciseCoverageParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "callCount":true, "detailed":true, "allowTriggeredUpdates":true}})"; - objectData = StartPreciseCoverageParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_TRUE(objectData->GetCallCount()); ASSERT_TRUE(objectData->GetDetailed()); @@ -417,31 +337,31 @@ HWTEST_F_L0(DebuggerParamsTest, SetSamplingIntervalParamsCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - objectData = SetSamplingIntervalParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = SetSamplingIntervalParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = SetSamplingIntervalParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = SetSamplingIntervalParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "interval":"500"}})"; - objectData = SetSamplingIntervalParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"interval":500}})"; - objectData = SetSamplingIntervalParams::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ(objectData->GetInterval(), 500); } -- Gitee From d45530583a16aa9ef693e1c2bcf2050b881d9067 Mon Sep 17 00:00:00 2001 From: wengchangcheng Date: Mon, 13 Jun 2022 22:40:45 +0800 Subject: [PATCH 018/154] Descriptor: debugger refactor of independent js_runtime [ part-4 ] details: 1. Add PtBaseReturns::ToJson 2. Add PtBaseEvents::ToJson issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5C3FS Signed-off-by: wengchangcheng Change-Id: Ic8028d79f62b91724f22c63e8062d57367b5f27e --- ecmascript/dfx/hprof/heap_snapshot.cpp | 20 +- ecmascript/dfx/hprof/heap_snapshot.h | 12 +- .../tooling/agent/heapprofiler_impl.cpp | 12 +- ecmascript/tooling/agent/heapprofiler_impl.h | 12 +- ecmascript/tooling/base/pt_events.cpp | 249 +++++++++++++++ ecmascript/tooling/base/pt_events.h | 33 +- ecmascript/tooling/base/pt_params.cpp | 2 +- ecmascript/tooling/base/pt_returns.cpp | 300 +++++++++++++++++- ecmascript/tooling/base/pt_returns.h | 32 +- ecmascript/tooling/interface/file_stream.cpp | 8 +- ecmascript/tooling/interface/file_stream.h | 12 +- ecmascript/tooling/interface/stream.h | 14 +- .../tooling/test/debugger_events_test.cpp | 2 +- .../tooling/test/debugger_returns_test.cpp | 4 +- 14 files changed, 639 insertions(+), 73 deletions(-) diff --git a/ecmascript/dfx/hprof/heap_snapshot.cpp b/ecmascript/dfx/hprof/heap_snapshot.cpp index ddb448c3..5925e57c 100644 --- a/ecmascript/dfx/hprof/heap_snapshot.cpp +++ b/ecmascript/dfx/hprof/heap_snapshot.cpp @@ -136,16 +136,16 @@ void HeapSnapshot::PushHeapStat(Stream* stream) LOG(ERROR, DEBUGGER) << "HeapSnapshot::PushHeapStat::stream is nullptr"; return; } - int preChunkSize = stream->GetSize(); - uint32_t sequenceId = 0; + int32_t preChunkSize = stream->GetSize(); + int32_t sequenceId = 0; auto iter = nodes_.begin(); for (size_t timeIndex = 0; timeIndex < timeStamps_.size(); ++timeIndex) { TimeStamp& timeStamp = timeStamps_[timeIndex]; - sequenceId = static_cast(timeStamp.GetLastSequenceId()); - uint32_t nodesSize = 0; - uint32_t nodesCount = 0; + sequenceId = timeStamp.GetLastSequenceId(); + int32_t nodesSize = 0; + int32_t nodesCount = 0; - while (iter != nodes_.end() && (*iter)->GetId() <= sequenceId) { + while (iter != nodes_.end() && (*iter)->GetId() <= static_cast(sequenceId)) { nodesCount++; nodesSize += (*iter)->GetSelfSize(); iter++; @@ -154,16 +154,16 @@ void HeapSnapshot::PushHeapStat(Stream* stream) && ((nodesCount != 0) && (nodesSize != 0))) { timeStamp.SetCount(nodesCount); timeStamp.SetSize(nodesSize); - statsBuffer.emplace_back(static_cast(timeIndex), nodesCount, nodesSize); - if (static_cast(statsBuffer.size()) >= preChunkSize) { - stream->UpdateHeapStats(&statsBuffer.front(), static_cast(statsBuffer.size())); + statsBuffer.emplace_back(static_cast(timeIndex), nodesCount, nodesSize); + if (static_cast(statsBuffer.size()) >= preChunkSize) { + stream->UpdateHeapStats(&statsBuffer.front(), static_cast(statsBuffer.size())); statsBuffer.clear(); } } } if (!statsBuffer.empty()) { - stream->UpdateHeapStats(&statsBuffer.front(), static_cast(statsBuffer.size())); + stream->UpdateHeapStats(&statsBuffer.front(), static_cast(statsBuffer.size())); statsBuffer.clear(); } stream->UpdateLastSeenObjectId(sequenceId); diff --git a/ecmascript/dfx/hprof/heap_snapshot.h b/ecmascript/dfx/hprof/heap_snapshot.h index 5f95f766..61b0e15c 100644 --- a/ecmascript/dfx/hprof/heap_snapshot.h +++ b/ecmascript/dfx/hprof/heap_snapshot.h @@ -197,22 +197,22 @@ public: return timeStampUs_; } - uint32_t GetSize() const + int32_t GetSize() const { return size_; } - void SetSize(uint32_t size) + void SetSize(int32_t size) { size_ = size; } - uint32_t GetCount() const + int32_t GetCount() const { return count_; } - void SetCount(uint32_t count) + void SetCount(int32_t count) { count_ = count; } @@ -228,8 +228,8 @@ private: int lastSequenceId_ {0}; int64_t timeStampUs_ {0}; - uint32_t size_ {0}; - uint32_t count_ {0}; + int32_t size_ {0}; + int32_t count_ {0}; }; class HeapEntryMap { diff --git a/ecmascript/tooling/agent/heapprofiler_impl.cpp b/ecmascript/tooling/agent/heapprofiler_impl.cpp index cd99f1e8..abf5aa9f 100644 --- a/ecmascript/tooling/agent/heapprofiler_impl.cpp +++ b/ecmascript/tooling/agent/heapprofiler_impl.cpp @@ -168,7 +168,7 @@ bool HeapProfilerImpl::Frontend::AllowNotify() const return channel_ != nullptr; } -void HeapProfilerImpl::Frontend::AddHeapSnapshotChunk(char *data, int size) +void HeapProfilerImpl::Frontend::AddHeapSnapshotChunk(char *data, int32_t size) { if (!AllowNotify()) { return; @@ -176,7 +176,7 @@ void HeapProfilerImpl::Frontend::AddHeapSnapshotChunk(char *data, int size) tooling::AddHeapSnapshotChunk addHeapSnapshotChunk; addHeapSnapshotChunk.GetChunk().resize(size); - for (int i = 0; i < size; ++i) { + for (int32_t i = 0; i < size; ++i) { addHeapSnapshotChunk.GetChunk()[i] = data[i]; } @@ -197,13 +197,13 @@ void HeapProfilerImpl::Frontend::ReportHeapSnapshotProgress(int32_t done, int32_ channel_->SendNotification(reportHeapSnapshotProgress); } -void HeapProfilerImpl::Frontend::HeapStatsUpdate(HeapStat* updateData, int count) +void HeapProfilerImpl::Frontend::HeapStatsUpdate(HeapStat* updateData, int32_t count) { if (!AllowNotify()) { return; } - std::vector statsDiff; - for (int i = 0; i < count; ++i) { + std::vector statsDiff; + for (int32_t i = 0; i < count; ++i) { statsDiff.emplace_back(updateData[i].index_); statsDiff.emplace_back(updateData[i].count_); statsDiff.emplace_back(updateData[i].size_); @@ -213,7 +213,7 @@ void HeapProfilerImpl::Frontend::HeapStatsUpdate(HeapStat* updateData, int count channel_->SendNotification(heapStatsUpdate); } -void HeapProfilerImpl::Frontend::LastSeenObjectId(uint32_t lastSeenObjectId) +void HeapProfilerImpl::Frontend::LastSeenObjectId(int32_t lastSeenObjectId) { if (!AllowNotify()) { return; diff --git a/ecmascript/tooling/agent/heapprofiler_impl.h b/ecmascript/tooling/agent/heapprofiler_impl.h index a5c2bc60..e74e6241 100644 --- a/ecmascript/tooling/agent/heapprofiler_impl.h +++ b/ecmascript/tooling/agent/heapprofiler_impl.h @@ -89,10 +89,10 @@ private: public: explicit Frontend(ProtocolChannel *channel) : channel_(channel) {} - void AddHeapSnapshotChunk(char *data, int size); + void AddHeapSnapshotChunk(char *data, int32_t size); void ReportHeapSnapshotProgress(int32_t done, int32_t total); - void HeapStatsUpdate(HeapStat* updateData, int count); - void LastSeenObjectId(uint32_t lastSeenObjectId); + void HeapStatsUpdate(HeapStat* updateData, int32_t count); + void LastSeenObjectId(int32_t lastSeenObjectId); void ResetProfiles(); private: @@ -112,7 +112,7 @@ private: static const int heapProfilerChunkSise = 102400; return heapProfilerChunkSise; } - bool WriteChunk(char *data, int size) override + bool WriteChunk(char *data, int32_t size) override { if (!Good()) { return false; @@ -125,7 +125,7 @@ private: return frontend_ != nullptr; } - void UpdateHeapStats(HeapStat* updateData, int count) override + void UpdateHeapStats(HeapStat* updateData, int32_t count) override { if (!Good()) { return; @@ -133,7 +133,7 @@ private: frontend_->HeapStatsUpdate(updateData, count); } - void UpdateLastSeenObjectId(uint32_t lastSeenObjectId) override + void UpdateLastSeenObjectId(int32_t lastSeenObjectId) override { if (!Good()) { return; diff --git a/ecmascript/tooling/base/pt_events.cpp b/ecmascript/tooling/base/pt_events.cpp index e22aa306..4dffbd22 100644 --- a/ecmascript/tooling/base/pt_events.cpp +++ b/ecmascript/tooling/base/pt_events.cpp @@ -86,6 +86,35 @@ Local Paused::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr Paused::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = callFrames_.size(); + for (size_t i = 0; i < len; i++) { + array->Push(callFrames_[i]->ToJson()); + } + result->Add("callFrames", array); + result->Add("reason", reason_.c_str()); + if (data_) { + result->Add("data", data_.value()->ToJson()); + } + if (hitBreakpoints_) { + std::unique_ptr breakpoints = PtJson::CreateArray(); + len = hitBreakpoints_->size(); + for (size_t i = 0; i < len; i++) { + array->Push(hitBreakpoints_.value()[i].c_str()); + } + } + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local Resumed::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -99,6 +128,17 @@ Local Resumed::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr Resumed::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local ScriptFailedToParse::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -174,6 +214,47 @@ Local ScriptFailedToParse::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr ScriptFailedToParse::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("scriptId", std::to_string(scriptId_).c_str()); + result->Add("url", url_.c_str()); + result->Add("startLine", startLine_); + result->Add("startColumn", startColumn_); + result->Add("endLine", endLine_); + result->Add("endColumn", endColumn_); + result->Add("executionContextId", executionContextId_); + result->Add("hash", hash_.c_str()); + if (sourceMapUrl_) { + result->Add("sourceMapURL", sourceMapUrl_->c_str()); + } + if (hasSourceUrl_) { + result->Add("hasSourceURL", hasSourceUrl_.value()); + } + if (isModule_) { + result->Add("isModule", isModule_.value()); + } + if (length_) { + result->Add("length", length_.value()); + } + if (codeOffset_) { + result->Add("codeOffset", codeOffset_.value()); + } + if (scriptLanguage_) { + result->Add("scriptLanguage", scriptLanguage_->c_str()); + } + if (embedderName_) { + result->Add("embedderName", embedderName_->c_str()); + } + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local ScriptParsed::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -253,6 +334,50 @@ Local ScriptParsed::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr ScriptParsed::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("scriptId", std::to_string(scriptId_).c_str()); + result->Add("url", url_.c_str()); + result->Add("startLine", startLine_); + result->Add("startColumn", startColumn_); + result->Add("endLine", endLine_); + result->Add("endColumn", endColumn_); + result->Add("executionContextId", executionContextId_); + result->Add("hash", hash_.c_str()); + if (isLiveEdit_) { + result->Add("isLiveEdit", isLiveEdit_.value()); + } + if (sourceMapUrl_) { + result->Add("sourceMapURL", sourceMapUrl_->c_str()); + } + if (hasSourceUrl_) { + result->Add("hasSourceURL", hasSourceUrl_.value()); + } + if (isModule_) { + result->Add("isModule", isModule_.value()); + } + if (length_) { + result->Add("length", length_.value()); + } + if (codeOffset_) { + result->Add("codeOffset", codeOffset_.value()); + } + if (scriptLanguage_) { + result->Add("scriptLanguage", scriptLanguage_->c_str()); + } + if (embedderName_) { + result->Add("embedderName", embedderName_->c_str()); + } + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local AddHeapSnapshotChunk::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -270,6 +395,19 @@ Local AddHeapSnapshotChunk::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr AddHeapSnapshotChunk::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("chunk", chunk_.c_str()); + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local ConsoleProfileFinished::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -298,6 +436,28 @@ Local ConsoleProfileFinished::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr ConsoleProfileFinished::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("id", id_.c_str()); + if (location_ != nullptr) { + result->Add("location", location_->ToJson()); + } + if (profile_ != nullptr) { + result->Add("profile", profile_->ToJson()); + } + if (title_) { + result->Add("title", title_->c_str()); + } + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local ConsoleProfileStarted::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -323,6 +483,25 @@ Local ConsoleProfileStarted::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr ConsoleProfileStarted::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("id", id_.c_str()); + if (location_ != nullptr) { + result->Add("location", location_->ToJson()); + } + if (title_) { + result->Add("title", title_->c_str()); + } + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local PreciseCoverageDeltaUpdate::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -349,6 +528,27 @@ Local PreciseCoverageDeltaUpdate::ToObject(const EcmaVM *ecmaVm) cons return object; } +std::unique_ptr PreciseCoverageDeltaUpdate::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("timestamp", timestamp_); + result->Add("occasion", occasion_.c_str()); + std::unique_ptr array = PtJson::CreateArray(); + size_t len = result_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr res = result_[i]->ToJson(); + array->Push(res); + } + result->Add("result", array); + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local HeapStatsUpdate::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -370,6 +570,24 @@ Local HeapStatsUpdate::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr HeapStatsUpdate::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = statsUpdate_.size(); + for (size_t i = 0; i < len; i++) { + array->Push(statsUpdate_[i]); + } + result->Add("statsUpdate", array); + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local LastSeenObjectId::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -388,6 +606,20 @@ Local LastSeenObjectId::ToObject(const EcmaVM *ecmaVm) const return object; } +std::unique_ptr LastSeenObjectId::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("lastSeenObjectId", lastSeenObjectId_); + result->Add("timestamp", timestamp_); + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} + Local ReportHeapSnapshotProgress::ToObject(const EcmaVM *ecmaVm) const { Local params = NewObject(ecmaVm); @@ -411,4 +643,21 @@ Local ReportHeapSnapshotProgress::ToObject(const EcmaVM *ecmaVm) cons return object; } + +std::unique_ptr ReportHeapSnapshotProgress::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("done", done_); + result->Add("total", total_); + if (finished_) { + result->Add("finished", finished_.value()); + } + + std::unique_ptr object = PtJson::CreateObject(); + object->Add("method", GetName().c_str()); + object->Add("params", result); + + return object; +} } // namespace panda::ecmascript::tooling diff --git a/ecmascript/tooling/base/pt_events.h b/ecmascript/tooling/base/pt_events.h index 5044ff87..8e929052 100644 --- a/ecmascript/tooling/base/pt_events.h +++ b/ecmascript/tooling/base/pt_events.h @@ -84,6 +84,7 @@ public: Paused() = default; ~Paused() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -208,6 +209,7 @@ public: Resumed() = default; ~Resumed() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -224,6 +226,7 @@ public: ScriptFailedToParse() = default; ~ScriptFailedToParse() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -476,6 +479,7 @@ public: ScriptParsed() = default; ~ScriptParsed() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -651,12 +655,12 @@ public: return isModule_.has_value(); } - uint32_t GetLength() const + int32_t GetLength() const { return length_.value_or(0); } - ScriptParsed &SetLength(uint32_t length) + ScriptParsed &SetLength(int32_t length) { length_ = length; return *this; @@ -667,12 +671,12 @@ public: return length_.has_value(); } - uint32_t GetCodeOffset() const + int32_t GetCodeOffset() const { return codeOffset_.value_or(0); } - ScriptParsed &SetCodeOffset(uint32_t codeOffset) + ScriptParsed &SetCodeOffset(int32_t codeOffset) { codeOffset_ = codeOffset; return *this; @@ -734,8 +738,8 @@ private: std::optional sourceMapUrl_ {}; std::optional hasSourceUrl_ {}; std::optional isModule_ {}; - std::optional length_ {}; - std::optional codeOffset_ {}; + std::optional length_ {}; + std::optional codeOffset_ {}; std::optional scriptLanguage_ {}; std::optional embedderName_ {}; }; @@ -745,6 +749,7 @@ public: AddHeapSnapshotChunk() = default; ~AddHeapSnapshotChunk() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -768,6 +773,7 @@ public: ConsoleProfileFinished() = default; ~ConsoleProfileFinished() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { return "Profile.ConsoleProfileFinished"; @@ -838,6 +844,7 @@ public: ConsoleProfileStarted() = default; ~ConsoleProfileStarted() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { return "Profile.ConsoleProfileStarted"; @@ -896,6 +903,7 @@ public: PreciseCoverageDeltaUpdate() = default; ~PreciseCoverageDeltaUpdate() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { return "Profile.PreciseCoverageDeltaUpdate"; @@ -948,18 +956,19 @@ public: HeapStatsUpdate() = default; ~HeapStatsUpdate() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { return "HeapProfiler.heapStatsUpdate"; } - const std::vector *GetStatsUpdate() const + const std::vector *GetStatsUpdate() const { return &statsUpdate_; } - HeapStatsUpdate &SetStatsUpdate(std::vector statsUpdate) + HeapStatsUpdate &SetStatsUpdate(std::vector statsUpdate) { statsUpdate_ = std::move(statsUpdate); return *this; @@ -969,7 +978,7 @@ private: NO_COPY_SEMANTIC(HeapStatsUpdate); NO_MOVE_SEMANTIC(HeapStatsUpdate); - std::vector statsUpdate_ {}; + std::vector statsUpdate_ {}; }; class LastSeenObjectId final : public PtBaseEvents { @@ -977,6 +986,7 @@ public: LastSeenObjectId() = default; ~LastSeenObjectId() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -988,7 +998,7 @@ public: return lastSeenObjectId_; } - LastSeenObjectId &SetLastSeenObjectId(uint32_t lastSeenObjectId) + LastSeenObjectId &SetLastSeenObjectId(int32_t lastSeenObjectId) { lastSeenObjectId_ = lastSeenObjectId; return *this; @@ -1009,7 +1019,7 @@ private: NO_COPY_SEMANTIC(LastSeenObjectId); NO_MOVE_SEMANTIC(LastSeenObjectId); - uint32_t lastSeenObjectId_ {}; + int32_t lastSeenObjectId_ {}; int64_t timestamp_ {}; }; @@ -1018,6 +1028,7 @@ public: ReportHeapSnapshotProgress() = default; ~ReportHeapSnapshotProgress() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; std::string GetName() const override { diff --git a/ecmascript/tooling/base/pt_params.cpp b/ecmascript/tooling/base/pt_params.cpp index 1ebfe9e3..35fff8e1 100644 --- a/ecmascript/tooling/base/pt_params.cpp +++ b/ecmascript/tooling/base/pt_params.cpp @@ -257,7 +257,7 @@ std::unique_ptr SetBlackboxPatternsParams::Create(con if (item->IsString()) { paramsObject->patterns_.emplace_back(item->GetString()); } else { - error += "'patterns' items should be a String;"; + error += "'patterns' items should be a String;"; } } } else { diff --git a/ecmascript/tooling/base/pt_returns.cpp b/ecmascript/tooling/base/pt_returns.cpp index e3b36fb4..bba89d4e 100644 --- a/ecmascript/tooling/base/pt_returns.cpp +++ b/ecmascript/tooling/base/pt_returns.cpp @@ -54,6 +54,22 @@ Local SetBreakpointByUrlReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr SetBreakpointByUrlReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("breakpointId", id_.c_str()); + std::unique_ptr array = PtJson::CreateArray(); + size_t len = locations_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr location = locations_[i]->ToJson(); + array->Push(location); + } + result->Add("locations", array); + + return result; +} + Local EvaluateOnCallFrameReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -70,6 +86,20 @@ Local EvaluateOnCallFrameReturns::ToObject(const EcmaVM *ecmaVm) cons return result; } +std::unique_ptr EvaluateOnCallFrameReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + if (result_ != nullptr) { + result->Add("result", result_->ToJson()); + } + if (exceptionDetails_ && exceptionDetails_.value() != nullptr) { + result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); + } + + return result; +} + Local GetPossibleBreakpointsReturns::ToObject(const EcmaVM *ecmaVm) const { size_t len = locations_.size(); @@ -85,6 +115,21 @@ Local GetPossibleBreakpointsReturns::ToObject(const EcmaVM *ecmaVm) c return result; } +std::unique_ptr GetPossibleBreakpointsReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = locations_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr location = locations_[i]->ToJson(); + array->Push(location); + } + result->Add("locations", array); + + return result; +} + Local GetScriptSourceReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -101,6 +146,18 @@ Local GetScriptSourceReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr GetScriptSourceReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("scriptSource", scriptSource_.c_str()); + if (bytecode_) { + result->Add("bytecode", bytecode_->c_str()); + } + + return result; +} + Local RestartFrameReturns::ToObject(const EcmaVM *ecmaVm) const { size_t len = callFrames_.size(); @@ -115,13 +172,28 @@ Local RestartFrameReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr RestartFrameReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = callFrames_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr location = callFrames_[i]->ToJson(); + array->Push(location); + } + result->Add("callFrames", array); + + return result; +} + Local SearchInContentReturns::ToObject(const EcmaVM *ecmaVm) const { size_t len = result_.size(); Local values = ArrayRef::New(ecmaVm, len); for (size_t i = 0; i < len; i++) { - Local location = result_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, location); + Local res = result_[i]->ToObject(ecmaVm); + values->Set(ecmaVm, i, res); } Local result = NewObject(ecmaVm); @@ -130,6 +202,21 @@ Local SearchInContentReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr SearchInContentReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = result_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr res = result_[i]->ToJson(); + array->Push(res); + } + result->Add("result", array); + + return result; +} + Local SetBreakpointReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -145,6 +232,18 @@ Local SetBreakpointReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr SetBreakpointReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("breakpointId", breakpointId_.c_str()); + if (location_ != nullptr) { + result->Add("actualLocation", location_->ToJson()); + } + + return result; +} + Local SetInstrumentationBreakpointReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -156,6 +255,15 @@ Local SetInstrumentationBreakpointReturns::ToObject(const EcmaVM *ecm return result; } +std::unique_ptr SetInstrumentationBreakpointReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("breakpointId", breakpointId_.c_str()); + + return result; +} + Local SetScriptSourceReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -186,6 +294,29 @@ Local SetScriptSourceReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr SetScriptSourceReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + if (callFrames_) { + std::unique_ptr array = PtJson::CreateArray(); + size_t len = callFrames_->size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr location = callFrames_.value()[i]->ToJson(); + array->Push(location); + } + result->Add("callFrames", array); + } + if (stackChanged_) { + result->Add("stackChanged", stackChanged_.value()); + } + if (exceptionDetails_ && exceptionDetails_.value() != nullptr) { + result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); + } + + return result; +} + Local GetPropertiesReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -226,6 +357,42 @@ Local GetPropertiesReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr GetPropertiesReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = result_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr location = result_[i]->ToJson(); + array->Push(location); + } + result->Add("result", array); + if (internalPropertyDescripties_) { + array = PtJson::CreateArray(); + len = internalPropertyDescripties_->size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr location = internalPropertyDescripties_.value()[i]->ToJson(); + array->Push(location); + } + result->Add("internalProperties", array); + } + if (privateProperties_) { + array = PtJson::CreateArray(); + len = privateProperties_->size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr location = privateProperties_.value()[i]->ToJson(); + array->Push(location); + } + result->Add("privateProperties", array); + } + if (exceptionDetails_ && exceptionDetails_.value() != nullptr) { + result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); + } + + return result; +} + Local CallFunctionOnReturns::ToObject(const EcmaVM *ecmaVm) const { // For this @@ -244,6 +411,20 @@ Local CallFunctionOnReturns::ToObject(const EcmaVM *ecmaVm) const return returns; } +std::unique_ptr CallFunctionOnReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + if (result_ != nullptr) { + result->Add("result", result_->ToJson()); + } + if (exceptionDetails_ && exceptionDetails_.value() != nullptr) { + result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); + } + + return result; +} + Local StopSamplingReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -256,6 +437,17 @@ Local StopSamplingReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr StopSamplingReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + if (profile_ != nullptr) { + result->Add("profile", profile_->ToJson()); + } + + return result; +} + Local GetHeapObjectIdReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -267,6 +459,15 @@ Local GetHeapObjectIdReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr GetHeapObjectIdReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("heapSnapshotObjectId", std::to_string(heapSnapshotObjectId_).c_str()); + + return result; +} + Local GetObjectByHeapObjectIdReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -280,6 +481,17 @@ Local GetObjectByHeapObjectIdReturns::ToObject(const EcmaVM *ecmaVm) return result; } +std::unique_ptr GetObjectByHeapObjectIdReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + if (remoteObjectResult_ != nullptr) { + result->Add("result", remoteObjectResult_->ToJson()); + } + + return result; +} + Local StopReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -290,6 +502,17 @@ Local StopReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr StopReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + if (profile_ != nullptr) { + result->Add("profile", profile_->ToJson()); + } + + return result; +} + Local GetHeapUsageReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -304,6 +527,16 @@ Local GetHeapUsageReturns::ToObject(const EcmaVM *ecmaVm) const return result; } +std::unique_ptr GetHeapUsageReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("usedSize", usedSize_); + result->Add("totalSize", totalSize_); + + return result; +} + Local GetBestEffortCoverageReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -319,6 +552,21 @@ Local GetBestEffortCoverageReturns::ToObject(const EcmaVM *ecmaVm) co return result; } +std::unique_ptr GetBestEffortCoverageReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = result_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr scriptCoverage = result_[i]->ToJson(); + array->Push(scriptCoverage); + } + result->Add("result", array); + + return result; +} + Local StartPreciseCoverageReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -328,6 +576,15 @@ Local StartPreciseCoverageReturns::ToObject(const EcmaVM *ecmaVm) con return result; } +std::unique_ptr StartPreciseCoverageReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("timestamp", timestamp_); + + return result; +} + Local TakePreciseCoverageReturns::ToObject(const EcmaVM *ecmaVm) const { Local returns = NewObject(ecmaVm); @@ -339,15 +596,29 @@ Local TakePreciseCoverageReturns::ToObject(const EcmaVM *ecmaVm) cons values->Set(ecmaVm, i, scriptCoverage); } returns->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), values); - if (timestamp_) { - returns->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "timestamp")), - NumberRef::New(ecmaVm, timestamp_)); - } + returns->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "timestamp")), + NumberRef::New(ecmaVm, timestamp_)); return returns; } -Local TakeTypeProfileturns::ToObject(const EcmaVM *ecmaVm) const +std::unique_ptr TakePreciseCoverageReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = result_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr scriptTypeProfile = result_[i]->ToJson(); + array->Push(scriptTypeProfile); + } + result->Add("result", array); + result->Add("timestamp", timestamp_); + + return result; +} + +Local TakeTypeProfileReturns::ToObject(const EcmaVM *ecmaVm) const { Local result = NewObject(ecmaVm); @@ -360,4 +631,19 @@ Local TakeTypeProfileturns::ToObject(const EcmaVM *ecmaVm) const result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), values); return result; } + +std::unique_ptr TakeTypeProfileReturns::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + std::unique_ptr array = PtJson::CreateArray(); + size_t len = result_.size(); + for (size_t i = 0; i < len; i++) { + std::unique_ptr scriptTypeProfile = result_[i]->ToJson(); + array->Push(scriptTypeProfile); + } + result->Add("result", array); + + return result; +} } // namespace panda::ecmascript::tooling \ No newline at end of file diff --git a/ecmascript/tooling/base/pt_returns.h b/ecmascript/tooling/base/pt_returns.h index 69231a6c..6c46925d 100644 --- a/ecmascript/tooling/base/pt_returns.h +++ b/ecmascript/tooling/base/pt_returns.h @@ -62,6 +62,7 @@ public: ~SetBreakpointByUrlReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: SetBreakpointByUrlReturns() = default; @@ -80,6 +81,7 @@ public: {} ~EvaluateOnCallFrameReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: EvaluateOnCallFrameReturns() = default; @@ -98,6 +100,7 @@ public: ~GetPossibleBreakpointsReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: GetPossibleBreakpointsReturns() = default; @@ -115,6 +118,7 @@ public: ~GetScriptSourceReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: GetScriptSourceReturns() = default; @@ -132,6 +136,7 @@ public: {} ~RestartFrameReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: RestartFrameReturns() = default; @@ -147,6 +152,7 @@ public: {} ~SearchInContentReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: SearchInContentReturns() = default; @@ -163,6 +169,7 @@ public: {} ~SetBreakpointReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: SetBreakpointReturns() = default; @@ -178,6 +185,7 @@ public: {} ~SetInstrumentationBreakpointReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: SetInstrumentationBreakpointReturns() = default; @@ -198,6 +206,7 @@ public: {} ~SetScriptSourceReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: SetScriptSourceReturns() = default; @@ -222,6 +231,7 @@ public: {} ~GetPropertiesReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: GetPropertiesReturns() = default; @@ -243,6 +253,7 @@ public: {} ~CallFunctionOnReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: CallFunctionOnReturns() = default; @@ -261,6 +272,7 @@ public: ~StopSamplingReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: StopSamplingReturns() = default; @@ -278,6 +290,7 @@ public: ~GetHeapObjectIdReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: GetHeapObjectIdReturns() = default; @@ -295,6 +308,7 @@ public: ~GetObjectByHeapObjectIdReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: GetObjectByHeapObjectIdReturns() = default; @@ -309,6 +323,7 @@ public: explicit StopReturns(std::unique_ptr profile) : profile_(std::move(profile)) {} ~StopReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: StopReturns() = default; @@ -324,6 +339,7 @@ public: : usedSize_(usedSize), totalSize_(totalSize) {} ~GetHeapUsageReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: GetHeapUsageReturns() = default; @@ -341,6 +357,7 @@ public: {} ~GetBestEffortCoverageReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: GetBestEffortCoverageReturns() = default; @@ -355,6 +372,7 @@ public: explicit StartPreciseCoverageReturns(int64_t tamp) : timestamp_(tamp) {} ~StartPreciseCoverageReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: StartPreciseCoverageReturns() = default; @@ -372,6 +390,7 @@ public: {} ~TakePreciseCoverageReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: TakePreciseCoverageReturns() = default; @@ -382,18 +401,19 @@ private: int64_t timestamp_ {0}; }; -class TakeTypeProfileturns : public PtBaseReturns { +class TakeTypeProfileReturns : public PtBaseReturns { public: - explicit TakeTypeProfileturns(std::vector> result) + explicit TakeTypeProfileReturns(std::vector> result) : result_(std::move(result)) {} - ~TakeTypeProfileturns() override = default; + ~TakeTypeProfileReturns() override = default; Local ToObject(const EcmaVM *ecmaVm) const override; + std::unique_ptr ToJson() const override; private: - TakeTypeProfileturns() = default; - NO_COPY_SEMANTIC(TakeTypeProfileturns); - NO_MOVE_SEMANTIC(TakeTypeProfileturns); + TakeTypeProfileReturns() = default; + NO_COPY_SEMANTIC(TakeTypeProfileReturns); + NO_MOVE_SEMANTIC(TakeTypeProfileReturns); std::vector> result_ {}; }; diff --git a/ecmascript/tooling/interface/file_stream.cpp b/ecmascript/tooling/interface/file_stream.cpp index 6c02144b..48bc240f 100644 --- a/ecmascript/tooling/interface/file_stream.cpp +++ b/ecmascript/tooling/interface/file_stream.cpp @@ -69,7 +69,7 @@ std::pair FileStream::FilePathValid(const std::string &fileNa } // Writes the chunk of data into the stream -bool FileStream::WriteChunk(char *data, int size) +bool FileStream::WriteChunk(char *data, int32_t size) { if (fileStream_.fail()) { return false; @@ -77,7 +77,7 @@ bool FileStream::WriteChunk(char *data, int size) std::string str; str.resize(size); - for (int i = 0; i < size; ++i) { + for (int32_t i = 0; i < size; ++i) { str[i] = data[i]; } @@ -99,7 +99,7 @@ bool FileDescriptorStream::Good() } // Writes the chunk of data into the stream -bool FileDescriptorStream::WriteChunk(char *data, int size) +bool FileDescriptorStream::WriteChunk(char *data, int32_t size) { if (fd_ < 0) { return false; @@ -107,7 +107,7 @@ bool FileDescriptorStream::WriteChunk(char *data, int size) std::string str; str.resize(size); - for (int i = 0; i < size; ++i) { + for (int32_t i = 0; i < size; ++i) { str[i] = data[i]; } int ret = dprintf(fd_, "%s", str.c_str()); diff --git a/ecmascript/tooling/interface/file_stream.h b/ecmascript/tooling/interface/file_stream.h index 0f57f8f0..eba3c3e8 100644 --- a/ecmascript/tooling/interface/file_stream.h +++ b/ecmascript/tooling/interface/file_stream.h @@ -36,12 +36,12 @@ public: } // Writes the chunk of data into the stream - bool WriteChunk(char* data, int size) override; + bool WriteChunk(char* data, int32_t size) override; bool Good() override; - void UpdateHeapStats([[maybe_unused]]HeapStat* data, [[maybe_unused]]int count) override + void UpdateHeapStats([[maybe_unused]] HeapStat* data, [[maybe_unused]] int32_t count) override { } - void UpdateLastSeenObjectId([[maybe_unused]]uint32_t lastSeenObjectId) override + void UpdateLastSeenObjectId([[maybe_unused]] int32_t lastSeenObjectId) override { } @@ -67,12 +67,12 @@ public: } // Writes the chunk of data into the stream - bool WriteChunk(char *data, int size) override; + bool WriteChunk(char *data, int32_t size) override; bool Good() override; - void UpdateHeapStats([[maybe_unused]]HeapStat* data, [[maybe_unused]]int count) override + void UpdateHeapStats([[maybe_unused]] HeapStat* data, [[maybe_unused]] int32_t count) override { } - void UpdateLastSeenObjectId([[maybe_unused]]uint32_t lastSeenObjectId) override + void UpdateLastSeenObjectId([[maybe_unused]] int32_t lastSeenObjectId) override { } diff --git a/ecmascript/tooling/interface/stream.h b/ecmascript/tooling/interface/stream.h index 771895c3..cd7285b6 100644 --- a/ecmascript/tooling/interface/stream.h +++ b/ecmascript/tooling/interface/stream.h @@ -19,12 +19,12 @@ namespace panda::ecmascript { class HeapStat { public: - HeapStat(uint32_t index, uint32_t count, uint32_t size) + HeapStat(int32_t index, int32_t count, int32_t size) : index_(index), count_(count), size_(size) {} - uint32_t index_; - uint32_t count_; - uint32_t size_; + int32_t index_; + int32_t count_; + int32_t size_; }; class Stream { @@ -37,10 +37,10 @@ public: virtual int GetSize() = 0; // Writes the chunk of data into the stream - virtual bool WriteChunk(char *data, int size) = 0; + virtual bool WriteChunk(char *data, int32_t size) = 0; virtual bool Good() = 0; - virtual void UpdateHeapStats(HeapStat* data, int count) = 0; - virtual void UpdateLastSeenObjectId(uint32_t lastSeenObjectId) = 0; + virtual void UpdateHeapStats(HeapStat* data, int32_t count) = 0; + virtual void UpdateLastSeenObjectId(int32_t lastSeenObjectId) = 0; }; } // namespace panda::ecmascript diff --git a/ecmascript/tooling/test/debugger_events_test.cpp b/ecmascript/tooling/test/debugger_events_test.cpp index 175420a9..ff1f8e93 100644 --- a/ecmascript/tooling/test/debugger_events_test.cpp +++ b/ecmascript/tooling/test/debugger_events_test.cpp @@ -527,7 +527,7 @@ HWTEST_F_L0(DebuggerEventsTest, HeapStatsUpdateToObjectTest) HeapStatsUpdate heapStatsUpdate; Local tmpStr = StringRef::NewFromUtf8(ecmaVm, "params"); - heapStatsUpdate.SetStatsUpdate(std::vector {}); + heapStatsUpdate.SetStatsUpdate(std::vector {}); Local object1 = heapStatsUpdate.ToObject(ecmaVm); Local result = object1->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); diff --git a/ecmascript/tooling/test/debugger_returns_test.cpp b/ecmascript/tooling/test/debugger_returns_test.cpp index 1d60edf8..04cfa21d 100644 --- a/ecmascript/tooling/test/debugger_returns_test.cpp +++ b/ecmascript/tooling/test/debugger_returns_test.cpp @@ -372,8 +372,8 @@ HWTEST_F_L0(DebuggerReturnsTest, TakeTypeProfileturnsToObjectTest) { auto result = std::vector>(); std::unique_ptr scriptTypeProfile = std::make_unique(); - std::unique_ptr takeTypeProfileturns = std::make_unique - (std::move(result)); + std::unique_ptr takeTypeProfileturns = std::make_unique + (std::move(result)); Local getObject = takeTypeProfileturns->ToObject(ecmaVm); Local tmpStr = StringRef::NewFromUtf8(ecmaVm, "result"); ASSERT_TRUE(getObject->Has(ecmaVm, tmpStr)); -- Gitee From c5b6265496914d74da2d3d0c7ceef3186e7a913f Mon Sep 17 00:00:00 2001 From: wupengyong Date: Tue, 14 Jun 2022 20:19:18 +0800 Subject: [PATCH 019/154] reason:fix SetPropertyByValueWithOwn handler description:add InterpreterSetPropertyByValueWithOwn GHCcall issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CACE?from=project-issue Signed-off-by: wupengyong Change-Id: Ifdf8695f3318a67ddb3d2d10e859b5f55c2486a8 --- ecmascript/compiler/common_stubs.cpp | 66 +-------------------- ecmascript/compiler/interpreter_stub.cpp | 34 ++++------- ecmascript/compiler/stub.cpp | 75 ++++++++++++++++++++++++ ecmascript/compiler/stub.h | 1 + 4 files changed, 88 insertions(+), 88 deletions(-) diff --git a/ecmascript/compiler/common_stubs.cpp b/ecmascript/compiler/common_stubs.cpp index a60d577b..b6d5031e 100644 --- a/ecmascript/compiler/common_stubs.cpp +++ b/ecmascript/compiler/common_stubs.cpp @@ -229,72 +229,10 @@ void SetPropertyByNameWithOwnStub::GenerateCircuit(const CompilationConfig *cfg) void GetPropertyByValueStub::GenerateCircuit(const CompilationConfig *cfg) { Stub::GenerateCircuit(cfg); - auto env = GetEnvironment(); GateRef glue = PtrArgument(0); GateRef receiver = TaggedArgument(1); - DEFVARIABLE(key, VariableType::JS_ANY(), TaggedArgument(2)); /* 2 : 3rd parameter is key */ - - Label isNumberOrStringSymbol(env); - Label notNumber(env); - Label isStringOrSymbol(env); - Label notStringOrSymbol(env); - Label exit(env); - - Branch(TaggedIsNumber(*key), &isNumberOrStringSymbol, ¬Number); - Bind(¬Number); - { - Branch(TaggedIsStringOrSymbol(*key), &isNumberOrStringSymbol, ¬StringOrSymbol); - Bind(¬StringOrSymbol); - { - Return(Hole()); - } - } - Bind(&isNumberOrStringSymbol); - { - GateRef index = TryToElementsIndex(*key); - Label validIndex(env); - Label notValidIndex(env); - Branch(Int32GreaterThanOrEqual(index, Int32(0)), &validIndex, ¬ValidIndex); - Bind(&validIndex); - { - Return(GetPropertyByIndex(glue, receiver, index)); - } - Bind(¬ValidIndex); - { - Label notNumber1(env); - Label getByName(env); - Branch(TaggedIsNumber(*key), &exit, ¬Number1); - Bind(¬Number1); - { - Label isString(env); - Label notString(env); - Label isInternalString(env); - Label notIntenalString(env); - Branch(TaggedIsString(*key), &isString, ¬String); - Bind(&isString); - { - Branch(IsInternalString(*key), &isInternalString, ¬IntenalString); - Bind(&isInternalString); - Jump(&getByName); - Bind(¬IntenalString); - { - key = CallRuntime(glue, RTSTUB_ID(NewInternalString), { *key }); - Jump(&getByName); - } - } - Bind(¬String); - { - Jump(&getByName); - } - } - Bind(&getByName); - { - Return(GetPropertyByName(glue, receiver, *key)); - } - } - } - Bind(&exit); - Return(Hole()); + GateRef key = TaggedArgument(2); // 2 : 3rd para + Return(GetPropertyByValue(glue, receiver, key)); } void SetPropertyByValueStub::GenerateCircuit(const CompilationConfig *cfg) diff --git a/ecmascript/compiler/interpreter_stub.cpp b/ecmascript/compiler/interpreter_stub.cpp index bdcdd0b8..16833c6c 100644 --- a/ecmascript/compiler/interpreter_stub.cpp +++ b/ecmascript/compiler/interpreter_stub.cpp @@ -2491,9 +2491,7 @@ DECLARE_ASM_HANDLER(HandleLdObjByValuePrefV8V8) } Bind(&tryFastPath); { - GateRef result = CallStub(glue, - CommonStubCSigns::GetPropertyByValue, - { glue, receiver, propKey }); + GateRef result = GetPropertyByValue(glue, receiver, propKey); Label notHole(env); Branch(TaggedIsHole(result), &slowPath, ¬Hole); Bind(¬Hole); @@ -2590,9 +2588,7 @@ DECLARE_ASM_HANDLER(HandleStObjByValuePrefV8V8) } Bind(&tryFastPath); { - GateRef result = CallStub(glue, - CommonStubCSigns::SetPropertyByValue, - { glue, receiver, propKey, acc }); // acc is value + GateRef result = SetPropertyByValue(glue, receiver, propKey, acc, false); Label notHole(env); Branch(TaggedIsHole(result), &slowPath, ¬Hole); Bind(¬Hole); @@ -2635,8 +2631,7 @@ DECLARE_ASM_HANDLER(HandleStOwnByValuePrefV8V8) Bind(¬ClassPrototype); { // fast path - GateRef result = CallStub(glue, CommonStubCSigns::SetPropertyByValueWithOwn, - { glue, receiver, propKey, acc }); // acc is value + GateRef result = SetPropertyByValue(glue, receiver, propKey, acc, true); // acc is value Label notHole(env); Branch(TaggedIsHole(result), &slowPath, ¬Hole); Bind(¬Hole); @@ -2757,8 +2752,7 @@ DECLARE_ASM_HANDLER(HandleLdObjByIndexPrefV8Imm32) Branch(TaggedIsHeapObject(receiver), &fastPath, &slowPath); Bind(&fastPath); { - GateRef result = CallStub(glue, CommonStubCSigns::GetPropertyByIndex, - { glue, receiver, index }); + GateRef result = GetPropertyByIndex(glue, receiver, index); Label notHole(env); Branch(TaggedIsHole(result), &slowPath, ¬Hole); Bind(¬Hole); @@ -2800,8 +2794,7 @@ DECLARE_ASM_HANDLER(HandleStObjByIndexPrefV8Imm32) Branch(TaggedIsHeapObject(receiver), &fastPath, &slowPath); Bind(&fastPath); { - GateRef result = CallStub(glue, CommonStubCSigns::SetPropertyByIndex, - { glue, receiver, index, acc }); // acc is value + GateRef result = SetPropertyByIndex(glue, receiver, index, acc, false); Label notHole(env); Branch(TaggedIsHole(result), &slowPath, ¬Hole); Bind(¬Hole); @@ -2842,8 +2835,7 @@ DECLARE_ASM_HANDLER(HandleStOwnByIndexPrefV8Imm32) Bind(¬ClassPrototype); { // fast path - GateRef result = CallStub(glue, CommonStubCSigns::SetPropertyByIndexWithOwn, - { glue, receiver, index, acc }); // acc is value + GateRef result = SetPropertyByIndex(glue, receiver, index, acc, true); // acc is value Label notHole(env); Branch(TaggedIsHole(result), &slowPath, ¬Hole); Bind(¬Hole); @@ -3797,9 +3789,7 @@ DECLARE_ASM_HANDLER(HandleStObjByNamePrefId32V8) { GateRef stringId = ReadInst32_1(pc); GateRef propKey = GetValueFromTaggedArray(VariableType::JS_ANY(), constpool, stringId); - result = CallStub(glue, CommonStubCSigns::SetPropertyByName, { - glue, receiver, propKey, acc - }); + result = SetPropertyByName(glue, receiver, propKey, acc, false); Branch(TaggedIsHole(*result), &slowPath, &checkResult); } } @@ -3849,9 +3839,7 @@ DECLARE_ASM_HANDLER(HandleStOwnByValueWithNameSetPrefV8V8) Branch(IsClassPrototype(receiver), &slowPath, ¬ClassPrototype); Bind(¬ClassPrototype); { - GateRef res = CallStub(glue, - CommonStubCSigns::SetPropertyByValueWithOwn, - { glue, receiver, propKey, acc }); + GateRef res = SetPropertyByValue(glue, receiver, propKey, acc, true); Branch(TaggedIsHole(res), &slowPath, ¬Hole); Bind(¬Hole); { @@ -3903,8 +3891,7 @@ DECLARE_ASM_HANDLER(HandleStOwnByNamePrefId32V8) Branch(IsClassPrototype(receiver), &slowPath, &fastPath); Bind(&fastPath); { - result = CallStub(glue, CommonStubCSigns::SetPropertyByNameWithOwn, - { glue, receiver, propKey, acc }); + result = SetPropertyByName(glue, receiver, propKey, acc, true); Branch(TaggedIsHole(*result), &slowPath, &checkResult); } } @@ -3951,8 +3938,7 @@ DECLARE_ASM_HANDLER(HandleStOwnByNameWithNameSetPrefId32V8) Branch(IsClassPrototype(receiver), ¬JSObject, ¬ClassPrototype); Bind(¬ClassPrototype); { - GateRef res = CallStub(glue, CommonStubCSigns::SetPropertyByNameWithOwn, - { glue, receiver, propKey, acc }); + GateRef res = SetPropertyByName(glue, receiver, propKey, acc, true); Branch(TaggedIsHole(res), ¬JSObject, ¬Hole); Bind(¬Hole); { diff --git a/ecmascript/compiler/stub.cpp b/ecmascript/compiler/stub.cpp index ffcf0219..6e7f863b 100644 --- a/ecmascript/compiler/stub.cpp +++ b/ecmascript/compiler/stub.cpp @@ -1973,6 +1973,81 @@ GateRef Stub::GetPropertyByIndex(GateRef glue, GateRef receiver, GateRef index) return ret; } +GateRef Stub::GetPropertyByValue(GateRef glue, GateRef receiver, GateRef keyValue) +{ + auto env = GetEnvironment(); + Label entry(env); + env->SubCfgEntry(&entry); + DEFVARIABLE(key, VariableType::JS_ANY(), keyValue); + DEFVARIABLE(result, VariableType::JS_ANY(), Hole()); + Label isNumberOrStringSymbol(env); + Label notNumber(env); + Label isStringOrSymbol(env); + Label notStringOrSymbol(env); + Label exit(env); + + Branch(TaggedIsNumber(*key), &isNumberOrStringSymbol, ¬Number); + Bind(¬Number); + { + Branch(TaggedIsStringOrSymbol(*key), &isNumberOrStringSymbol, ¬StringOrSymbol); + Bind(¬StringOrSymbol); + { + result = Hole(); + Jump(&exit); + } + } + Bind(&isNumberOrStringSymbol); + { + GateRef index = TryToElementsIndex(*key); + Label validIndex(env); + Label notValidIndex(env); + Branch(Int32GreaterThanOrEqual(index, Int32(0)), &validIndex, ¬ValidIndex); + Bind(&validIndex); + { + result = GetPropertyByIndex(glue, receiver, index); + Jump(&exit); + } + Bind(¬ValidIndex); + { + Label notNumber1(env); + Label getByName(env); + Branch(TaggedIsNumber(*key), &exit, ¬Number1); + Bind(¬Number1); + { + Label isString(env); + Label notString(env); + Label isInternalString(env); + Label notIntenalString(env); + Branch(TaggedIsString(*key), &isString, ¬String); + Bind(&isString); + { + Branch(IsInternalString(*key), &isInternalString, ¬IntenalString); + Bind(&isInternalString); + Jump(&getByName); + Bind(¬IntenalString); + { + key = CallRuntime(glue, RTSTUB_ID(NewInternalString), { *key }); + Jump(&getByName); + } + } + Bind(¬String); + { + Jump(&getByName); + } + } + Bind(&getByName); + { + result = GetPropertyByName(glue, receiver, *key); + Jump(&exit); + } + } + } + Bind(&exit); + auto ret = *result; + env->SubCfgExit(); + return ret; +} + GateRef Stub::GetPropertyByName(GateRef glue, GateRef receiver, GateRef key) { auto env = GetEnvironment(); diff --git a/ecmascript/compiler/stub.h b/ecmascript/compiler/stub.h index 33678217..af6fb8dd 100644 --- a/ecmascript/compiler/stub.h +++ b/ecmascript/compiler/stub.h @@ -402,6 +402,7 @@ public: void SetValueWithBarrier(GateRef glue, GateRef obj, GateRef offset, GateRef value); GateRef GetPropertyByIndex(GateRef glue, GateRef receiver, GateRef index); GateRef GetPropertyByName(GateRef glue, GateRef receiver, GateRef key); + GateRef GetPropertyByValue(GateRef glue, GateRef receiver, GateRef keyValue); GateRef SetPropertyByIndex(GateRef glue, GateRef receiver, GateRef index, GateRef value, bool useOwn); GateRef SetPropertyByName(GateRef glue, GateRef receiver, GateRef key, GateRef value, bool useOwn); // Crawl prototype chain -- Gitee From 083984ed9d4ef4539975f2990bcf0b55ae4e7025 Mon Sep 17 00:00:00 2001 From: songzhengchao Date: Thu, 16 Jun 2022 14:01:06 +0800 Subject: [PATCH 020/154] Frame Handler refactor Frame Handler directly operate frame(set callsitesp/returnAddr/getPrevFrame,etc) which is hard to maintain. Frames are operated by FrameIterator. issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CKVR?from=project-issue Change-Id: Iba1c44c1ab1afec8b5bea0111f4e986b47cc8bc4 Signed-off-by: songzhengchao --- ecmascript/ecma_vm.cpp | 1 - ecmascript/ecma_vm.h | 4 - ecmascript/frames.cpp | 246 ++++++++++++++++++- ecmascript/frames.h | 96 ++++++-- ecmascript/interpreter/frame_handler.cpp | 300 ++--------------------- ecmascript/interpreter/frame_handler.h | 32 +-- ecmascript/llvm_stackmap_parser.cpp | 5 +- ecmascript/llvm_stackmap_parser.h | 3 +- ecmascript/mem/heap.h | 3 +- 9 files changed, 352 insertions(+), 338 deletions(-) diff --git a/ecmascript/ecma_vm.cpp b/ecmascript/ecma_vm.cpp index 793e8957..36cbe22b 100644 --- a/ecmascript/ecma_vm.cpp +++ b/ecmascript/ecma_vm.cpp @@ -67,7 +67,6 @@ #include "ecmascript/require/js_cjs_module_cache.h" #include "ecmascript/require/js_require_manager.h" #include "ecmascript/tooling/interface/js_debugger_manager.h" -#include "ecmascript/llvm_stackmap_parser.h" #ifdef PANDA_TARGET_WINDOWS #ifdef ERROR #undef ERROR diff --git a/ecmascript/ecma_vm.h b/ecmascript/ecma_vm.h index 8931f4b2..13677ded 100644 --- a/ecmascript/ecma_vm.h +++ b/ecmascript/ecma_vm.h @@ -67,9 +67,6 @@ class JSFunction; class Program; class TSLoader; class FileLoader; -namespace kungfu { - class LLVMStackMapParser; -}; class ModuleManager; class JSCjsModule; class JSCjsExports; @@ -336,7 +333,6 @@ public: JSTaggedValue FindConstpool(const JSPandaFile *jsPandaFile); void SetAOTFuncEntry(uint32_t hash, uint32_t methodId, uint64_t funcEntry); - void StoreBCOffsetInfo(const std::string& methodName, int32_t bcOffset) { exceptionBCList_.emplace_back(std::pair(methodName, bcOffset)); diff --git a/ecmascript/frames.cpp b/ecmascript/frames.cpp index f5092d33..16c4afd6 100644 --- a/ecmascript/frames.cpp +++ b/ecmascript/frames.cpp @@ -17,6 +17,7 @@ #include "ecmascript/file_loader.h" #include "ecmascript/js_thread.h" #include "ecmascript/llvm_stackmap_parser.h" +#include "ecmascript/interpreter/frame_handler.h" namespace panda::ecmascript { void FrameIterator::Advance() @@ -26,65 +27,95 @@ void FrameIterator::Advance() switch (t) { case FrameType::OPTIMIZED_FRAME : { auto frame = GetFrame(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(optimizedReturnAddr_); + optimizedReturnAddr_ = frame->GetReturnAddr(); current_ = frame->GetPrevFrameFp(); break; } case FrameType::OPTIMIZED_ENTRY_FRAME : { auto frame = GetFrame(); + optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; current_ = frame->GetPrevFrameFp(); break; } - case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: - case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME : { + case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME: { auto frame = GetFrame(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(); + optimizedReturnAddr_ = frame->GetReturnAddr(); + current_ = frame->GetPrevFrameFp(); + break; + } + case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: { + auto frame = GetFrame(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(optimizedReturnAddr_); + optimizedReturnAddr_ = frame->GetReturnAddr(); current_ = frame->GetPrevFrameFp(); break; } case FrameType::LEAVE_FRAME : { auto frame = GetFrame(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(); + optimizedReturnAddr_ = frame->GetReturnAddr(); current_ = frame->GetPrevFrameFp(); break; } case FrameType::LEAVE_FRAME_WITH_ARGV : { auto frame = GetFrame(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(); + optimizedReturnAddr_ = frame->GetReturnAddr(); current_ = frame->GetPrevFrameFp(); break; } case FrameType::INTERPRETER_FRAME: case FrameType::INTERPRETER_FAST_NEW_FRAME : { auto frame = GetFrame(); + optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; current_ = frame->GetPrevFrameFp(); break; } case FrameType::INTERPRETER_CONSTRUCTOR_FRAME: case FrameType::ASM_INTERPRETER_FRAME : { auto frame = GetFrame(); + optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; current_ = frame->GetPrevFrameFp(); break; } case FrameType::BUILTIN_FRAME: case FrameType::BUILTIN_ENTRY_FRAME : { auto frame = GetFrame(); + optimizedReturnAddr_ = frame->GetReturnAddr(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(); current_ = frame->GetPrevFrameFp(); break; } case FrameType::BUILTIN_FRAME_WITH_ARGV : { auto frame = GetFrame(); + optimizedReturnAddr_ = frame->GetReturnAddr(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(); current_ = frame->GetPrevFrameFp(); break; } case FrameType::INTERPRETER_ENTRY_FRAME : { auto frame = GetFrame(); + optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; current_ = frame->GetPrevFrameFp(); break; } case FrameType::ASM_INTERPRETER_ENTRY_FRAME : { auto frame = GetFrame(); + optimizedReturnAddr_ = 0; + optimizedCallSiteSp_ = 0; current_ = frame->GetPrevFrameFp(); break; } case FrameType::ASM_INTERPRETER_BRIDGE_FRAME : { auto frame = GetFrame(); + optimizedCallSiteSp_ = GetPrevFrameCallSiteSp(optimizedReturnAddr_); + optimizedReturnAddr_ = frame->GetReturnAddr(); current_ = frame->GetPrevFrameFp(); break; } @@ -93,7 +124,7 @@ void FrameIterator::Advance() } } } -uintptr_t FrameIterator::GetPrevFrameCallSiteSp(uintptr_t curPc) +uintptr_t FrameIterator::GetPrevFrameCallSiteSp(uintptr_t curPc) const { if (Done()) { return 0; @@ -122,6 +153,7 @@ uintptr_t FrameIterator::GetPrevFrameCallSiteSp(uintptr_t curPc) } case FrameType::OPTIMIZED_FRAME: case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: { + ASSERT(thread_ != nullptr); auto callSiteSp = reinterpret_cast(current_) + thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->GetFuncFpDelta(curPc); return callSiteSp; @@ -145,4 +177,212 @@ uintptr_t FrameIterator::GetPrevFrameCallSiteSp(uintptr_t curPc) } } } + +ARK_INLINE void OptimizedFrame::GCIterate(const FrameIterator &it, + const RootVisitor &v0, + [[maybe_unused]] const RootRangeVisitor &v1, + ChunkMap *derivedPointers, + bool isVerifying) const +{ + std::set slotAddrs; + const JSThread *thread = it.GetThread(); + ASSERT(thread != nullptr); + bool ret = thread->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( + it.GetOptimizedReturnAddr(), reinterpret_cast(it.GetSp()), slotAddrs, derivedPointers, + isVerifying, it.GetCallSiteSp()); + if (!ret) { +#ifndef NDEBUG + LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << it.GetOptimizedReturnAddr(); +#endif + return; + } + + for (const auto &slot : slotAddrs) { + v0(Root::ROOT_FRAME, ObjectSlot(slot)); + } +} + +ARK_INLINE void OptimizedJSFunctionFrame::GCIterate(const FrameIterator &it, + const RootVisitor &v0, + [[maybe_unused]] const RootRangeVisitor &v1, + ChunkMap *derivedPointers, + bool isVerifying) const +{ + OptimizedJSFunctionFrame *frame = OptimizedJSFunctionFrame::GetFrameFromSp(it.GetSp()); + + const JSThread *thread = it.GetThread(); + ASSERT(thread != nullptr); + int delta = thread->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->GetFuncFpDelta(it.GetOptimizedReturnAddr()); + uintptr_t *preFrameSp = frame->ComputePrevFrameSp(it.GetSp(), delta); + + auto argc = *(reinterpret_cast(preFrameSp)); + JSTaggedType *argv = frame->GetArgv(reinterpret_cast(preFrameSp)); + if (argc > 0) { + uintptr_t start = ToUintPtr(argv); // argv + uintptr_t end = ToUintPtr(argv + argc); + v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); + } + + std::set slotAddrs; + bool ret = thread->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( + it.GetOptimizedReturnAddr(), reinterpret_cast(it.GetSp()), + slotAddrs, derivedPointers, isVerifying, it.GetCallSiteSp()); + if (!ret) { +#ifndef NDEBUG + LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << it.GetOptimizedReturnAddr(); +#endif + return; + } + + for (const auto &slot : slotAddrs) { + v0(Root::ROOT_FRAME, ObjectSlot(slot)); + } +} + +ARK_INLINE void AsmInterpretedFrame::GCIterate(const FrameIterator &it, + const RootVisitor &v0, + const RootRangeVisitor &v1, + ChunkMap *derivedPointers, + bool isVerifying) const +{ + AsmInterpretedFrame *frame = AsmInterpretedFrame::GetFrameFromSp(it.GetSp()); + uintptr_t start = ToUintPtr(it.GetSp()); + uintptr_t end = ToUintPtr(frame->GetCurrentFramePointer()); + v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); + v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->function))); + if (frame->pc != nullptr) { + v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->acc))); + v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->env))); + } + + std::set slotAddrs; + const JSThread *thread = it.GetThread(); + bool ret = thread->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( + it.GetOptimizedReturnAddr(), reinterpret_cast(it.GetSp()), slotAddrs, derivedPointers, isVerifying, + it.GetCallSiteSp()); + if (!ret) { +#ifndef NDEBUG + LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << it.GetOptimizedReturnAddr(); +#endif + return; + } + for (auto slot : slotAddrs) { + v0(Root::ROOT_FRAME, ObjectSlot(slot)); + } +} + +ARK_INLINE void InterpretedFrame::GCIterate(const FrameIterator &it, + const RootVisitor &v0, + const RootRangeVisitor &v1) const +{ + auto sp = it.GetSp(); + InterpretedFrame *frame = InterpretedFrame::GetFrameFromSp(sp); + if (frame->function == JSTaggedValue::Hole()) { + return; + } + + JSTaggedType *prevSp = frame->GetPrevFrameFp(); + uintptr_t start = ToUintPtr(sp); + uintptr_t end = 0U; + const JSThread *thread = it.GetThread(); + FrameIterator prevIt(prevSp, thread); + FrameType type = prevIt.GetFrameType(); + if (type == FrameType::INTERPRETER_FRAME || type == FrameType::INTERPRETER_FAST_NEW_FRAME) { + auto prevFrame = InterpretedFrame::GetFrameFromSp(prevSp); + end = ToUintPtr(prevFrame); + } else if (type == FrameType::INTERPRETER_ENTRY_FRAME) { + end = ToUintPtr(FrameHandler::GetInterpretedEntryFrameStart(prevSp)); + } else { + LOG_ECMA(FATAL) << "frame type error!"; + } + v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); + v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->function))); + + // pc == nullptr, init InterpretedFrame & native InterpretedFrame. + if (frame->pc != nullptr) { + v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->acc))); + v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->constpool))); + v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->env))); + v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->profileTypeInfo))); + } +} + +ARK_INLINE void OptimizedLeaveFrame::GCIterate(const FrameIterator &it, + [[maybe_unused]] const RootVisitor &v0, + [[maybe_unused]] const RootRangeVisitor &v1, + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) const +{ + const JSTaggedType *sp = it.GetSp(); + OptimizedLeaveFrame *frame = OptimizedLeaveFrame::GetFrameFromSp(sp); + if (frame->argc > 0) { + JSTaggedType *argv = reinterpret_cast(&frame->argc + 1); + uintptr_t start = ToUintPtr(argv); // argv + uintptr_t end = ToUintPtr(argv + frame->argc); + v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); + } +} + +ARK_INLINE void OptimizedWithArgvLeaveFrame::GCIterate(const FrameIterator &it, + [[maybe_unused]] const RootVisitor &v0, + [[maybe_unused]] const RootRangeVisitor &v1, + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) const +{ + const JSTaggedType *sp = it.GetSp(); + OptimizedWithArgvLeaveFrame *frame = OptimizedWithArgvLeaveFrame::GetFrameFromSp(sp); + if (frame->argc > 0) { + uintptr_t* argvPtr = reinterpret_cast(&frame->argc + 1); + JSTaggedType *argv = reinterpret_cast(*argvPtr); + uintptr_t start = ToUintPtr(argv); // argv + uintptr_t end = ToUintPtr(argv + frame->argc); + v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); + } +} + +ARK_INLINE void BuiltinWithArgvFrame::GCIterate(const FrameIterator &it, + [[maybe_unused]] const RootVisitor &v0, + const RootRangeVisitor &v1, + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) const +{ + const JSTaggedType *sp = it.GetSp(); + auto frame = BuiltinWithArgvFrame::GetFrameFromSp(sp); + auto argc = frame->GetNumArgs() + BuiltinFrame::RESERVED_CALL_ARGCOUNT; + JSTaggedType *argv = reinterpret_cast(frame->GetStackArgsAddress()); + uintptr_t start = ToUintPtr(argv); + uintptr_t end = ToUintPtr(argv + argc); + v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); +} + +ARK_INLINE void BuiltinFrame::GCIterate(const FrameIterator &it, + [[maybe_unused]] const RootVisitor &v0, + const RootRangeVisitor &v1, + [[maybe_unused]] ChunkMap *derivedPointers, + [[maybe_unused]] bool isVerifying) const +{ + const JSTaggedType *sp = it.GetSp(); + auto frame = BuiltinFrame::GetFrameFromSp(sp); + // no need to visit stack map for entry frame + if (frame->type == FrameType::BUILTIN_ENTRY_FRAME) { + // only visit function + v0(Root::ROOT_FRAME, ObjectSlot(frame->GetStackArgsAddress())); + return; + } + JSTaggedType *argv = reinterpret_cast(frame->GetStackArgsAddress()); + auto argc = frame->GetNumArgs() + BuiltinFrame::RESERVED_CALL_ARGCOUNT; + uintptr_t start = ToUintPtr(argv); + uintptr_t end = ToUintPtr(argv + argc); + v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); +} + +ARK_INLINE void InterpretedEntryFrame::GCIterate(const FrameIterator &it, + [[maybe_unused]] const RootVisitor &v0, + const RootRangeVisitor &v1) const +{ + const JSTaggedType* sp = it.GetSp(); + uintptr_t start = ToUintPtr(FrameHandler::GetInterpretedEntryFrameStart(sp)); + uintptr_t end = ToUintPtr(sp - INTERPRETER_ENTRY_FRAME_STATE_SIZE); + v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); +} } // namespace panda::ecmascript diff --git a/ecmascript/frames.h b/ecmascript/frames.h index bc39fac7..f1cc5157 100644 --- a/ecmascript/frames.h +++ b/ecmascript/frames.h @@ -233,9 +233,13 @@ #include "ecmascript/base/aligned_struct.h" +#include "ecmascript/mem/chunk_containers.h" +#include "ecmascript/mem/visitor.h" namespace panda::ecmascript { class JSThread; class EcmaVM; +class FrameIterator; +using DerivedDataKey = std::pair; enum class FrameType: uintptr_t { OPTIMIZED_FRAME = 0, OPTIMIZED_ENTRY_FRAME = 1, @@ -288,6 +292,12 @@ struct OptimizedFrame : public base::AlignedStruct { public: + void GCIterate(const FrameIterator &it, + const RootVisitor &v0, + [[maybe_unused]] const RootRangeVisitor &v1, + ChunkMap *derivedPointers, + bool isVerifying) const; +private: enum class Index : size_t { TypeIndex = 0, PrevFpIndex, @@ -305,13 +315,14 @@ public: { return prevFp; } - uintptr_t GetReturnAddr() + uintptr_t GetReturnAddr() const { return returnAddr; } - alignas(EAS) FrameType type {0}; - alignas(EAS) JSTaggedType *prevFp {nullptr}; - alignas(EAS) uintptr_t returnAddr {0}; + [[maybe_unused]] alignas(EAS) FrameType type {0}; + [[maybe_unused]] alignas(EAS) JSTaggedType *prevFp {nullptr}; + [[maybe_unused]] alignas(EAS) uintptr_t returnAddr {0}; + friend class FrameIterator; }; STATIC_ASSERT_EQ_ARCH(sizeof(OptimizedFrame), OptimizedFrame::SizeArch32, OptimizedFrame::SizeArch64); @@ -375,10 +386,13 @@ public: { return reinterpret_cast(preFrameSp + sizeof(uint64_t) / sizeof(uintptr_t)); } - uintptr_t GetReturnAddr() + uintptr_t GetReturnAddr() const { return returnAddr; } + void GCIterate( + const FrameIterator &it, const RootVisitor &v0, const RootRangeVisitor &v1, + ChunkMap *derivedPointers, bool isVerifying) const; // dynamic callee saveregisters for x86-64 alignas(EAS) FrameType type {0}; alignas(EAS) JSTaggedType *prevFp {nullptr}; @@ -471,7 +485,7 @@ struct InterpretedFrame : public base::AlignedStruct(Index::NumOfMembers) == NumOfTypes); - inline JSTaggedType* GetPrevFrameFp() + inline JSTaggedType* GetPrevFrameFp() const { return base.prev; } @@ -484,6 +498,7 @@ struct InterpretedFrame : public base::AlignedStruct *derivedPointers, bool isVerifying) const; alignas(EAS) JSTaggedValue function {JSTaggedValue::Hole()}; alignas(EAS) JSTaggedValue acc {JSTaggedValue::Hole()}; @@ -612,7 +629,8 @@ struct InterpretedEntryFrame : public base::AlignedStruct(const_cast(sp)) - 1; } - + void GCIterate(const FrameIterator &it, const RootVisitor &v0, + const RootRangeVisitor &v1) const; alignas(EAS) const uint8_t *pc {nullptr}; alignas(EAS) InterpretedFrameBase base; }; @@ -661,7 +679,7 @@ struct AsmInterpretedBridgeFrame : public base::AlignedStruct(reinterpret_cast(sp) - MEMBER_OFFSET(AsmInterpretedBridgeFrame, returnAddr)); } - uintptr_t GetCallSiteSp() + uintptr_t GetCallSiteSp() const { return ToUintPtr(this) + sizeof(AsmInterpretedBridgeFrame); } @@ -672,7 +690,7 @@ struct AsmInterpretedBridgeFrame : public base::AlignedStruct(reinterpret_cast(sp) - MEMBER_OFFSET(OptimizedLeaveFrame, callsiteFp)); } - uintptr_t GetCallSiteSp() + uintptr_t GetCallSiteSp() const { #ifndef PANDA_TARGET_32 return ToUintPtr(this) + MEMBER_OFFSET(OptimizedLeaveFrame, argRuntimeId); @@ -704,10 +722,13 @@ struct OptimizedLeaveFrame { { return reinterpret_cast(callsiteFp); } - uintptr_t GetReturnAddr() + uintptr_t GetReturnAddr() const { return returnAddr; } + void GCIterate( + const FrameIterator &it, const RootVisitor &v0, const RootRangeVisitor &v1, + ChunkMap *derivedPointers, bool isVerifying) const; }; struct OptimizedWithArgvLeaveFrame { @@ -724,7 +745,7 @@ struct OptimizedWithArgvLeaveFrame { return reinterpret_cast(reinterpret_cast(sp) - MEMBER_OFFSET(OptimizedWithArgvLeaveFrame, callsiteFp)); } - uintptr_t GetCallSiteSp() + uintptr_t GetCallSiteSp() const { #ifndef PANDA_TARGET_32 return ToUintPtr(this) + MEMBER_OFFSET(OptimizedWithArgvLeaveFrame, argRuntimeId); @@ -736,10 +757,13 @@ struct OptimizedWithArgvLeaveFrame { { return reinterpret_cast(callsiteFp); } - uintptr_t GetReturnAddr() + uintptr_t GetReturnAddr() const { return returnAddr; } + void GCIterate( + const FrameIterator &it, const RootVisitor &v0, const RootRangeVisitor &v1, + ChunkMap *derivedPointers, bool isVerifying) const; }; struct BuiltinFrame : public base::AlignedStruct *derivedPointers, bool isVerifying) const; alignas(EAS) FrameType type; alignas(EAS) JSTaggedType *prevFp; alignas(EAS) uintptr_t returnAddr; @@ -844,7 +871,7 @@ struct BuiltinWithArgvFrame : public base::AlignedStruct(Index::NumArgsIndex) * sizeof(uintptr_t))); return *argcAddress; } - uintptr_t GetReturnAddr() + uintptr_t GetReturnAddr() const { return returnAddr; } + void GCIterate( + const FrameIterator &it, const RootVisitor &v0, const RootRangeVisitor &v1, + ChunkMap *derivedPointers, bool isVerifying) const; // argv(... this, new.target, function) // numargs alignas(EAS) FrameType type; @@ -879,10 +909,10 @@ struct BuiltinWithArgvFrame : public base::AlignedStruct( @@ -896,19 +926,43 @@ public: return T::GetFrameFromSp(current_); } - bool Done() + template + const T* GetFrame() const + { + return T::GetFrameFromSp(current_); + } + + bool Done() const { return current_ == nullptr; } + JSTaggedType *GetSp() const + { + return current_; + } JSTaggedType *GetSp() { return current_; } void Advance(); - uintptr_t GetPrevFrameCallSiteSp(uintptr_t curPc = 0); + uintptr_t GetPrevFrameCallSiteSp(uintptr_t curPc = 0) const; + uintptr_t GetCallSiteSp() const + { + return optimizedCallSiteSp_; + } + uintptr_t GetOptimizedReturnAddr() const + { + return optimizedReturnAddr_; + } + const JSThread *GetThread() const + { + return thread_; + } private: JSTaggedType *current_ {nullptr}; const JSThread *thread_ {nullptr}; + uintptr_t optimizedCallSiteSp_ {0}; + uintptr_t optimizedReturnAddr_ {0}; }; } // namespace panda::ecmascript #endif // ECMASCRIPT_FRAMES_H diff --git a/ecmascript/interpreter/frame_handler.cpp b/ecmascript/interpreter/frame_handler.cpp index b3cac6a3..bb0095e0 100644 --- a/ecmascript/interpreter/frame_handler.cpp +++ b/ecmascript/interpreter/frame_handler.cpp @@ -43,8 +43,9 @@ ARK_INLINE void FrameHandler::AdvanceToInterpretedFrame() ARK_INLINE void FrameHandler::PrevInterpretedFrame() { if (!thread_->IsAsmInterpreter()) { - auto frame = InterpretedFrameBase::GetFrameFromSp(sp_); - sp_ = frame->GetPrevFrameFp(); + FrameIterator it(sp_, thread_); + it.Advance(); + sp_ = it.GetSp(); return; } AdvanceToInterpretedFrame(); @@ -266,104 +267,6 @@ ARK_INLINE uintptr_t FrameHandler::GetInterpretedFrameEnd(JSTaggedType *prevSp) return end; } -ARK_INLINE void FrameHandler::InterpretedFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, - const RootRangeVisitor &v1) const -{ - InterpretedFrame *frame = InterpretedFrame::GetFrameFromSp(sp); - if (frame->function == JSTaggedValue::Hole()) { - return; - } - JSTaggedType *prevSp = frame->GetPrevFrameFp(); - uintptr_t start = ToUintPtr(sp); - uintptr_t end = 0U; - FrameType type = FrameHandler::GetFrameType(prevSp); - if (type == FrameType::INTERPRETER_FRAME || type == FrameType::INTERPRETER_FAST_NEW_FRAME) { - auto prevFrame = InterpretedFrame::GetFrameFromSp(prevSp); - end = ToUintPtr(prevFrame); - } else if (type == FrameType::INTERPRETER_ENTRY_FRAME) { - end = ToUintPtr(GetInterpretedEntryFrameStart(prevSp)); - } else { - LOG_ECMA(FATAL) << "frame type error!"; - } - v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); - v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->function))); - - // pc == nullptr, init InterpretedFrame & native InterpretedFrame. - if (frame->pc != nullptr) { - v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->acc))); - v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->constpool))); - v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->env))); - v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->profileTypeInfo))); - } -} - -ARK_INLINE void FrameHandler::AsmInterpretedFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, - const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) -{ - AsmInterpretedFrame *frame = AsmInterpretedFrame::GetFrameFromSp(sp); - uintptr_t start = ToUintPtr(sp); - uintptr_t end = ToUintPtr(frame->GetCurrentFramePointer()); - v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); - v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->function))); - if (frame->pc != nullptr) { - v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->acc))); - v0(Root::ROOT_FRAME, ObjectSlot(ToUintPtr(&frame->env))); - } - - uintptr_t curPc = optimizedReturnAddr_; - std::set slotAddrs; - bool ret = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( - curPc, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, - optimizedCallSiteSp_); - if (!ret) { -#ifndef NDEBUG - LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << curPc; -#endif - return; - } - for (auto slot : slotAddrs) { - v0(Root::ROOT_FRAME, ObjectSlot(slot)); - } -} - -ARK_INLINE void FrameHandler::BuiltinFrameIterate(const JSTaggedType *sp, - [[maybe_unused]] const RootVisitor &v0, - const RootRangeVisitor &v1, - [[maybe_unused]] ChunkMap *derivedPointers, - [[maybe_unused]] bool isVerifying) -{ - auto frame = BuiltinFrame::GetFrameFromSp(sp); - // no need to visit stack map for entry frame - if (frame->type == FrameType::BUILTIN_ENTRY_FRAME) { - // only visit function - v0(Root::ROOT_FRAME, ObjectSlot(frame->GetStackArgsAddress())); - return; - } - JSTaggedType *argv = reinterpret_cast(frame->GetStackArgsAddress()); - auto argc = frame->GetNumArgs() + BuiltinFrame::RESERVED_CALL_ARGCOUNT; - uintptr_t start = ToUintPtr(argv); - uintptr_t end = ToUintPtr(argv + argc); - v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); -} - -ARK_INLINE void FrameHandler::BuiltinWithArgvFrameIterate(const JSTaggedType *sp, - [[maybe_unused]] const RootVisitor &v0, - const RootRangeVisitor &v1, - [[maybe_unused]] ChunkMap *derivedPointers, - [[maybe_unused]] bool isVerifying) -{ - auto frame = BuiltinWithArgvFrame::GetFrameFromSp(sp); - auto argc = frame->GetNumArgs() + BuiltinFrame::RESERVED_CALL_ARGCOUNT; - JSTaggedType *argv = reinterpret_cast(frame->GetStackArgsAddress()); - uintptr_t start = ToUintPtr(argv); - uintptr_t end = ToUintPtr(argv + argc); - v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); -} - ARK_INLINE JSTaggedType *FrameHandler::GetInterpretedEntryFrameStart(const JSTaggedType *sp) { ASSERT(FrameHandler::GetFrameType(sp) == FrameType::INTERPRETER_ENTRY_FRAME); @@ -372,126 +275,6 @@ ARK_INLINE JSTaggedType *FrameHandler::GetInterpretedEntryFrameStart(const JSTag return argcSp - argc - RESERVED_CALL_ARGCOUNT; } -ARK_INLINE void FrameHandler::InterpretedEntryFrameIterate(const JSTaggedType *sp, - [[maybe_unused]] const RootVisitor &v0, - const RootRangeVisitor &v1) const -{ - uintptr_t start = ToUintPtr(GetInterpretedEntryFrameStart(sp)); - uintptr_t end = ToUintPtr(sp - INTERPRETER_ENTRY_FRAME_STATE_SIZE); - v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); -} - -ARK_INLINE void FrameHandler::OptimizedFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, - [[maybe_unused]] const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) -{ - std::set slotAddrs; - bool ret = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( - optimizedReturnAddr_, reinterpret_cast(sp), slotAddrs, derivedPointers, - isVerifying, optimizedCallSiteSp_); - if (!ret) { -#ifndef NDEBUG - LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << optimizedReturnAddr_; -#endif - return; - } - - for (const auto &slot : slotAddrs) { - v0(Root::ROOT_FRAME, ObjectSlot(slot)); - } -} - -ARK_INLINE void FrameHandler::OptimizedJSFunctionFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, - [[maybe_unused]] const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) -{ - OptimizedJSFunctionFrame *frame = OptimizedJSFunctionFrame::GetFrameFromSp(sp); - - int delta = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->GetFuncFpDelta(optimizedReturnAddr_); - uintptr_t *preFrameSp = frame->ComputePrevFrameSp(sp, delta); - - auto argc = *(reinterpret_cast(preFrameSp)); - JSTaggedType *argv = frame->GetArgv(reinterpret_cast(preFrameSp)); - if (argc > 0) { - uintptr_t start = ToUintPtr(argv); // argv - uintptr_t end = ToUintPtr(argv + argc); - v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); - } - - std::set slotAddrs; - auto currentPc = optimizedReturnAddr_; - bool ret = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( - currentPc, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedCallSiteSp_); - if (!ret) { -#ifndef NDEBUG - LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << currentPc; -#endif - return; - } - - for (const auto &slot : slotAddrs) { - v0(Root::ROOT_FRAME, ObjectSlot(slot)); - } -} - -ARK_INLINE void FrameHandler::OptimizedEntryFrameIterate(const JSTaggedType *sp, - const RootVisitor &v0, - [[maybe_unused]] const RootRangeVisitor &v1, - ChunkMap *derivedPointers, - bool isVerifying) -{ - std::set slotAddrs; - // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - auto returnAddr = reinterpret_cast(*(reinterpret_cast(const_cast(sp)) + 1)); - bool ret = thread_->GetEcmaVM()->GetFileLoader()->GetStackMapParser()->CollectGCSlots( - returnAddr, reinterpret_cast(sp), slotAddrs, derivedPointers, isVerifying, optimizedReturnAddr_); - if (!ret) { -#ifndef NDEBUG - LOG_ECMA(DEBUG) << " stackmap don't found returnAddr " << returnAddr; -#endif - return; - } - - for (const auto &slot : slotAddrs) { - v0(Root::ROOT_FRAME, ObjectSlot(slot)); - } -} - -ARK_INLINE void FrameHandler::OptimizedLeaveFrameIterate(const JSTaggedType *sp, - [[maybe_unused]] const RootVisitor &v0, - [[maybe_unused]] const RootRangeVisitor &v1, - [[maybe_unused]] ChunkMap *derivedPointers, - [[maybe_unused]] bool isVerifying) -{ - OptimizedLeaveFrame *frame = OptimizedLeaveFrame::GetFrameFromSp(sp); - if (frame->argc > 0) { - JSTaggedType *argv = reinterpret_cast(&frame->argc + 1); - uintptr_t start = ToUintPtr(argv); // argv - uintptr_t end = ToUintPtr(argv + frame->argc); - v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); - } -} - -ARK_INLINE void FrameHandler::OptimizedWithArgvLeaveFrameIterate(const JSTaggedType *sp, - [[maybe_unused]] const RootVisitor &v0, - [[maybe_unused]] const RootRangeVisitor &v1, - [[maybe_unused]] ChunkMap *derivedPointers, - [[maybe_unused]] bool isVerifying) -{ - OptimizedLeaveFrame *frame = OptimizedLeaveFrame::GetFrameFromSp(sp); - if (frame->argc > 0) { - uintptr_t* argvPtr = reinterpret_cast(&frame->argc + 1); - JSTaggedType *argv = reinterpret_cast(*argvPtr); - uintptr_t start = ToUintPtr(argv); // argv - uintptr_t end = ToUintPtr(argv + frame->argc); - v1(Root::ROOT_FRAME, ObjectSlot(start), ObjectSlot(end)); - } -} - void FrameHandler::IterateRsp(const RootVisitor &v0, const RootRangeVisitor &v1) { JSTaggedType *current = const_cast(thread_->GetLastLeaveFrame()); @@ -504,9 +287,11 @@ void FrameHandler::IterateSp(const RootVisitor &v0, const RootRangeVisitor &v1) while (current) { // only interpreter entry frame is on thread sp when rsp is enable ASSERT(FrameHandler::GetFrameType(current) == FrameType::INTERPRETER_ENTRY_FRAME); - InterpretedEntryFrame *frame = InterpretedEntryFrame::GetFrameFromSp(current); - InterpretedEntryFrameIterate(current, v0, v1); - current = frame->GetPrevFrameFp(); + FrameIterator it(current, thread_); + auto frame = it.GetFrame(); + frame->GCIterate(it, v0, v1); + it.Advance(); + current = it.GetSp(); } } @@ -528,7 +313,7 @@ void FrameHandler::Iterate(const RootVisitor &v0, const RootRangeVisitor &v1) IterateFrameChain(current, v0, v1); } -void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, const RootRangeVisitor &v1) +void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, const RootRangeVisitor &v1) const { ChunkMap *derivedPointers = thread_->GetEcmaVM()->GetHeap()->GetDerivedPointers(); bool isVerifying = false; @@ -542,87 +327,56 @@ void FrameHandler::IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, switch (type) { case FrameType::OPTIMIZED_FRAME: { auto frame = it.GetFrame(); - OptimizedFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); - optimizedCallSiteSp_ = it.GetPrevFrameCallSiteSp(optimizedReturnAddr_); - optimizedReturnAddr_ = frame->GetReturnAddr(); - break; - } - case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME: { - auto frame = it.GetFrame(); - optimizedCallSiteSp_ = it.GetPrevFrameCallSiteSp(); - optimizedReturnAddr_ = frame->GetReturnAddr(); + frame->GCIterate(it, v0, v1, derivedPointers, isVerifying); break; } case FrameType::OPTIMIZED_JS_FUNCTION_FRAME: { auto frame = it.GetFrame(); - OptimizedJSFunctionFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); - optimizedCallSiteSp_ = it.GetPrevFrameCallSiteSp(optimizedReturnAddr_); - optimizedReturnAddr_ = frame->GetReturnAddr(); - break; - } - case FrameType::OPTIMIZED_ENTRY_FRAME: { - optimizedReturnAddr_ = 0; - optimizedCallSiteSp_ = 0; - break; - } - case FrameType::ASM_INTERPRETER_ENTRY_FRAME: { - optimizedReturnAddr_ = 0; - optimizedCallSiteSp_ = 0; - break; - } - case FrameType::ASM_INTERPRETER_BRIDGE_FRAME: { - auto frame = it.GetFrame(); - optimizedCallSiteSp_ = it.GetPrevFrameCallSiteSp(optimizedReturnAddr_); - optimizedReturnAddr_ = frame->GetReturnAddr(); + frame->GCIterate(it, v0, v1, derivedPointers, isVerifying); break; } case FrameType::ASM_INTERPRETER_FRAME: case FrameType::INTERPRETER_CONSTRUCTOR_FRAME: { - AsmInterpretedFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); - optimizedReturnAddr_ = 0; - optimizedCallSiteSp_ = 0; + auto frame = it.GetFrame(); + frame->GCIterate(it, v0, v1, derivedPointers, isVerifying); break; } case FrameType::INTERPRETER_FRAME: case FrameType::INTERPRETER_FAST_NEW_FRAME: { - InterpretedFrameIterate(it.GetSp(), v0, v1); - optimizedReturnAddr_ = 0; - optimizedCallSiteSp_ = 0; + auto frame = it.GetFrame(); + frame->GCIterate(it, v0, v1); break; } case FrameType::LEAVE_FRAME: { auto frame = it.GetFrame(); - OptimizedLeaveFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); - optimizedCallSiteSp_ = it.GetPrevFrameCallSiteSp(); - optimizedReturnAddr_ = frame->GetReturnAddr(); + frame->GCIterate(it, v0, v1, derivedPointers, isVerifying); break; } case FrameType::LEAVE_FRAME_WITH_ARGV: { auto frame = it.GetFrame(); - OptimizedWithArgvLeaveFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); - optimizedCallSiteSp_ = it.GetPrevFrameCallSiteSp(); - optimizedReturnAddr_ = frame->GetReturnAddr(); + frame->GCIterate(it, v0, v1, derivedPointers, isVerifying); break; } case FrameType::BUILTIN_FRAME_WITH_ARGV: { auto frame = it.GetFrame(); - BuiltinWithArgvFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); - optimizedReturnAddr_ = frame->returnAddr; - optimizedCallSiteSp_ = it.GetPrevFrameCallSiteSp(); + frame->GCIterate(it, v0, v1, derivedPointers, isVerifying); break; } case FrameType::BUILTIN_ENTRY_FRAME: case FrameType::BUILTIN_FRAME: { auto frame = it.GetFrame(); - BuiltinFrameIterate(it.GetSp(), v0, v1, derivedPointers, isVerifying); - optimizedReturnAddr_ = frame->returnAddr; - optimizedCallSiteSp_ = it.GetPrevFrameCallSiteSp(); + frame->GCIterate(it, v0, v1, derivedPointers, isVerifying); break; } case FrameType::INTERPRETER_ENTRY_FRAME: { - InterpretedEntryFrameIterate(it.GetSp(), v0, v1); - optimizedReturnAddr_ = 0; - optimizedCallSiteSp_ = 0; + auto frame = it.GetFrame(); + frame->GCIterate(it, v0, v1); + break; + } + case FrameType::OPTIMIZED_JS_FUNCTION_ARGS_CONFIG_FRAME: + case FrameType::OPTIMIZED_ENTRY_FRAME: + case FrameType::ASM_INTERPRETER_ENTRY_FRAME: + case FrameType::ASM_INTERPRETER_BRIDGE_FRAME: { break; } default: { diff --git a/ecmascript/interpreter/frame_handler.h b/ecmascript/interpreter/frame_handler.h index b0858d0b..3d135d1d 100644 --- a/ecmascript/interpreter/frame_handler.h +++ b/ecmascript/interpreter/frame_handler.h @@ -166,7 +166,7 @@ public: // for Frame GC. void Iterate(const RootVisitor &v0, const RootRangeVisitor &v1); - void IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, const RootRangeVisitor &v1); + void IterateFrameChain(JSTaggedType *start, const RootVisitor &v0, const RootRangeVisitor &v1) const; void IterateRsp(const RootVisitor &v0, const RootRangeVisitor &v1); void IterateSp(const RootVisitor &v0, const RootRangeVisitor &v1); @@ -184,40 +184,10 @@ private: void AdvanceToInterpretedFrame(); uintptr_t GetInterpretedFrameEnd(JSTaggedType *prevSp) const; - - // for Frame GC. - void InterpretedFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1) const; - void AsmInterpretedFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying); - void InterpretedEntryFrameIterate(const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1) const; - void BuiltinFrameIterate( - const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying); - void BuiltinWithArgvFrameIterate( - const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying); - void OptimizedFrameIterate( - const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying); - void OptimizedJSFunctionFrameIterate( - const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying); - void OptimizedEntryFrameIterate( - const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying); - void OptimizedLeaveFrameIterate( - const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying); - void OptimizedWithArgvLeaveFrameIterate( - const JSTaggedType *sp, const RootVisitor &v0, const RootRangeVisitor &v1, - ChunkMap *derivedPointers, bool isVerifying); - private: JSTaggedType *sp_ {nullptr}; JSTaggedType *fp_ {nullptr}; const JSThread *thread_ {nullptr}; - uintptr_t optimizedCallSiteSp_ {0}; - uintptr_t optimizedReturnAddr_ {0}; }; class StackAssertScope { diff --git a/ecmascript/llvm_stackmap_parser.cpp b/ecmascript/llvm_stackmap_parser.cpp index 2ab4a614..0c21f41f 100644 --- a/ecmascript/llvm_stackmap_parser.cpp +++ b/ecmascript/llvm_stackmap_parser.cpp @@ -103,7 +103,8 @@ uintptr_t LLVMStackMapParser::GetStackSlotAddress(const DwarfRegAndOffsetType in } void LLVMStackMapParser::CollectBaseAndDerivedPointers(const CallSiteInfo* infos, std::set &baseSet, - ChunkMap *data, uintptr_t callsiteFp, uintptr_t callSiteSp) const + ChunkMap *data, [[maybe_unused]] bool isVerifying, + uintptr_t callsiteFp, uintptr_t callSiteSp) const { bool flag = (infos->size() % 2 != 0); size_t j = flag ? 1 : 0; // skip first element when size is odd number @@ -134,7 +135,7 @@ bool LLVMStackMapParser::CollectGCSlots(uintptr_t callSiteAddr, uintptr_t callsi return false; } ASSERT(callsiteFp != callSiteSp); - CollectBaseAndDerivedPointers(infos, baseSet, data, callsiteFp, callSiteSp); + CollectBaseAndDerivedPointers(infos, baseSet, data, isVerifying, callsiteFp, callSiteSp); if (IsLogEnabled()) { PrintCallSiteInfo(infos, callsiteFp, callSiteSp); diff --git a/ecmascript/llvm_stackmap_parser.h b/ecmascript/llvm_stackmap_parser.h index d2bb2ff3..2f2d242d 100644 --- a/ecmascript/llvm_stackmap_parser.h +++ b/ecmascript/llvm_stackmap_parser.h @@ -250,7 +250,8 @@ private: inline uintptr_t GetStackSlotAddress(const DwarfRegAndOffsetType info, uintptr_t callSiteSp, uintptr_t callsiteFp) const; void CollectBaseAndDerivedPointers(const CallSiteInfo *infos, std::set &baseSet, - ChunkMap *data, uintptr_t callsiteFp, uintptr_t callSiteSp) const; + ChunkMap *data, [[maybe_unused]] bool isVerifying, + uintptr_t callsiteFp, uintptr_t callSiteSp) const; void PrintCallSiteSlotAddr(const CallSiteInfo& callsiteInfo, uintptr_t callSiteSp, uintptr_t callsiteFp) const; diff --git a/ecmascript/mem/heap.h b/ecmascript/mem/heap.h index ede9d15e..0c5ee729 100644 --- a/ecmascript/mem/heap.h +++ b/ecmascript/mem/heap.h @@ -17,6 +17,7 @@ #define ECMASCRIPT_MEM_HEAP_H #include "ecmascript/base/config.h" +#include "ecmascript/frames.h" #include "ecmascript/js_thread.h" #include "ecmascript/mem/chunk_containers.h" #include "ecmascript/mem/linear_space.h" @@ -39,8 +40,6 @@ class ParallelEvacuator; class PartialGC; class STWYoungGC; -using DerivedDataKey = std::pair; - enum class MarkType : uint8_t { MARK_YOUNG, MARK_FULL -- Gitee From 7ce04249f8646b39dfc5dc5f3200314c300c84c2 Mon Sep 17 00:00:00 2001 From: zhangyukun8 Date: Thu, 16 Jun 2022 14:53:45 +0800 Subject: [PATCH 021/154] Fix uncaught exception crash 1. acc should be put into return reg of Execute Issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CLK2?from=project-issue Signed-off-by: zhangyukun8 Change-Id: I900e388131627a737dc2cf96c3d2126f991cd819 --- ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp | 5 +++++ ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp b/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp index 27ebc25f..9e9728ae 100644 --- a/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp +++ b/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp @@ -1315,15 +1315,20 @@ void AssemblerStubs::ResumeCaughtFrameAndDispatch(ExtendedAssembler *assembler) // ResumeUncaughtFrameAndReturn(uintptr_t glue) // GHC calling convention // X19 - glue +// X23 - call(default) void AssemblerStubs::ResumeUncaughtFrameAndReturn(ExtendedAssembler *assembler) { __ BindAssemblerStub(RTSTUB_ID(ResumeUncaughtFrameAndReturn)); Register glue(X19); Register fp(X5); + Register acc(X23); + Register cppRet(X0); __ Ldr(fp, MemoryOperand(glue, JSThread::GlueData::GetLastFpOffset(false))); __ Mov(Register(SP), fp); + // this method will return to Execute(cpp calling convention), and the return value should be put into X0. + __ Mov(cppRet, acc); __ RestoreFpAndLr(); __ Ret(); } diff --git a/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp b/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp index a461d213..a604b8e5 100644 --- a/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp +++ b/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp @@ -2005,10 +2005,13 @@ void AssemblerStubsX64::ResumeCaughtFrameAndDispatch(ExtendedAssembler *assemble // ResumeUncaughtFrameAndReturn(uintptr_t glue) // GHC calling convention // %r13 - glue +// %rsi - acc void AssemblerStubsX64::ResumeUncaughtFrameAndReturn(ExtendedAssembler *assembler) { __ BindAssemblerStub(RTSTUB_ID(ResumeUncaughtFrameAndReturn)); Register glueRegister = __ GlueRegister(); + Register acc(rsi); + Register cppRet(rax); Label ret; Register fpRegister = r11; @@ -2017,6 +2020,8 @@ void AssemblerStubsX64::ResumeUncaughtFrameAndReturn(ExtendedAssembler *assemble __ Jz(&ret); __ Movq(fpRegister, rsp); // resume rsp __ Bind(&ret); + // this method will return to Execute(cpp calling convention), and the return value should be put into rax. + __ Movq(acc, cppRet); __ Ret(); } -- Gitee From 0843d02ca6b512ca1ccf812ffd53c1881761d701 Mon Sep 17 00:00:00 2001 From: zhaozhibo Date: Thu, 16 Jun 2022 15:13:38 +0800 Subject: [PATCH 022/154] fix dateTimeFormatTest fail at rk3568 Signed-off-by: zhaozhibo --- ecmascript/tests/js_date_time_format_test.cpp | 57 ++++++++++++------- 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/ecmascript/tests/js_date_time_format_test.cpp b/ecmascript/tests/js_date_time_format_test.cpp index 5354341e..e2d0318e 100644 --- a/ecmascript/tests/js_date_time_format_test.cpp +++ b/ecmascript/tests/js_date_time_format_test.cpp @@ -61,7 +61,7 @@ public: }; void SetDateOptionsTest(JSThread *thread, JSHandle &optionsObj, - std::map dateOptions) + std::map &dateOptions) { auto vm = thread->GetEcmaVM(); auto factory = vm->GetFactory(); @@ -84,7 +84,7 @@ void SetDateOptionsTest(JSThread *thread, JSHandle &optionsObj, } void SetTimeOptionsTest(JSThread *thread, JSHandle &optionsObj, - std::map timeOptionsMap) + std::map &timeOptionsMap) { auto vm = thread->GetEcmaVM(); auto factory = vm->GetFactory(); @@ -147,6 +147,9 @@ HWTEST_F_L0(JSDateTimeFormatTest, Set_Get_IcuSimpleDateFormat) auto vm = thread->GetEcmaVM(); auto factory = vm->GetFactory(); auto env = vm->GetGlobalEnv(); + const icu::UnicodeString timeZoneId("Asia/Shanghai"); + icu::TimeZone *tz = icu::TimeZone::createTimeZone(timeZoneId); + icu::TimeZone::adoptDefault(tz); JSHandle ctor = env->GetDateTimeFormatFunction(); JSHandle dtf = JSHandle::Cast(factory->NewJSObjectByConstructor(JSHandle(ctor), ctor)); @@ -350,11 +353,14 @@ HWTEST_F_L0(JSDateTimeFormatTest, FormatDateTime_001) icu::Locale icuLocale("zh", "Hans", "Cn"); JSHandle objFun = env->GetObjectFunction(); - JSHandle optionsEmtpy = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); + JSHandle options = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); JSHandle hourCycleKey = globalConst->GetHandledHourCycleString(); JSHandle hourCycleValue(factory->NewFromASCII("h12")); - JSObject::SetProperty(thread, optionsEmtpy, hourCycleKey, hourCycleValue); - JSHandle dtf = CreateDateTimeFormatTest(thread, icuLocale, optionsEmtpy); + JSHandle timeZoneKey = globalConst->GetHandledTimeZoneString(); + JSHandle timeZoneValue(factory->NewFromASCII("ETC/GMT-8")); + JSObject::SetProperty(thread, options, timeZoneKey, timeZoneValue); + JSObject::SetProperty(thread, options, hourCycleKey, hourCycleValue); + JSHandle dtf = CreateDateTimeFormatTest(thread, icuLocale, options); double timeStamp1 = 1653448174000; // test "2022-05-25 11:09:34.000" double timeStamp2 = 1653921012999; // test "2022-05-30 22:30:12.999" @@ -376,12 +382,15 @@ HWTEST_F_L0(JSDateTimeFormatTest, FormatDateTime_002) icu::Locale icuLocale("zh", "Hans", "Cn"); JSHandle objFun = env->GetObjectFunction(); - JSHandle optionsEmtpy = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); + JSHandle options = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); JSHandle hourCycleKey = globalConst->GetHandledHourCycleString(); JSHandle hourCycleValue(factory->NewFromASCII("h12")); - JSObject::SetProperty(thread, optionsEmtpy, hourCycleKey, hourCycleValue); - JSHandle options = JSDateTimeFormat::ToDateTimeOptions( - thread, JSHandle::Cast(optionsEmtpy), RequiredOption::ANY, DefaultsOption::ALL); + JSHandle timeZoneKey = globalConst->GetHandledTimeZoneString(); + JSHandle timeZoneValue(factory->NewFromASCII("ETC/GMT-8")); + JSObject::SetProperty(thread, options, timeZoneKey, timeZoneValue); + JSObject::SetProperty(thread, options, hourCycleKey, hourCycleValue); + options = JSDateTimeFormat::ToDateTimeOptions( + thread, JSHandle::Cast(options), RequiredOption::ANY, DefaultsOption::ALL); JSHandle dtf = CreateDateTimeFormatTest(thread, icuLocale, options); double timeStamp1 = 1653448174000; // test "2022-05-25 11:09:34.000" @@ -403,13 +412,15 @@ HWTEST_F_L0(JSDateTimeFormatTest, FormatDateTime_003) icu::Locale icuLocale("zh", "Hans", "Cn"); JSHandle objFun = env->GetObjectFunction(); - JSHandle optionsEmtpy = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); + JSHandle options = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); JSHandle hourCycleKey = globalConst->GetHandledHourCycleString(); JSHandle hourCycleValue(factory->NewFromASCII("h12")); - JSObject::SetProperty(thread, optionsEmtpy, hourCycleKey, hourCycleValue); + JSHandle timeZoneKey = globalConst->GetHandledTimeZoneString(); + JSHandle timeZoneValue(factory->NewFromASCII("ETC/GMT-8")); + JSObject::SetProperty(thread, options, timeZoneKey, timeZoneValue); + JSObject::SetProperty(thread, options, hourCycleKey, hourCycleValue); // Set custom date time format. - JSHandle options = optionsEmtpy; std::map dateOptionsMap { { "weekday", "long" }, { "year", "2-digit" }, @@ -445,15 +456,17 @@ HWTEST_F_L0(JSDateTimeFormatTest, FormatDateTime_004) auto env = vm->GetGlobalEnv(); auto globalConst = thread->GlobalConstants(); - icu::Locale icuLocale("en", "Hans", "US"); + icu::Locale icuLocale("en", "Latn", "US"); JSHandle objFun = env->GetObjectFunction(); - JSHandle optionsEmtpy = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); + JSHandle options = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); JSHandle hourCycleKey = globalConst->GetHandledHourCycleString(); JSHandle hourCycleValue(factory->NewFromASCII("h12")); - JSObject::SetProperty(thread, optionsEmtpy, hourCycleKey, hourCycleValue); + JSHandle timeZoneKey = globalConst->GetHandledTimeZoneString(); + JSHandle timeZoneValue(factory->NewFromASCII("ETC/GMT-8")); + JSObject::SetProperty(thread, options, timeZoneKey, timeZoneValue); + JSObject::SetProperty(thread, options, hourCycleKey, hourCycleValue); // Set custom date time format. - JSHandle options = optionsEmtpy; std::map dateOptionsMap { { "weekday", "long" }, { "year", "2-digit" }, @@ -513,11 +526,14 @@ HWTEST_F_L0(JSDateTimeFormatTest, FormatDateTimeToParts_001) icu::Locale icuLocale("zh", "Hans", "Cn"); JSHandle objFun = env->GetObjectFunction(); - JSHandle optionsEmtpy = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); + JSHandle options = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); JSHandle hourCycleKey = globalConst->GetHandledHourCycleString(); JSHandle hourCycleValue(factory->NewFromASCII("h12")); - JSObject::SetProperty(thread, optionsEmtpy, hourCycleKey, hourCycleValue); - JSHandle dtf = CreateDateTimeFormatTest(thread, icuLocale, optionsEmtpy); + JSHandle timeZoneKey = globalConst->GetHandledTimeZoneString(); + JSHandle timeZoneValue(factory->NewFromASCII("ETC/GMT-8")); + JSObject::SetProperty(thread, options, timeZoneKey, timeZoneValue); + JSObject::SetProperty(thread, options, hourCycleKey, hourCycleValue); + JSHandle dtf = CreateDateTimeFormatTest(thread, icuLocale, options); double timeStamp = 1653448174123; // test "2022-05-25 11:09:34.123" // Use default date time format and format date and time to parts. @@ -555,6 +571,9 @@ HWTEST_F_L0(JSDateTimeFormatTest, FormatDateTimeToParts_002) JSHandle options = factory->NewJSObjectByConstructor(JSHandle(objFun), objFun); JSHandle hourCycleKey = globalConst->GetHandledHourCycleString(); JSHandle hourCycleValue(factory->NewFromASCII("h12")); + JSHandle timeZoneKey = globalConst->GetHandledTimeZoneString(); + JSHandle timeZoneValue(factory->NewFromASCII("ETC/GMT-8")); + JSObject::SetProperty(thread, options, timeZoneKey, timeZoneValue); JSObject::SetProperty(thread, options, hourCycleKey, hourCycleValue); double timeStamp = 1653448174123; // test "2022-05-25 11:09:34.123" -- Gitee From 9e98f2645a8bf17a433c85e5b7a7622d21d27096 Mon Sep 17 00:00:00 2001 From: wengchangcheng Date: Thu, 16 Jun 2022 15:44:23 +0800 Subject: [PATCH 023/154] Descriptor: fix crash when create generate object details: check is undefined before cast issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5CM43 Signed-off-by: wengchangcheng Change-Id: I59ea34e70578418f57870e933583d2062d1fc9f0 --- ecmascript/js_object.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ecmascript/js_object.cpp b/ecmascript/js_object.cpp index 62ca5f81..62c6ddb6 100644 --- a/ecmascript/js_object.cpp +++ b/ecmascript/js_object.cpp @@ -1409,10 +1409,10 @@ JSHandle JSObject::GetFunctionRealm(JSThread *thread, const JSHandle< return GetFunctionRealm(thread, proxyTarget); } JSTaggedValue maybeGlobalEnv = JSHandle(object)->GetLexicalEnv(); - if (maybeGlobalEnv.IsUndefined()) { - return thread->GetEcmaVM()->GetGlobalEnv(); - } while (!maybeGlobalEnv.IsJSGlobalEnv()) { + if (maybeGlobalEnv.IsUndefined()) { + return thread->GetEcmaVM()->GetGlobalEnv(); + } maybeGlobalEnv = LexicalEnv::Cast(maybeGlobalEnv.GetTaggedObject())->GetParentEnv(); } return JSHandle(thread, maybeGlobalEnv); -- Gitee From 87c8732d185e3ff5242ecb662f612da978c4aeb2 Mon Sep 17 00:00:00 2001 From: wengchangcheng Date: Wed, 15 Jun 2022 22:57:15 +0800 Subject: [PATCH 024/154] Descriptor: debugger refactor of independent js_runtime [ part-5 ] details: enable PtJson issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5CHWX Signed-off-by: wengchangcheng Change-Id: I143952f7f0a44f235067b8d03cba33d02e771ece --- ecmascript/tooling/agent/debugger_impl.cpp | 6 +- ecmascript/tooling/agent/debugger_impl.h | 2 +- .../tooling/agent/heapprofiler_impl.cpp | 4 +- ecmascript/tooling/agent/runtime_impl.cpp | 4 +- ecmascript/tooling/agent/runtime_impl.h | 4 +- ecmascript/tooling/backend/debugger_api.cpp | 17 +- ecmascript/tooling/backend/debugger_api.h | 8 +- ecmascript/tooling/backend/js_debugger.cpp | 2 +- ecmascript/tooling/backend/js_debugger.h | 2 +- .../tooling/backend/js_debugger_interface.h | 2 +- ecmascript/tooling/base/pt_events.cpp | 405 +-- ecmascript/tooling/base/pt_events.h | 21 +- ecmascript/tooling/base/pt_params.h | 7 +- ecmascript/tooling/base/pt_returns.cpp | 371 +-- ecmascript/tooling/base/pt_returns.h | 26 - ecmascript/tooling/base/pt_script.h | 2 +- ecmascript/tooling/base/pt_types.cpp | 2709 ++--------------- ecmascript/tooling/base/pt_types.h | 169 +- ecmascript/tooling/dispatcher.cpp | 27 +- ecmascript/tooling/dispatcher.h | 12 +- .../tooling/interface/js_debugger_manager.h | 4 +- ecmascript/tooling/protocol_handler.cpp | 42 +- ecmascript/tooling/protocol_handler.h | 4 +- .../tooling/test/debugger_events_test.cpp | 69 +- .../tooling/test/debugger_params_test.cpp | 84 +- .../tooling/test/debugger_returns_test.cpp | 19 +- .../tooling/test/debugger_types_test.cpp | 1343 ++------ 27 files changed, 701 insertions(+), 4664 deletions(-) diff --git a/ecmascript/tooling/agent/debugger_impl.cpp b/ecmascript/tooling/agent/debugger_impl.cpp index a6927a4e..7edf5d29 100644 --- a/ecmascript/tooling/agent/debugger_impl.cpp +++ b/ecmascript/tooling/agent/debugger_impl.cpp @@ -514,7 +514,7 @@ DispatchResponse DebuggerImpl::EvaluateOnCallFrame(const EvaluateOnCallFramePara { CallFrameId callFrameId = params.GetCallFrameId(); const std::string &expression = params.GetExpression(); - if (callFrameId < 0 || callFrameId >= static_cast(callFrameHandlers_.size())) { + if (callFrameId < 0 || callFrameId >= static_cast(callFrameHandlers_.size())) { return DispatchResponse::Fail("Invalid callFrameId."); } @@ -893,7 +893,7 @@ std::unique_ptr DebuggerImpl::GetLocalScopeChain(const FrameHandler *fram } std::unique_ptr local = std::make_unique(); - Local localObj(local->NewObject(vm_)); + Local localObj = ObjectRef::New(vm_); local->SetType(ObjectType::Object) .SetObjectId(runtime_->curObjectId_) .SetClassName(ObjectClassName::Object) @@ -1009,7 +1009,7 @@ std::unique_ptr DebuggerImpl::GetGlobalScopeChain() } void DebuggerImpl::UpdateScopeObject(const FrameHandler *frameHandler, - std::string_view varName, const Local &newVal) + std::string_view varName, Local newVal) { auto *sp = DebuggerApi::GetSp(frameHandler); auto iter = scopeObjects_.find(sp); diff --git a/ecmascript/tooling/agent/debugger_impl.h b/ecmascript/tooling/agent/debugger_impl.h index 38bceeac..bd631dd4 100644 --- a/ecmascript/tooling/agent/debugger_impl.h +++ b/ecmascript/tooling/agent/debugger_impl.h @@ -141,7 +141,7 @@ private: void GetLocalVariables(const FrameHandler *frameHandler, const JSMethod *method, Local &thisVal, Local &localObj); void CleanUpOnPaused(); - void UpdateScopeObject(const FrameHandler *frameHandler, std::string_view varName, const Local &newVal); + void UpdateScopeObject(const FrameHandler *frameHandler, std::string_view varName, Local newVal); Local ConvertToLocal(const std::string &varValue); bool DecodeAndCheckBase64(const std::string &src, std::string &dest); bool IsSkipLine(const JSPtLocation &location); diff --git a/ecmascript/tooling/agent/heapprofiler_impl.cpp b/ecmascript/tooling/agent/heapprofiler_impl.cpp index abf5aa9f..abdc6cd8 100644 --- a/ecmascript/tooling/agent/heapprofiler_impl.cpp +++ b/ecmascript/tooling/agent/heapprofiler_impl.cpp @@ -221,11 +221,11 @@ void HeapProfilerImpl::Frontend::LastSeenObjectId(int32_t lastSeenObjectId) tooling::LastSeenObjectId lastSeenObjectIdEvent; lastSeenObjectIdEvent.SetLastSeenObjectId(lastSeenObjectId); - size_t timestamp = 0; + int64_t timestamp = 0; struct timeval tv = {0, 0}; gettimeofday(&tv, nullptr); const int THOUSAND = 1000; - timestamp = static_cast(tv.tv_usec + tv.tv_sec * THOUSAND * THOUSAND); + timestamp = static_cast(tv.tv_usec + tv.tv_sec * THOUSAND * THOUSAND); lastSeenObjectIdEvent.SetTimestamp(timestamp); channel_->SendNotification(lastSeenObjectIdEvent); } diff --git a/ecmascript/tooling/agent/runtime_impl.cpp b/ecmascript/tooling/agent/runtime_impl.cpp index 885b3ba8..90a7c520 100644 --- a/ecmascript/tooling/agent/runtime_impl.cpp +++ b/ecmascript/tooling/agent/runtime_impl.cpp @@ -281,7 +281,7 @@ void RuntimeImpl::CacheObjectIfNeeded(Local valRef, RemoteObject *re } } -void RuntimeImpl::GetProtoOrProtoType(const Local &value, bool isOwn, bool isAccessorOnly, +void RuntimeImpl::GetProtoOrProtoType(Local value, bool isOwn, bool isAccessorOnly, std::vector> *outPropertyDesc) { if (!isAccessorOnly && isOwn && !value->IsProxy()) { @@ -315,7 +315,7 @@ void RuntimeImpl::GetProtoOrProtoType(const Local &value, bool isOwn outPropertyDesc->emplace_back(std::move(debuggerProperty)); } -void RuntimeImpl::GetAdditionalProperties(const Local &value, +void RuntimeImpl::GetAdditionalProperties(Local value, std::vector> *outPropertyDesc) { // The length of the TypedArray have to be limited(less than or equal to lengthTypedArrayLimit) until we construct diff --git a/ecmascript/tooling/agent/runtime_impl.h b/ecmascript/tooling/agent/runtime_impl.h index 2feae617..34e7ec26 100644 --- a/ecmascript/tooling/agent/runtime_impl.h +++ b/ecmascript/tooling/agent/runtime_impl.h @@ -76,9 +76,9 @@ private: const char* name, std::vector> *outPropertyDesc); void AddTypedArrayRefs(Local arrayBufferRef, std::vector> *outPropertyDesc); - void GetProtoOrProtoType(const Local &value, bool isOwn, bool isAccessorOnly, + void GetProtoOrProtoType(Local value, bool isOwn, bool isAccessorOnly, std::vector> *outPropertyDesc); - void GetAdditionalProperties(const Local &value, + void GetAdditionalProperties(Local value, std::vector> *outPropertyDesc); class Frontend { diff --git a/ecmascript/tooling/backend/debugger_api.cpp b/ecmascript/tooling/backend/debugger_api.cpp index 14b59f91..16b9074c 100644 --- a/ecmascript/tooling/backend/debugger_api.cpp +++ b/ecmascript/tooling/backend/debugger_api.cpp @@ -134,19 +134,6 @@ Local DebuggerApi::GetVRegValue(const EcmaVM *ecmaVm, return JSNApiHelper::ToLocal(handledValue); } -std::string DebuggerApi::ToStdString(Local str) -{ - ecmascript::JSHandle ret = JSNApiHelper::ToJSHandle(str); - ASSERT(ret->IsString()); - EcmaString *ecmaStr = EcmaString::Cast(ret.GetTaggedValue().GetTaggedObject()); - return CstringConvertToStdString(ConvertToString(ecmaStr)); -} - -int32_t DebuggerApi::StringToInt(Local str) -{ - return std::stoi(ToStdString(str)); -} - // JSThread Local DebuggerApi::GetAndClearException(const EcmaVM *ecmaVm) { @@ -189,7 +176,7 @@ void DebuggerApi::RegisterHooks(JSDebugger *debugger, PtHooks *hooks) } bool DebuggerApi::SetBreakpoint(JSDebugger *debugger, const JSPtLocation &location, - const Local &condFuncRef) + Local condFuncRef) { return debugger->SetBreakpoint(location, condFuncRef); } @@ -337,7 +324,7 @@ Local DebuggerApi::GenerateFuncFromBuffer(const EcmaVM *ecmaVm, con return JSNApiHelper::ToLocal(JSHandle(ecmaVm->GetJSThread(), func)); } -Local DebuggerApi::EvaluateViaFuncCall(EcmaVM *ecmaVm, const Local &funcRef, +Local DebuggerApi::EvaluateViaFuncCall(EcmaVM *ecmaVm, Local funcRef, std::shared_ptr &frameHandler) { JSNApi::EnableUserUncaughtErrorHandler(ecmaVm); diff --git a/ecmascript/tooling/backend/debugger_api.h b/ecmascript/tooling/backend/debugger_api.h index 2c715439..b2d6376f 100644 --- a/ecmascript/tooling/backend/debugger_api.h +++ b/ecmascript/tooling/backend/debugger_api.h @@ -68,10 +68,6 @@ public: static Local GetGlobalValue(const EcmaVM *vm, Local name); static bool SetGlobalValue(const EcmaVM *vm, Local name, Local value); - // String - static std::string ToStdString(Local str); - static int32_t StringToInt(Local str); - // JSThread static Local GetAndClearException(const EcmaVM *ecmaVm); static void SetException(const EcmaVM *ecmaVm, Local exception); @@ -85,10 +81,10 @@ public: static void DestroyJSDebugger(JSDebugger *debugger); static void RegisterHooks(JSDebugger *debugger, PtHooks *hooks); static bool SetBreakpoint(JSDebugger *debugger, const JSPtLocation &location, - const Local &condFuncRef); + Local condFuncRef); static bool RemoveBreakpoint(JSDebugger *debugger, const JSPtLocation &location); static void HandleUncaughtException(const EcmaVM *ecmaVm, std::string &message); - static Local EvaluateViaFuncCall(EcmaVM *ecmaVm, const Local &funcRef, + static Local EvaluateViaFuncCall(EcmaVM *ecmaVm, Local funcRef, std::shared_ptr &frameHandler); static Local GenerateFuncFromBuffer(const EcmaVM *ecmaVm, const void *buffer, size_t size, std::string_view entryPoint); diff --git a/ecmascript/tooling/backend/js_debugger.cpp b/ecmascript/tooling/backend/js_debugger.cpp index 74a3da70..659b93c8 100644 --- a/ecmascript/tooling/backend/js_debugger.cpp +++ b/ecmascript/tooling/backend/js_debugger.cpp @@ -25,7 +25,7 @@ namespace panda::ecmascript::tooling { using panda::ecmascript::base::BuiltinsBase; -bool JSDebugger::SetBreakpoint(const JSPtLocation &location, const Local &condFuncRef) +bool JSDebugger::SetBreakpoint(const JSPtLocation &location, Local condFuncRef) { JSMethod *method = FindMethod(location); if (method == nullptr) { diff --git a/ecmascript/tooling/backend/js_debugger.h b/ecmascript/tooling/backend/js_debugger.h index dbda46cf..56663a13 100644 --- a/ecmascript/tooling/backend/js_debugger.h +++ b/ecmascript/tooling/backend/js_debugger.h @@ -92,7 +92,7 @@ public: hooks_ = nullptr; } - bool SetBreakpoint(const JSPtLocation &location, const Local &condFuncRef) override; + bool SetBreakpoint(const JSPtLocation &location, Local condFuncRef) override; bool RemoveBreakpoint(const JSPtLocation &location) override; void BytecodePcChanged(JSThread *thread, JSMethod *method, uint32_t bcOffset) override; void LoadModule(std::string_view filename) override diff --git a/ecmascript/tooling/backend/js_debugger_interface.h b/ecmascript/tooling/backend/js_debugger_interface.h index 1afebdc4..08f7943d 100644 --- a/ecmascript/tooling/backend/js_debugger_interface.h +++ b/ecmascript/tooling/backend/js_debugger_interface.h @@ -112,7 +112,7 @@ public: * @param condition Optional condition * @return Error if any errors occur */ - virtual bool SetBreakpoint(const JSPtLocation &location, const Local &condFuncRef) = 0; + virtual bool SetBreakpoint(const JSPtLocation &location, Local condFuncRef) = 0; /** * \brief Remove breakpoint from \param location diff --git a/ecmascript/tooling/base/pt_events.cpp b/ecmascript/tooling/base/pt_events.cpp index 4dffbd22..57dbbbfa 100644 --- a/ecmascript/tooling/base/pt_events.cpp +++ b/ecmascript/tooling/base/pt_events.cpp @@ -16,30 +16,11 @@ #include "ecmascript/tooling/base/pt_events.h" namespace panda::ecmascript::tooling { -Local BreakpointResolved::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "breakpointId")), - Local(StringRef::NewFromUtf8(ecmaVm, breakpointId_.c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "location")), - Local(location_->ToObject(ecmaVm))); - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr BreakpointResolved::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("breakpointId", breakpointId_.c_str()); + ASSERT(location_ != nullptr); result->Add("location", location_->ToJson()); std::unique_ptr object = PtJson::CreateObject(); @@ -49,43 +30,6 @@ std::unique_ptr BreakpointResolved::ToJson() const return object; } -Local Paused::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - size_t len = callFrames_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local callFrame = callFrames_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, callFrame); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "callFrames")), values); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "reason")), - Local(StringRef::NewFromUtf8(ecmaVm, reason_.c_str()))); - if (data_) { - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "data")), - Local(data_.value()->ToObject(ecmaVm))); - } - if (hitBreakpoints_) { - len = hitBreakpoints_->size(); - values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local id = StringRef::NewFromUtf8(ecmaVm, hitBreakpoints_.value()[i].c_str()); - values->Set(ecmaVm, i, id); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "hitBreakpoints")), values); - } - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr Paused::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -93,19 +37,22 @@ std::unique_ptr Paused::ToJson() const std::unique_ptr array = PtJson::CreateArray(); size_t len = callFrames_.size(); for (size_t i = 0; i < len; i++) { + ASSERT(callFrames_[i] != nullptr); array->Push(callFrames_[i]->ToJson()); } result->Add("callFrames", array); result->Add("reason", reason_.c_str()); if (data_) { + ASSERT(data_.value() != nullptr); result->Add("data", data_.value()->ToJson()); } if (hitBreakpoints_) { std::unique_ptr breakpoints = PtJson::CreateArray(); len = hitBreakpoints_->size(); for (size_t i = 0; i < len; i++) { - array->Push(hitBreakpoints_.value()[i].c_str()); + breakpoints->Push(hitBreakpoints_.value()[i].c_str()); } + result->Add("hitBreakpoints", breakpoints); } std::unique_ptr object = PtJson::CreateObject(); @@ -115,19 +62,6 @@ std::unique_ptr Paused::ToJson() const return object; } -Local Resumed::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr Resumed::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -139,81 +73,6 @@ std::unique_ptr Resumed::ToJson() const return object; } -Local ScriptFailedToParse::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(scriptId_).c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "url")), - Local(StringRef::NewFromUtf8(ecmaVm, url_.c_str()))); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "startLine")), - IntegerRef::New(ecmaVm, startLine_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "startColumn")), - IntegerRef::New(ecmaVm, startColumn_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "endLine")), - IntegerRef::New(ecmaVm, endLine_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "endColumn")), - IntegerRef::New(ecmaVm, endColumn_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "executionContextId")), - IntegerRef::New(ecmaVm, executionContextId_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "hash")), - Local(StringRef::NewFromUtf8(ecmaVm, hash_.c_str()))); - if (execContextAuxData_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "executionContextAuxData")), - Local(execContextAuxData_.value())); - } - if (sourceMapUrl_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "sourceMapURL")), - Local(StringRef::NewFromUtf8(ecmaVm, sourceMapUrl_->c_str()))); - } - if (hasSourceUrl_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "hasSourceURL")), - BooleanRef::New(ecmaVm, hasSourceUrl_.value())); - } - if (isModule_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "isModule")), - BooleanRef::New(ecmaVm, isModule_.value())); - } - if (length_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "length")), - IntegerRef::New(ecmaVm, length_.value())); - } - if (codeOffset_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "codeOffset")), - IntegerRef::New(ecmaVm, codeOffset_.value())); - } - if (scriptLanguage_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptLanguage")), - Local(StringRef::NewFromUtf8(ecmaVm, scriptLanguage_->c_str()))); - } - if (embedderName_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "embedderName")), - Local(StringRef::NewFromUtf8(ecmaVm, embedderName_->c_str()))); - } - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr ScriptFailedToParse::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -255,85 +114,6 @@ std::unique_ptr ScriptFailedToParse::ToJson() const return object; } -Local ScriptParsed::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(scriptId_).c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "url")), - Local(StringRef::NewFromUtf8(ecmaVm, url_.c_str()))); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "startLine")), - IntegerRef::New(ecmaVm, startLine_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "startColumn")), - IntegerRef::New(ecmaVm, startColumn_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "endLine")), - IntegerRef::New(ecmaVm, endLine_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "endColumn")), - IntegerRef::New(ecmaVm, endColumn_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "executionContextId")), - IntegerRef::New(ecmaVm, executionContextId_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "hash")), - Local(StringRef::NewFromUtf8(ecmaVm, hash_.c_str()))); - if (execContextAuxData_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "executionContextAuxData")), - Local(execContextAuxData_.value())); - } - if (isLiveEdit_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "isLiveEdit")), - BooleanRef::New(ecmaVm, isLiveEdit_.value())); - } - if (sourceMapUrl_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "sourceMapURL")), - Local(StringRef::NewFromUtf8(ecmaVm, sourceMapUrl_->c_str()))); - } - if (hasSourceUrl_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "hasSourceURL")), - BooleanRef::New(ecmaVm, hasSourceUrl_.value())); - } - if (isModule_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "isModule")), - BooleanRef::New(ecmaVm, isModule_.value())); - } - if (length_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "length")), - IntegerRef::New(ecmaVm, length_.value())); - } - if (codeOffset_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "codeOffset")), - IntegerRef::New(ecmaVm, codeOffset_.value())); - } - if (scriptLanguage_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptLanguage")), - Local(StringRef::NewFromUtf8(ecmaVm, scriptLanguage_->c_str()))); - } - if (embedderName_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "embedderName")), - Local(StringRef::NewFromUtf8(ecmaVm, embedderName_->c_str()))); - } - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr ScriptParsed::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -378,23 +158,6 @@ std::unique_ptr ScriptParsed::ToJson() const return object; } -Local AddHeapSnapshotChunk::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "chunk")), - Local(StringRef::NewFromUtf8(ecmaVm, chunk_.c_str()))); - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr AddHeapSnapshotChunk::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -408,45 +171,15 @@ std::unique_ptr AddHeapSnapshotChunk::ToJson() const return object; } -Local ConsoleProfileFinished::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "id")), - Local(StringRef::NewFromUtf8(ecmaVm, id_.c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "location")), - Local(location_->ToObject(ecmaVm))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "profile")), - Local(profile_->ToObject(ecmaVm))); - if (title_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "title")), - Local(StringRef::NewFromUtf8(ecmaVm, title_->c_str()))); - } - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr ConsoleProfileFinished::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("id", id_.c_str()); - if (location_ != nullptr) { - result->Add("location", location_->ToJson()); - } - if (profile_ != nullptr) { - result->Add("profile", profile_->ToJson()); - } + ASSERT(location_ != nullptr); + result->Add("location", location_->ToJson()); + ASSERT(profile_ != nullptr); + result->Add("profile", profile_->ToJson()); if (title_) { result->Add("title", title_->c_str()); } @@ -458,39 +191,13 @@ std::unique_ptr ConsoleProfileFinished::ToJson() const return object; } -Local ConsoleProfileStarted::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "id")), - Local(StringRef::NewFromUtf8(ecmaVm, id_.c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "location")), - Local(location_->ToObject(ecmaVm))); - if (title_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "title")), - Local(StringRef::NewFromUtf8(ecmaVm, title_->c_str()))); - } - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr ConsoleProfileStarted::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("id", id_.c_str()); - if (location_ != nullptr) { - result->Add("location", location_->ToJson()); - } + ASSERT(location_ != nullptr); + result->Add("location", location_->ToJson()); if (title_) { result->Add("title", title_->c_str()); } @@ -502,32 +209,6 @@ std::unique_ptr ConsoleProfileStarted::ToJson() const return object; } -Local PreciseCoverageDeltaUpdate::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "timestamp")), - NumberRef::New(ecmaVm, timestamp_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "occasion")), - Local(StringRef::NewFromUtf8(ecmaVm, occasion_.c_str()))); - size_t len = result_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local result = result_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, result); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), values); - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr PreciseCoverageDeltaUpdate::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -537,6 +218,7 @@ std::unique_ptr PreciseCoverageDeltaUpdate::ToJson() const std::unique_ptr array = PtJson::CreateArray(); size_t len = result_.size(); for (size_t i = 0; i < len; i++) { + ASSERT(result_[i] != nullptr); std::unique_ptr res = result_[i]->ToJson(); array->Push(res); } @@ -549,27 +231,6 @@ std::unique_ptr PreciseCoverageDeltaUpdate::ToJson() const return object; } -Local HeapStatsUpdate::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - size_t len = statsUpdate_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local elem = IntegerRef::New(ecmaVm, statsUpdate_[i]); - values->Set(ecmaVm, i, elem); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "statsUpdate")), values); - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr HeapStatsUpdate::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -588,24 +249,6 @@ std::unique_ptr HeapStatsUpdate::ToJson() const return object; } -Local LastSeenObjectId::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lastSeenObjectId")), - IntegerRef::New(ecmaVm, lastSeenObjectId_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "timestamp")), - NumberRef::New(ecmaVm, timestamp_)); - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr LastSeenObjectId::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -620,30 +263,6 @@ std::unique_ptr LastSeenObjectId::ToJson() const return object; } -Local ReportHeapSnapshotProgress::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "done")), - IntegerRef::New(ecmaVm, done_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "total")), - IntegerRef::New(ecmaVm, total_)); - - if (finished_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "finished")), - BooleanRef::New(ecmaVm, finished_.value())); - } - - Local object = NewObject(ecmaVm); - object->Set(ecmaVm, - StringRef::NewFromUtf8(ecmaVm, "method"), - Local(StringRef::NewFromUtf8(ecmaVm, GetName().c_str()))); - object->Set(ecmaVm, StringRef::NewFromUtf8(ecmaVm, "params"), Local(params)); - - return object; -} - std::unique_ptr ReportHeapSnapshotProgress::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); diff --git a/ecmascript/tooling/base/pt_events.h b/ecmascript/tooling/base/pt_events.h index 8e929052..622b7dfe 100644 --- a/ecmascript/tooling/base/pt_events.h +++ b/ecmascript/tooling/base/pt_events.h @@ -29,7 +29,6 @@ class PtBaseEvents : public PtBaseTypes { public: PtBaseEvents() = default; ~PtBaseEvents() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override = 0; virtual std::string GetName() const = 0; private: @@ -41,7 +40,6 @@ class BreakpointResolved final : public PtBaseEvents { public: BreakpointResolved() = default; ~BreakpointResolved() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override @@ -83,7 +81,6 @@ class Paused final : public PtBaseEvents { public: Paused() = default; ~Paused() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override @@ -208,7 +205,6 @@ class Resumed final : public PtBaseEvents { public: Resumed() = default; ~Resumed() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override @@ -225,7 +221,6 @@ class ScriptFailedToParse final : public PtBaseEvents { public: ScriptFailedToParse() = default; ~ScriptFailedToParse() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override @@ -326,7 +321,7 @@ public: return execContextAuxData_.value_or(Local()); } - ScriptFailedToParse &SetExecutionContextAuxData(const Local &execContextAuxData) + ScriptFailedToParse &SetExecutionContextAuxData(Local execContextAuxData) { execContextAuxData_ = execContextAuxData; return *this; @@ -456,7 +451,7 @@ private: NO_COPY_SEMANTIC(ScriptFailedToParse); NO_MOVE_SEMANTIC(ScriptFailedToParse); - ScriptId scriptId_ {}; + ScriptId scriptId_ {0}; std::string url_ {}; int32_t startLine_ {0}; int32_t startColumn_ {0}; @@ -478,7 +473,6 @@ class ScriptParsed final : public PtBaseEvents { public: ScriptParsed() = default; ~ScriptParsed() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override @@ -595,7 +589,7 @@ public: return execContextAuxData_.value_or(Local()); } - ScriptParsed &SetExecutionContextAuxData(const Local &execContextAuxData) + ScriptParsed &SetExecutionContextAuxData(Local execContextAuxData) { execContextAuxData_ = execContextAuxData; return *this; @@ -725,7 +719,7 @@ private: NO_COPY_SEMANTIC(ScriptParsed); NO_MOVE_SEMANTIC(ScriptParsed); - ScriptId scriptId_ {}; + ScriptId scriptId_ {0}; std::string url_ {}; int32_t startLine_ {0}; int32_t startColumn_ {0}; @@ -748,7 +742,6 @@ class AddHeapSnapshotChunk final : public PtBaseEvents { public: AddHeapSnapshotChunk() = default; ~AddHeapSnapshotChunk() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override @@ -772,7 +765,6 @@ class ConsoleProfileFinished final : public PtBaseEvents { public: ConsoleProfileFinished() = default; ~ConsoleProfileFinished() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -843,7 +835,6 @@ class ConsoleProfileStarted final : public PtBaseEvents { public: ConsoleProfileStarted() = default; ~ConsoleProfileStarted() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -902,7 +893,6 @@ class PreciseCoverageDeltaUpdate final : public PtBaseEvents { public: PreciseCoverageDeltaUpdate() = default; ~PreciseCoverageDeltaUpdate() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override { @@ -955,7 +945,6 @@ class HeapStatsUpdate final : public PtBaseEvents { public: HeapStatsUpdate() = default; ~HeapStatsUpdate() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override @@ -985,7 +974,6 @@ class LastSeenObjectId final : public PtBaseEvents { public: LastSeenObjectId() = default; ~LastSeenObjectId() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override @@ -1027,7 +1015,6 @@ class ReportHeapSnapshotProgress final : public PtBaseEvents { public: ReportHeapSnapshotProgress() = default; ~ReportHeapSnapshotProgress() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const override diff --git a/ecmascript/tooling/base/pt_params.h b/ecmascript/tooling/base/pt_params.h index 7fe6278c..72672f1d 100644 --- a/ecmascript/tooling/base/pt_params.h +++ b/ecmascript/tooling/base/pt_params.h @@ -23,10 +23,9 @@ class PtBaseParams : public PtBaseTypes { public: PtBaseParams() = default; ~PtBaseParams() override = default; - - Local ToObject([[maybe_unused]] const EcmaVM *ecmaVm) const override final + std::unique_ptr ToJson() const override { - return Local(); + UNREACHABLE(); } private: @@ -149,7 +148,7 @@ private: NO_COPY_SEMANTIC(GetScriptSourceParams); NO_MOVE_SEMANTIC(GetScriptSourceParams); - ScriptId scriptId_ {}; + ScriptId scriptId_ {0}; }; class RemoveBreakpointParams : public PtBaseParams { diff --git a/ecmascript/tooling/base/pt_returns.cpp b/ecmascript/tooling/base/pt_returns.cpp index bba89d4e..458c262b 100644 --- a/ecmascript/tooling/base/pt_returns.cpp +++ b/ecmascript/tooling/base/pt_returns.cpp @@ -16,17 +16,6 @@ #include "ecmascript/tooling/base/pt_returns.h" namespace panda::ecmascript::tooling { -Local EnableReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "debuggerId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(debuggerId_).c_str()))); - - return result; -} - std::unique_ptr EnableReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -36,24 +25,6 @@ std::unique_ptr EnableReturns::ToJson() const return result; } -Local SetBreakpointByUrlReturns::ToObject(const EcmaVM *ecmaVm) const -{ - size_t len = locations_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local location = locations_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, location); - } - - Local result = NewObject(ecmaVm); - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "breakpointId")), - Local(StringRef::NewFromUtf8(ecmaVm, id_.c_str()))); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "locations")), values); - - return result; -} - std::unique_ptr SetBreakpointByUrlReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -70,51 +41,20 @@ std::unique_ptr SetBreakpointByUrlReturns::ToJson() const return result; } -Local EvaluateOnCallFrameReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - Local location = result_->ToObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), Local(location)); - if (exceptionDetails_) { - Local exception = exceptionDetails_.value()->ToObject(ecmaVm); - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "exceptionDetails")), - Local(exception)); - } - - return result; -} - std::unique_ptr EvaluateOnCallFrameReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - if (result_ != nullptr) { - result->Add("result", result_->ToJson()); - } - if (exceptionDetails_ && exceptionDetails_.value() != nullptr) { + ASSERT(result_ != nullptr); + result->Add("result", result_->ToJson()); + if (exceptionDetails_) { + ASSERT(exceptionDetails_.value() != nullptr); result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); } return result; } -Local GetPossibleBreakpointsReturns::ToObject(const EcmaVM *ecmaVm) const -{ - size_t len = locations_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local location = locations_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, location); - } - - Local result = NewObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "locations")), values); - - return result; -} - std::unique_ptr GetPossibleBreakpointsReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -130,22 +70,6 @@ std::unique_ptr GetPossibleBreakpointsReturns::ToJson() const return result; } -Local GetScriptSourceReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptSource")), - Local(StringRef::NewFromUtf8(ecmaVm, scriptSource_.c_str()))); - if (bytecode_) { - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "bytecode")), - Local(StringRef::NewFromUtf8(ecmaVm, bytecode_->c_str()))); - } - - return result; -} - std::unique_ptr GetScriptSourceReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -158,20 +82,6 @@ std::unique_ptr GetScriptSourceReturns::ToJson() const return result; } -Local RestartFrameReturns::ToObject(const EcmaVM *ecmaVm) const -{ - size_t len = callFrames_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local location = callFrames_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, location); - } - - Local result = NewObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "callFrames")), values); - return result; -} - std::unique_ptr RestartFrameReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -187,21 +97,6 @@ std::unique_ptr RestartFrameReturns::ToJson() const return result; } -Local SearchInContentReturns::ToObject(const EcmaVM *ecmaVm) const -{ - size_t len = result_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local res = result_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, res); - } - - Local result = NewObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), values); - - return result; -} - std::unique_ptr SearchInContentReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -217,40 +112,12 @@ std::unique_ptr SearchInContentReturns::ToJson() const return result; } -Local SetBreakpointReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "breakpointId")), - Local(StringRef::NewFromUtf8(ecmaVm, breakpointId_.c_str()))); - - Local location = location_->ToObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "actualLocation")), - Local(location)); - - return result; -} - std::unique_ptr SetBreakpointReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("breakpointId", breakpointId_.c_str()); - if (location_ != nullptr) { - result->Add("actualLocation", location_->ToJson()); - } - - return result; -} - -Local SetInstrumentationBreakpointReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "breakpointId")), - Local(StringRef::NewFromUtf8(ecmaVm, breakpointId_.c_str()))); + result->Add("actualLocation", location_->ToJson()); return result; } @@ -264,36 +131,6 @@ std::unique_ptr SetInstrumentationBreakpointReturns::ToJson() const return result; } -Local SetScriptSourceReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - if (callFrames_) { - const std::vector> &callFrame = callFrames_.value(); - size_t len = callFrame.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local location = callFrame[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, location); - } - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "callFrames")), values); - } - - if (stackChanged_) { - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "stackChanged")), - BooleanRef::New(ecmaVm, stackChanged_.value())); - } - - if (exceptionDetails_) { - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "exceptionDetails")), - Local(exceptionDetails_.value()->ToObject(ecmaVm))); - } - - return result; -} - std::unique_ptr SetScriptSourceReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -310,48 +147,9 @@ std::unique_ptr SetScriptSourceReturns::ToJson() const if (stackChanged_) { result->Add("stackChanged", stackChanged_.value()); } - if (exceptionDetails_ && exceptionDetails_.value() != nullptr) { - result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); - } - - return result; -} - -Local GetPropertiesReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - size_t len = result_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local descriptor = result_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, descriptor); - } - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), values); - if (internalPropertyDescripties_) { - auto &descripties = internalPropertyDescripties_.value(); - len = descripties.size(); - values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local descriptor = descripties[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, descriptor); - } - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "internalProperties")), values); - } - if (privateProperties_) { - auto &descripties = privateProperties_.value(); - len = descripties.size(); - values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local descriptor = descripties[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, descriptor); - } - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "privateProperties")), values); - } if (exceptionDetails_) { - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "exceptionDetails")), - Local(exceptionDetails_.value()->ToObject(ecmaVm))); + ASSERT(exceptionDetails_.value() != nullptr); + result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); } return result; @@ -386,75 +184,32 @@ std::unique_ptr GetPropertiesReturns::ToJson() const } result->Add("privateProperties", array); } - if (exceptionDetails_ && exceptionDetails_.value() != nullptr) { + if (exceptionDetails_) { + ASSERT(exceptionDetails_.value() != nullptr); result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); } return result; } -Local CallFunctionOnReturns::ToObject(const EcmaVM *ecmaVm) const -{ - // For this - Local returns = NewObject(ecmaVm); - - // For this.result_ - Local result = result_->ToObject(ecmaVm); - returns->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), - Local(result)); - // For this.exceptionDetails_ - if (exceptionDetails_) { - returns->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "exceptionDetails")), - Local(exceptionDetails_.value()->ToObject(ecmaVm))); - } - - return returns; -} - std::unique_ptr CallFunctionOnReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - if (result_ != nullptr) { - result->Add("result", result_->ToJson()); - } - if (exceptionDetails_ && exceptionDetails_.value() != nullptr) { + result->Add("result", result_->ToJson()); + if (exceptionDetails_) { + ASSERT(exceptionDetails_.value() != nullptr); result->Add("exceptionDetails", exceptionDetails_.value()->ToJson()); } return result; } -Local StopSamplingReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - if (profile_ != nullptr) { - Local profile = profile_->ToObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "profile")), - Local(profile)); - } - return result; -} - std::unique_ptr StopSamplingReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - if (profile_ != nullptr) { - result->Add("profile", profile_->ToJson()); - } - - return result; -} - -Local GetHeapObjectIdReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "heapSnapshotObjectId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(heapSnapshotObjectId_).c_str()))); + result->Add("profile", profile_->ToJson()); return result; } @@ -468,36 +223,11 @@ std::unique_ptr GetHeapObjectIdReturns::ToJson() const return result; } -Local GetObjectByHeapObjectIdReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - if (remoteObjectResult_ != nullptr) { - Local remoteObjectResult = remoteObjectResult_->ToObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), - Local(remoteObjectResult)); - } - - return result; -} - std::unique_ptr GetObjectByHeapObjectIdReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - if (remoteObjectResult_ != nullptr) { - result->Add("result", remoteObjectResult_->ToJson()); - } - - return result; -} - -Local StopReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - Local profile = profile_->ToObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "profile")), Local(profile)); + result->Add("result", remoteObjectResult_->ToJson()); return result; } @@ -506,23 +236,7 @@ std::unique_ptr StopReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - if (profile_ != nullptr) { - result->Add("profile", profile_->ToJson()); - } - - return result; -} - -Local GetHeapUsageReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "usedSize")), - NumberRef::New(ecmaVm, usedSize_)); - result->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "totalSize")), - NumberRef::New(ecmaVm, totalSize_)); + result->Add("profile", profile_->ToJson()); return result; } @@ -537,21 +251,6 @@ std::unique_ptr GetHeapUsageReturns::ToJson() const return result; } -Local GetBestEffortCoverageReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - size_t len = result_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local scriptCoverage = result_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, scriptCoverage); - } - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), values); - - return result; -} - std::unique_ptr GetBestEffortCoverageReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -567,15 +266,6 @@ std::unique_ptr GetBestEffortCoverageReturns::ToJson() const return result; } -Local StartPreciseCoverageReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "timestamp")), - NumberRef::New(ecmaVm, timestamp_)); - - return result; -} - std::unique_ptr StartPreciseCoverageReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -585,23 +275,6 @@ std::unique_ptr StartPreciseCoverageReturns::ToJson() const return result; } -Local TakePreciseCoverageReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local returns = NewObject(ecmaVm); - - size_t len = result_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local scriptCoverage = result_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, scriptCoverage); - } - returns->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), values); - returns->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "timestamp")), - NumberRef::New(ecmaVm, timestamp_)); - - return returns; -} - std::unique_ptr TakePreciseCoverageReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -618,20 +291,6 @@ std::unique_ptr TakePreciseCoverageReturns::ToJson() const return result; } -Local TakeTypeProfileReturns::ToObject(const EcmaVM *ecmaVm) const -{ - Local result = NewObject(ecmaVm); - - size_t len = result_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local scriptTypeProfile = result_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, scriptTypeProfile); - } - result->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "result")), values); - return result; -} - std::unique_ptr TakeTypeProfileReturns::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); diff --git a/ecmascript/tooling/base/pt_returns.h b/ecmascript/tooling/base/pt_returns.h index 6c46925d..12227940 100644 --- a/ecmascript/tooling/base/pt_returns.h +++ b/ecmascript/tooling/base/pt_returns.h @@ -23,11 +23,6 @@ class PtBaseReturns : public PtBaseTypes { public: PtBaseReturns() = default; ~PtBaseReturns() override = default; - - Local ToObject(const EcmaVM *ecmaVm) const override - { - return NewObject(ecmaVm); - } std::unique_ptr ToJson() const override { return PtJson::CreateObject(); @@ -43,7 +38,6 @@ public: explicit EnableReturns(UniqueDebuggerId id) : debuggerId_(id) {} ~EnableReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -61,7 +55,6 @@ public: {} ~SetBreakpointByUrlReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -80,7 +73,6 @@ public: : result_(std::move(result)), exceptionDetails_(std::move(exceptionDetails)) {} ~EvaluateOnCallFrameReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -99,7 +91,6 @@ public: {} ~GetPossibleBreakpointsReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -117,7 +108,6 @@ public: {} ~GetScriptSourceReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -135,7 +125,6 @@ public: : callFrames_(std::move(callFrames)) {} ~RestartFrameReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -151,7 +140,6 @@ public: explicit SearchInContentReturns(std::vector> result) : result_(std::move(result)) {} ~SearchInContentReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -168,7 +156,6 @@ public: : breakpointId_(id), location_(std::move(location)) {} ~SetBreakpointReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -184,7 +171,6 @@ public: explicit SetInstrumentationBreakpointReturns(const std::string &id) : breakpointId_(id) {} ~SetInstrumentationBreakpointReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -205,7 +191,6 @@ public: exceptionDetails_(std::move(exceptionDetails)) {} ~SetScriptSourceReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -230,7 +215,6 @@ public: exceptionDetails_(std::move(exceptionDetails)) {} ~GetPropertiesReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -252,7 +236,6 @@ public: exceptionDetails_(std::move(exceptionDetails)) {} ~CallFunctionOnReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -271,7 +254,6 @@ public: {} ~StopSamplingReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -289,7 +271,6 @@ public: {} ~GetHeapObjectIdReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -307,7 +288,6 @@ public: {} ~GetObjectByHeapObjectIdReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -322,7 +302,6 @@ class StopReturns : public PtBaseReturns { public: explicit StopReturns(std::unique_ptr profile) : profile_(std::move(profile)) {} ~StopReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -338,7 +317,6 @@ public: explicit GetHeapUsageReturns(double usedSize, double totalSize) : usedSize_(usedSize), totalSize_(totalSize) {} ~GetHeapUsageReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -356,7 +334,6 @@ public: : result_(std::move(result)) {} ~GetBestEffortCoverageReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -371,7 +348,6 @@ class StartPreciseCoverageReturns : public PtBaseReturns { public: explicit StartPreciseCoverageReturns(int64_t tamp) : timestamp_(tamp) {} ~StartPreciseCoverageReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -389,7 +365,6 @@ public: timestamp_(tamp) {} ~TakePreciseCoverageReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -407,7 +382,6 @@ public: : result_(std::move(result)) {} ~TakeTypeProfileReturns() override = default; - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: diff --git a/ecmascript/tooling/base/pt_script.h b/ecmascript/tooling/base/pt_script.h index a7425bb8..50f24dfa 100644 --- a/ecmascript/tooling/base/pt_script.h +++ b/ecmascript/tooling/base/pt_script.h @@ -105,7 +105,7 @@ private: NO_COPY_SEMANTIC(PtScript); NO_MOVE_SEMANTIC(PtScript); - ScriptId scriptId_ {}; // start from 0, such as "0","1","2"... + ScriptId scriptId_ {0}; // start from 0, such as "0","1","2"... std::string fileName_ {}; // binary file name, such as xx.bin std::string url_ {}; // source file name, such as xx.js std::string hash_ {}; // js source file hash code diff --git a/ecmascript/tooling/base/pt_types.cpp b/ecmascript/tooling/base/pt_types.cpp index 5cb250de..12879240 100644 --- a/ecmascript/tooling/base/pt_types.cpp +++ b/ecmascript/tooling/base/pt_types.cpp @@ -90,14 +90,7 @@ const std::string RemoteObject::MapIteratorDescription = "MapIterator"; // NOLI const std::string RemoteObject::WeakMapDescription = "WeakMap"; // NOLINT (readability-identifier-naming) const std::string RemoteObject::WeakSetDescription = "WeakSet"; // NOLINT (readability-identifier-naming) -static constexpr uint64_t DOUBLE_SIGN_MASK = 0x8000000000000000ULL; - -Local PtBaseTypes::NewObject(const EcmaVM *ecmaVm) -{ - return ObjectRef::New(ecmaVm); -} - -std::unique_ptr RemoteObject::FromTagged(const EcmaVM *ecmaVm, const Local &tagged) +std::unique_ptr RemoteObject::FromTagged(const EcmaVM *ecmaVm, Local tagged) { if (tagged->IsNull() || tagged->IsUndefined() || tagged->IsBoolean() || tagged->IsNumber() || @@ -105,10 +98,10 @@ std::unique_ptr RemoteObject::FromTagged(const EcmaVM *ecmaVm, con return std::make_unique(ecmaVm, tagged); } if (tagged->IsString()) { - return std::make_unique(ecmaVm, tagged); + return std::make_unique(ecmaVm, Local(tagged)); } if (tagged->IsSymbol()) { - return std::make_unique(ecmaVm, tagged); + return std::make_unique(ecmaVm, Local(tagged)); } if (tagged->IsFunction()) { return std::make_unique(ecmaVm, tagged); @@ -169,30 +162,85 @@ std::unique_ptr RemoteObject::FromTagged(const EcmaVM *ecmaVm, con return object; } -PrimitiveRemoteObject::PrimitiveRemoteObject(const EcmaVM *ecmaVm, const Local &tagged) +PrimitiveRemoteObject::PrimitiveRemoteObject(const EcmaVM *ecmaVm, Local tagged) { if (tagged->IsNull()) { - this->SetType(ObjectType::Object).SetSubType(ObjectSubType::Null).SetValue(tagged); + SetType(ObjectType::Object).SetSubType(ObjectSubType::Null); } else if (tagged->IsBoolean()) { - this->SetType(ObjectType::Boolean).SetValue(tagged); + std::string description = tagged->IsTrue() ? "true" : "false"; + SetType(ObjectType::Boolean) + .SetValue(tagged) + .SetUnserializableValue(description) + .SetDescription(description); } else if (tagged->IsUndefined()) { - this->SetType(ObjectType::Undefined); + SetType(ObjectType::Undefined); } else if (tagged->IsNumber()) { - this->SetType(ObjectType::Number) - .SetDescription(DebuggerApi::ToStdString(tagged->ToString(ecmaVm))); - double val = Local(tagged)->Value(); - if (!std::isfinite(val) || (val == 0 && ((bit_cast(val) & DOUBLE_SIGN_MASK) == DOUBLE_SIGN_MASK))) { - this->SetUnserializableValue(this->GetDescription()); - } else { - this->SetValue(tagged); - } + std::string description = tagged->ToString(ecmaVm)->ToString(); + SetType(ObjectType::Number) + .SetValue(tagged) + .SetUnserializableValue(description) + .SetDescription(description); } else if (tagged->IsBigInt()) { - std::string literal = tagged->ToString(ecmaVm)->ToString() + "n"; // n : BigInt literal postfix - this->SetType(ObjectType::Bigint).SetValue(StringRef::NewFromUtf8(ecmaVm, literal.data())); + std::string description = tagged->ToString(ecmaVm)->ToString() + "n"; // n : BigInt literal postfix + SetType(ObjectType::Bigint) + .SetValue(tagged) + .SetUnserializableValue(description) + .SetDescription(description); } } -std::string ObjectRemoteObject::DescriptionForObject(const EcmaVM *ecmaVm, const Local &tagged) +StringRemoteObject::StringRemoteObject([[maybe_unused]] const EcmaVM *ecmaVm, Local tagged) +{ + std::string description = tagged->ToString(); + SetType(RemoteObject::TypeName::String) + .SetValue(tagged) + .SetUnserializableValue(description) + .SetDescription(description); +} + +SymbolRemoteObject::SymbolRemoteObject(const EcmaVM *ecmaVm, Local tagged) +{ + std::string description = DescriptionForSymbol(ecmaVm, tagged); + SetType(RemoteObject::TypeName::Symbol) + .SetValue(tagged) + .SetUnserializableValue(description) + .SetDescription(description); +} + +FunctionRemoteObject::FunctionRemoteObject(const EcmaVM *ecmaVm, Local tagged) +{ + std::string description = DescriptionForFunction(ecmaVm, tagged); + SetType(RemoteObject::TypeName::Function) + .SetClassName(RemoteObject::ClassName::Function) + .SetValue(tagged) + .SetUnserializableValue(description) + .SetDescription(description); +} + +ObjectRemoteObject::ObjectRemoteObject(const EcmaVM *ecmaVm, Local tagged, + const std::string &classname) +{ + std::string description = DescriptionForObject(ecmaVm, tagged); + SetType(RemoteObject::TypeName::Object) + .SetClassName(classname) + .SetValue(tagged) + .SetUnserializableValue(description) + .SetDescription(description); +} + +ObjectRemoteObject::ObjectRemoteObject(const EcmaVM *ecmaVm, Local tagged, + const std::string &classname, const std::string &subtype) +{ + std::string description = DescriptionForObject(ecmaVm, tagged); + SetType(RemoteObject::TypeName::Object) + .SetSubType(subtype) + .SetClassName(classname) + .SetValue(tagged) + .SetUnserializableValue(description) + .SetDescription(description); +} + +std::string ObjectRemoteObject::DescriptionForObject(const EcmaVM *ecmaVm, Local tagged) { if (tagged->IsArray(ecmaVm)) { return DescriptionForArray(ecmaVm, Local(tagged)); @@ -242,60 +290,59 @@ std::string ObjectRemoteObject::DescriptionForObject(const EcmaVM *ecmaVm, const return RemoteObject::ObjectDescription; } -std::string ObjectRemoteObject::DescriptionForArray(const EcmaVM *ecmaVm, const Local &tagged) +std::string ObjectRemoteObject::DescriptionForArray(const EcmaVM *ecmaVm, Local tagged) { std::string description = "Array(" + std::to_string(tagged->Length(ecmaVm)) + ")"; return description; } -std::string ObjectRemoteObject::DescriptionForRegexp(const EcmaVM *ecmaVm, const Local &tagged) +std::string ObjectRemoteObject::DescriptionForRegexp(const EcmaVM *ecmaVm, Local tagged) { - std::string regexpSource = DebuggerApi::ToStdString(tagged->GetOriginalSource(ecmaVm)); + std::string regexpSource = tagged->GetOriginalSource(ecmaVm)->ToString(); std::string description = "/" + regexpSource + "/"; return description; } -std::string ObjectRemoteObject::DescriptionForDate(const EcmaVM *ecmaVm, const Local &tagged) +std::string ObjectRemoteObject::DescriptionForDate(const EcmaVM *ecmaVm, Local tagged) { - std::string description = DebuggerApi::ToStdString(tagged->ToString(ecmaVm)); + std::string description = tagged->ToString(ecmaVm)->ToString(); return description; } -std::string ObjectRemoteObject::DescriptionForMap(const Local &tagged) +std::string ObjectRemoteObject::DescriptionForMap(Local tagged) { std::string description = ("Map(" + std::to_string(tagged->GetSize()) + ")"); return description; } -std::string ObjectRemoteObject::DescriptionForSet(const Local &tagged) +std::string ObjectRemoteObject::DescriptionForSet(Local tagged) { std::string description = ("Set(" + std::to_string(tagged->GetSize()) + ")"); return description; } -std::string ObjectRemoteObject::DescriptionForError(const EcmaVM *ecmaVm, const Local &tagged) +std::string ObjectRemoteObject::DescriptionForError(const EcmaVM *ecmaVm, Local tagged) { // add message Local stack = StringRef::NewFromUtf8(ecmaVm, "message"); Local result = Local(tagged)->Get(ecmaVm, stack); - return DebuggerApi::ToStdString(result->ToString(ecmaVm)); + return result->ToString(ecmaVm)->ToString(); } -std::string ObjectRemoteObject::DescriptionForArrayBuffer(const EcmaVM *ecmaVm, const Local &tagged) +std::string ObjectRemoteObject::DescriptionForArrayBuffer(const EcmaVM *ecmaVm, Local tagged) { int32_t len = tagged->ByteLength(ecmaVm); std::string description = ("ArrayBuffer(" + std::to_string(len) + ")"); return description; } -std::string SymbolRemoteObject::DescriptionForSymbol(const EcmaVM *ecmaVm, const Local &tagged) const +std::string SymbolRemoteObject::DescriptionForSymbol(const EcmaVM *ecmaVm, Local tagged) const { - std::string description = - "Symbol(" + DebuggerApi::ToStdString(tagged->GetDescription(ecmaVm)) + ")"; + std::string description = "Symbol(" + tagged->GetDescription(ecmaVm)->ToString() + ")"; return description; } -std::string FunctionRemoteObject::DescriptionForFunction(const EcmaVM *ecmaVm, const Local &tagged) const +std::string FunctionRemoteObject::DescriptionForFunction(const EcmaVM *ecmaVm, Local tagged) const { std::string sourceCode; if (tagged->IsNative(ecmaVm)) { @@ -304,93 +351,10 @@ std::string FunctionRemoteObject::DescriptionForFunction(const EcmaVM *ecmaVm, c sourceCode = "[js code]"; } Local name = tagged->GetName(ecmaVm); - std::string description = "function " + DebuggerApi::ToStdString(name) + "( { " + sourceCode + " }"; + std::string description = "function " + name->ToString() + "( { " + sourceCode + " }"; return description; } -std::unique_ptr RemoteObject::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create params is nullptr"; - return nullptr; - } - std::string error; - auto remoteObject = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "type"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - auto type = DebuggerApi::ToStdString(result); - if (ObjectType::Valid(type)) { - remoteObject->type_ = type; - } else { - error += "'type' is invalid;"; - } - } else { - error += "'type' should be a String;"; - } - } else { - error += "should contain 'type';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "subtype"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - auto type = DebuggerApi::ToStdString(result); - if (ObjectSubType::Valid(type)) { - remoteObject->subType_ = type; - } else { - error += "'subtype' is invalid;"; - } - } else { - error += "'subtype' should be a String;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "className"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - remoteObject->className_ = DebuggerApi::ToStdString(result); - } else { - error += "'className' should be a String;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "value"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - remoteObject->value_ = result; - } - result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "unserializableValue"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - remoteObject->unserializableValue_ = DebuggerApi::ToStdString(result); - } else { - error += "'unserializableValue' should be a String;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "description"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - remoteObject->description_ = DebuggerApi::ToStdString(result); - } else { - error += "'description' should be a String;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "objectId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - remoteObject->objectId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'objectId' should be a String;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "RemoteObject::Create " << error; - return nullptr; - } - - return remoteObject; -} - std::unique_ptr RemoteObject::Create(const PtJson ¶ms) { std::string error; @@ -461,45 +425,6 @@ std::unique_ptr RemoteObject::Create(const PtJson ¶ms) return remoteObject; } -Local RemoteObject::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "type")), - Local(StringRef::NewFromUtf8(ecmaVm, type_.c_str()))); - if (subType_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "subtype")), - Local(StringRef::NewFromUtf8(ecmaVm, subType_->c_str()))); - } - if (className_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "className")), - Local(StringRef::NewFromUtf8(ecmaVm, className_->c_str()))); - } - if (value_) { - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "value")), value_.value()); - } - if (unserializableValue_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "unserializableValue")), - Local(StringRef::NewFromUtf8(ecmaVm, unserializableValue_->c_str()))); - } - if (description_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "description")), - Local(StringRef::NewFromUtf8(ecmaVm, description_->c_str()))); - } - if (objectId_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "objectId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(objectId_.value()).c_str()))); - } - - return params; -} - std::unique_ptr RemoteObject::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -524,103 +449,6 @@ std::unique_ptr RemoteObject::ToJson() const return result; } -std::unique_ptr ExceptionDetails::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "ExceptionDetails::Create params is nullptr"; - return nullptr; - } - std::string error; - auto exceptionDetails = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "exceptionId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - exceptionDetails->exceptionId_ = static_cast(Local(result)->Value()); - } else { - error += "'exceptionId' should be a Number;"; - } - } else { - error += "should contain 'exceptionId';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "text"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - exceptionDetails->text_ = DebuggerApi::ToStdString(result); - } else { - error += "'text' should be a String;"; - } - } else { - error += "should contain 'text';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - exceptionDetails->lineNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'lineNumber' should be a Number;"; - } - } else { - error += "should contain 'lineNumber';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - exceptionDetails->columnNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'columnNumber' should be a Number;"; - } - } else { - error += "should contain 'columnNumber';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - exceptionDetails->scriptId_ = static_cast(DebuggerApi::StringToInt(result)); - } else { - error += "'scriptId' should be a String;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "url"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - exceptionDetails->url_ = DebuggerApi::ToStdString(result); - } else { - error += "'url' should be a String;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "exception"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'exception' format error;"; - } else { - exceptionDetails->exception_ = std::move(obj); - } - } else { - error += "'exception' should be an Object;"; - } - } - - result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "executionContextId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - exceptionDetails->executionContextId_ = static_cast(Local(result)->Value()); - } else { - error += "'executionContextId' should be a Number;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "ExceptionDetails::Create " << error; - return nullptr; - } - - return exceptionDetails; -} - std::unique_ptr ExceptionDetails::Create(const PtJson ¶ms) { std::string error; @@ -679,10 +507,10 @@ std::unique_ptr ExceptionDetails::Create(const PtJson ¶ms) ret = params.GetObject("exception", &exception); if (ret == Result::SUCCESS) { std::unique_ptr obj = RemoteObject::Create(*exception); - if (obj != nullptr) { - exceptionDetails->exception_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'exception' format error;"; + } else { + exceptionDetails->exception_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'exception';"; @@ -704,45 +532,6 @@ std::unique_ptr ExceptionDetails::Create(const PtJson ¶ms) return exceptionDetails; } -Local ExceptionDetails::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "exceptionId")), - IntegerRef::New(ecmaVm, exceptionId_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "text")), - Local(StringRef::NewFromUtf8(ecmaVm, text_.c_str()))); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, lineNumber_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, columnNumber_)); - if (scriptId_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(scriptId_.value()).c_str()))); - } - if (url_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "url")), - Local(StringRef::NewFromUtf8(ecmaVm, url_->c_str()))); - } - if (exception_) { - ASSERT(exception_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "exception")), - Local(exception_.value()->ToObject(ecmaVm))); - } - if (executionContextId_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "executionContextId")), - IntegerRef::New(ecmaVm, executionContextId_.value())); - } - - return params; -} - std::unique_ptr ExceptionDetails::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -758,7 +547,8 @@ std::unique_ptr ExceptionDetails::ToJson() const if (url_) { result->Add("url", url_->c_str()); } - if (exception_ && exception_.value() != nullptr) { + if (exception_) { + ASSERT(exception_.value() != nullptr); result->Add("exception", exception_.value()->ToJson()); } if (executionContextId_) { @@ -768,48 +558,6 @@ std::unique_ptr ExceptionDetails::ToJson() const return result; } -std::unique_ptr InternalPropertyDescriptor::Create(const EcmaVM *ecmaVm, - const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "InternalPropertyDescriptor::Create params is nullptr"; - return nullptr; - } - std::string error; - auto internalPropertyDescriptor = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "name"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - internalPropertyDescriptor->name_ = DebuggerApi::ToStdString(result); - } else { - error += "'name' should be a String;"; - } - } else { - error += "should contain 'name';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "value"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'value' format error;"; - } else { - internalPropertyDescriptor->value_ = std::move(obj); - } - } else { - error += "'value' should be an Object;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "InternalPropertyDescriptor::Create " << error; - return nullptr; - } - - return internalPropertyDescriptor; -} - std::unique_ptr InternalPropertyDescriptor::Create(const PtJson ¶ms) { std::string error; @@ -828,10 +576,10 @@ std::unique_ptr InternalPropertyDescriptor::Create(c ret = params.GetObject("value", &value); if (ret == Result::SUCCESS) { std::unique_ptr obj = RemoteObject::Create(*value); - if (obj != nullptr) { - internalPropertyDescriptor->value_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'value' format error;"; + } else { + internalPropertyDescriptor->value_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'value';"; @@ -845,103 +593,19 @@ std::unique_ptr InternalPropertyDescriptor::Create(c return internalPropertyDescriptor; } -Local InternalPropertyDescriptor::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "name")), - Local(StringRef::NewFromUtf8(ecmaVm, name_.c_str()))); - if (value_) { - ASSERT(value_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "value")), - Local(value_.value()->ToObject(ecmaVm))); - } - - return params; -} - std::unique_ptr InternalPropertyDescriptor::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("name", name_.c_str()); - if (value_ && value_.value() != nullptr) { + if (value_) { + ASSERT(value_.value() != nullptr); result->Add("value", value_.value()->ToJson()); } return result; } -std::unique_ptr PrivatePropertyDescriptor::Create(const EcmaVM *ecmaVm, - const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "PrivatePropertyDescriptor::Create params is nullptr"; - return nullptr; - } - std::string error; - auto propertyDescriptor = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "name"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - propertyDescriptor->name_ = DebuggerApi::ToStdString(result); - } else { - error += "'name' should be a String;"; - } - } else { - error += "should contain 'name';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "value"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'value' format error;"; - } else { - propertyDescriptor->value_ = std::move(obj); - } - } else { - error += "'value' should be a Object;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "get"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'get' format error;"; - } else { - propertyDescriptor->get_ = std::move(obj); - } - } else { - error += "'get' should be an Object;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "set"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'set' format error;"; - } else { - propertyDescriptor->set_ = std::move(obj); - } - } else { - error += "'set' should be an Object;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "PrivatePropertyDescriptor::Create " << error; - return nullptr; - } - - return propertyDescriptor; -} - std::unique_ptr PrivatePropertyDescriptor::Create(const PtJson ¶ms) { std::string error; @@ -961,10 +625,10 @@ std::unique_ptr PrivatePropertyDescriptor::Create(con std::unique_ptr obj; if (ret == Result::SUCCESS) { obj = RemoteObject::Create(*value); - if (obj != nullptr) { - privatePropertyDescriptor->value_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'value' format error;"; + } else { + privatePropertyDescriptor->value_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'value';"; @@ -974,10 +638,10 @@ std::unique_ptr PrivatePropertyDescriptor::Create(con ret = params.GetObject("get", &get); if (ret == Result::SUCCESS) { obj = RemoteObject::Create(*get); - if (obj != nullptr) { - privatePropertyDescriptor->get_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'get' format error;"; + } else { + privatePropertyDescriptor->get_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'get';"; @@ -987,10 +651,10 @@ std::unique_ptr PrivatePropertyDescriptor::Create(con ret = params.GetObject("set", &set); if (ret == Result::SUCCESS) { obj = RemoteObject::Create(*set); - if (obj != nullptr) { - privatePropertyDescriptor->set_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'set' format error;"; + } else { + privatePropertyDescriptor->set_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'set';"; @@ -1004,47 +668,21 @@ std::unique_ptr PrivatePropertyDescriptor::Create(con return privatePropertyDescriptor; } -Local PrivatePropertyDescriptor::ToObject(const EcmaVM *ecmaVm) const +std::unique_ptr PrivatePropertyDescriptor::ToJson() const { - Local params = NewObject(ecmaVm); + std::unique_ptr result = PtJson::CreateObject(); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "name")), - Local(StringRef::NewFromUtf8(ecmaVm, name_.c_str()))); + result->Add("name", name_.c_str()); if (value_) { ASSERT(value_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "value")), - Local(value_.value()->ToObject(ecmaVm))); + result->Add("value", value_.value()->ToJson()); } if (get_) { ASSERT(get_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "get")), - Local(get_.value()->ToObject(ecmaVm))); + result->Add("get", get_.value()->ToJson()); } if (set_) { ASSERT(set_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "set")), - Local(set_.value()->ToObject(ecmaVm))); - } - - return params; -} - -std::unique_ptr PrivatePropertyDescriptor::ToJson() const -{ - std::unique_ptr result = PtJson::CreateObject(); - - result->Add("name", name_.c_str()); - if (value_ && value_.value() != nullptr) { - result->Add("value", value_.value()->ToJson()); - } - if (get_ && get_.value() != nullptr) { - result->Add("get", get_.value()->ToJson()); - } - if (set_ && set_.value() != nullptr) { result->Add("set", set_.value()->ToJson()); } @@ -1052,18 +690,17 @@ std::unique_ptr PrivatePropertyDescriptor::ToJson() const } std::unique_ptr PropertyDescriptor::FromProperty(const EcmaVM *ecmaVm, - const Local &name, const PropertyAttribute &property) + Local name, const PropertyAttribute &property) { std::unique_ptr debuggerProperty = std::make_unique(); std::string nameStr; if (name->IsSymbol()) { Local symbol(name); - nameStr = - "Symbol(" + DebuggerApi::ToStdString(Local(name)->GetDescription(ecmaVm)) + ")"; + nameStr = "Symbol(" + Local(name)->GetDescription(ecmaVm)->ToString() + ")"; debuggerProperty->symbol_ = RemoteObject::FromTagged(ecmaVm, name); } else { - nameStr = DebuggerApi::ToStdString(name->ToString(ecmaVm)); + nameStr = name->ToString(ecmaVm)->ToString(); } debuggerProperty->name_ = nameStr; @@ -1086,142 +723,18 @@ std::unique_ptr PropertyDescriptor::FromProperty(const EcmaV return debuggerProperty; } -std::unique_ptr PropertyDescriptor::Create(const EcmaVM *ecmaVm, const Local ¶ms) +std::unique_ptr PropertyDescriptor::Create(const PtJson ¶ms) { - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "PropertyDescriptor::Create params is nullptr"; - return nullptr; - } std::string error; auto propertyDescriptor = std::make_unique(); + Result ret; - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "name"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - propertyDescriptor->name_ = DebuggerApi::ToStdString(result); - } else { - error += "'name' should be a String;"; - } + std::string name; + ret = params.GetString("name", &name); + if (ret == Result::SUCCESS) { + propertyDescriptor->name_ = std::move(name); } else { - error += "should contain 'name';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "value"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'value' format error;"; - } else { - propertyDescriptor->value_ = std::move(obj); - } - } else { - error += "'value' should be an Object;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "writable"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - propertyDescriptor->writable_ = result->IsTrue(); - } else { - error += "'writable' should be a Boolean;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "get"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'get' format error;"; - } else { - propertyDescriptor->get_ = std::move(obj); - } - } else { - error += "'get' should be an Object;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "set"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'set' format error;"; - } else { - propertyDescriptor->set_ = std::move(obj); - } - } else { - error += "'set' should be an Object;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "configurable"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - propertyDescriptor->configurable_ = result->IsTrue(); - } else { - error += "'configurable' should be a Boolean;"; - } - } else { - error += "should contain 'configurable';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "enumerable"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - propertyDescriptor->enumerable_ = result->IsTrue(); - } else { - error += "'enumerable' should be a Boolean;"; - } - } else { - error += "should contain 'enumerable';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "wasThrown"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - propertyDescriptor->wasThrown_ = result->IsTrue(); - } else { - error += "'wasThrown' should be a Boolean;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "isOwn"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - propertyDescriptor->isOwn_ = result->IsTrue(); - } else { - error += "'isOwn' should be a Boolean;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "symbol"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'symbol' format error;"; - } else { - propertyDescriptor->symbol_ = std::move(obj); - } - } else { - error += "'symbol' should be an Object;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "PropertyDescriptor::Create " << error; - return nullptr; - } - - return propertyDescriptor; -} - -std::unique_ptr PropertyDescriptor::Create(const PtJson ¶ms) -{ - std::string error; - auto propertyDescriptor = std::make_unique(); - Result ret; - - std::string name; - ret = params.GetString("name", &name); - if (ret == Result::SUCCESS) { - propertyDescriptor->name_ = std::move(name); - } else { - error += "Unknown 'name';"; + error += "Unknown 'name';"; } std::unique_ptr value; @@ -1229,10 +742,10 @@ std::unique_ptr PropertyDescriptor::Create(const PtJson &par ret = params.GetObject("value", &value); if (ret == Result::SUCCESS) { obj = RemoteObject::Create(*value); - if (obj != nullptr) { - propertyDescriptor->value_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'value' format error;"; + } else { + propertyDescriptor->value_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'value';"; @@ -1250,10 +763,10 @@ std::unique_ptr PropertyDescriptor::Create(const PtJson &par ret = params.GetObject("get", &get); if (ret == Result::SUCCESS) { obj = RemoteObject::Create(*get); - if (obj != nullptr) { - propertyDescriptor->get_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'get' format error;"; + } else { + propertyDescriptor->get_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'get';"; @@ -1263,10 +776,10 @@ std::unique_ptr PropertyDescriptor::Create(const PtJson &par ret = params.GetObject("set", &set); if (ret == Result::SUCCESS) { obj = RemoteObject::Create(*set); - if (obj != nullptr) { - propertyDescriptor->set_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'set' format error;"; + } else { + propertyDescriptor->set_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'set';"; @@ -1308,10 +821,10 @@ std::unique_ptr PropertyDescriptor::Create(const PtJson &par ret = params.GetObject("symbol", &symbol); if (ret == Result::SUCCESS) { obj = RemoteObject::Create(*symbol); - if (obj != nullptr) { - propertyDescriptor->symbol_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'symbol' format error;"; + } else { + propertyDescriptor->symbol_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'symbol';"; @@ -1325,76 +838,24 @@ std::unique_ptr PropertyDescriptor::Create(const PtJson &par return propertyDescriptor; } -Local PropertyDescriptor::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "name")), - Local(StringRef::NewFromUtf8(ecmaVm, name_.c_str()))); - if (value_) { - ASSERT(value_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "value")), - Local(value_.value()->ToObject(ecmaVm))); - } - if (writable_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "writable")), - BooleanRef::New(ecmaVm, writable_.value())); - } - if (get_) { - ASSERT(get_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "get")), - Local(get_.value()->ToObject(ecmaVm))); - } - if (set_) { - ASSERT(set_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "set")), - Local(set_.value()->ToObject(ecmaVm))); - } - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "configurable")), - BooleanRef::New(ecmaVm, configurable_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "enumerable")), - BooleanRef::New(ecmaVm, enumerable_)); - if (wasThrown_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "wasThrown")), - BooleanRef::New(ecmaVm, wasThrown_.value())); - } - if (isOwn_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "isOwn")), - BooleanRef::New(ecmaVm, isOwn_.value())); - } - if (symbol_) { - ASSERT(symbol_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "symbol")), - Local(symbol_.value()->ToObject(ecmaVm))); - } - - return params; -} - std::unique_ptr PropertyDescriptor::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("name", name_.c_str()); - if (value_ && value_.value() != nullptr) { + if (value_) { + ASSERT(value_.value() != nullptr); result->Add("value", value_.value()->ToJson()); } if (writable_) { result->Add("writable", writable_.value()); } - if (get_ && get_.value() != nullptr) { + if (get_) { + ASSERT(get_.value() != nullptr); result->Add("get", get_.value()->ToJson()); } - if (set_ && set_.value() != nullptr) { + if (set_) { + ASSERT(set_.value() != nullptr); result->Add("set", set_.value()->ToJson()); } result->Add("configurable", configurable_); @@ -1405,7 +866,8 @@ std::unique_ptr PropertyDescriptor::ToJson() const if (isOwn_) { result->Add("isOwn", isOwn_.value()); } - if (symbol_ && symbol_.value() != nullptr) { + if (symbol_) { + ASSERT(symbol_.value() != nullptr); result->Add("symbol", symbol_.value()->ToJson()); } @@ -1455,52 +917,6 @@ std::unique_ptr CallArgument::ToJson() const return result; } -std::unique_ptr Location::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "Location::Create params is nullptr"; - return nullptr; - } - std::string error; - auto location = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - location->scriptId_ = DebuggerApi::StringToInt(result); - } else { - error += "'scriptId' should be a String;"; - } - } else { - error += "should contain 'scriptId';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - location->lineNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'lineNumber' should be a Number;"; - } - } else { - error += "should contain 'lineNumber';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - location->columnNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'columnNumber' should be a Number;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "Location::Create " << error; - return nullptr; - } - - return location; -} - std::unique_ptr Location::Create(const PtJson ¶ms) { auto location = std::make_unique(); @@ -1537,24 +953,6 @@ std::unique_ptr Location::Create(const PtJson ¶ms) return location; } -Local Location::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(scriptId_).c_str()))); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, lineNumber_)); - if (columnNumber_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, columnNumber_.value())); - } - - return params; -} - std::unique_ptr Location::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -1597,18 +995,6 @@ std::unique_ptr ScriptPosition::Create(const PtJson ¶ms) return scriptPosition; } -Local ScriptPosition::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, lineNumber_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, columnNumber_)); - - return params; -} - std::unique_ptr ScriptPosition::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -1619,46 +1005,6 @@ std::unique_ptr ScriptPosition::ToJson() const return result; } -std::unique_ptr SearchMatch::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "SearchMatch::Create params is nullptr"; - return nullptr; - } - std::string error; - auto locationSearch = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - locationSearch->lineNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'lineNumber' should be a Number;"; - } - } else { - error += "should contain 'lineNumber';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineContent"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - locationSearch->lineContent_ = DebuggerApi::ToStdString(result); - } else { - error += "'lineContent' should be a String;"; - } - } else { - error += "should contain 'lineContent';"; - } - - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "SearchMatch::Create " << error; - return nullptr; - } - - return locationSearch; -} - std::unique_ptr SearchMatch::Create(const PtJson ¶ms) { std::string error; @@ -1689,18 +1035,6 @@ std::unique_ptr SearchMatch::Create(const PtJson ¶ms) return locationSearch; } -Local SearchMatch::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, lineNumber_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "lineContent")), - Local(StringRef::NewFromUtf8(ecmaVm, lineContent_.c_str()))); - return params; -} - std::unique_ptr SearchMatch::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -1730,10 +1064,10 @@ std::unique_ptr LocationRange::Create(const PtJson ¶ms) ret = params.GetObject("start", &start); if (ret == Result::SUCCESS) { obj = ScriptPosition::Create(*start); - if (obj != nullptr) { - locationRange->start_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'start' format error;"; + } else { + locationRange->start_ = std::move(obj); } } else { error += "Unknown 'start';"; @@ -1743,10 +1077,10 @@ std::unique_ptr LocationRange::Create(const PtJson ¶ms) ret = params.GetObject("end", &end); if (ret == Result::SUCCESS) { obj = ScriptPosition::Create(*end); - if (obj != nullptr) { - locationRange->end_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'end' format error;"; + } else { + locationRange->end_ = std::move(obj); } } else { error += "Unknown 'end';"; @@ -1760,98 +1094,19 @@ std::unique_ptr LocationRange::Create(const PtJson ¶ms) return locationRange; } -Local LocationRange::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(scriptId_).c_str()))); - ASSERT(start_ != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "object")), - Local(start_->ToObject(ecmaVm))); - ASSERT(end_ != nullptr); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "object")), - Local(end_->ToObject(ecmaVm))); - - return params; -} - std::unique_ptr LocationRange::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("scriptId", std::to_string(scriptId_).c_str()); - if (start_ != nullptr) { - result->Add("start", start_->ToJson()); - } - if (end_ != nullptr) { - result->Add("end", end_->ToJson()); - } + ASSERT(start_ != nullptr); + result->Add("start", start_->ToJson()); + ASSERT(end_ != nullptr); + result->Add("end", end_->ToJson()); return result; } -std::unique_ptr BreakLocation::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "BreakLocation::Create params is nullptr"; - return nullptr; - } - std::string error; - auto breakLocation = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - breakLocation->scriptId_ = DebuggerApi::StringToInt(result); - } else { - error += "'scriptId' should be a String;"; - } - } else { - error += "should contain 'scriptId';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - breakLocation->lineNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'lineNumber' should be a Number;"; - } - } else { - error += "should contain 'lineNumber';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - breakLocation->columnNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'columnNumber' should be a Number;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "type"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - auto type = DebuggerApi::ToStdString(result); - if (BreakType::Valid(type)) { - breakLocation->type_ = type; - } else { - error += "'type' is invalid;"; - } - } else { - error += "'type' should be a String;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "Location::Create " << error; - return nullptr; - } - - return breakLocation; -} - std::unique_ptr BreakLocation::Create(const PtJson ¶ms) { std::string error; @@ -1902,29 +1157,6 @@ std::unique_ptr BreakLocation::Create(const PtJson ¶ms) return breakLocation; } -Local BreakLocation::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(scriptId_).c_str()))); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, lineNumber_)); - if (columnNumber_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, columnNumber_.value())); - } - if (type_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "type")), - Local(StringRef::NewFromUtf8(ecmaVm, type_->c_str()))); - } - - return params; -} - std::unique_ptr BreakLocation::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -1941,88 +1173,6 @@ std::unique_ptr BreakLocation::ToJson() const return result; } -std::unique_ptr Scope::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "Scope::Create params is nullptr"; - return nullptr; - } - std::string error; - auto scope = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "type"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - auto type = DebuggerApi::ToStdString(result); - if (Scope::Type::Valid(type)) { - scope->type_ = type; - } else { - error += "'type' is invalid;"; - } - } else { - error += "'type' should be a String;"; - } - } else { - error += "should contain 'type';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "object"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'object' format error;"; - } else { - scope->object_ = std::move(obj); - } - } else { - error += "'object' should be an Object;"; - } - } else { - error += "should contain 'object';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "name"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - scope->name_ = DebuggerApi::ToStdString(result); - } else { - error += "'name' should be a String;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "startLocation"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = Location::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'startLocation' format error;"; - } else { - scope->startLocation_ = std::move(obj); - } - } else { - error += "'startLocation' should be an Object;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "endLocation"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = Location::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'endLocation' format error;"; - } else { - scope->endLocation_ = std::move(obj); - } - } else { - error += "'endLocation' should be an Object;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "Location::Create " << error; - return nullptr; - } - - return scope; -} - std::unique_ptr Scope::Create(const PtJson ¶ms) { std::string error; @@ -2046,10 +1196,10 @@ std::unique_ptr Scope::Create(const PtJson ¶ms) ret = params.GetObject("object", &object); if (ret == Result::SUCCESS) { remoteObject = RemoteObject::Create(*object); - if (remoteObject != nullptr) { - scope->object_ = std::move(remoteObject); - } else { + if (remoteObject == nullptr) { error += "'object' format error;"; + } else { + scope->object_ = std::move(remoteObject); } } else { error += "Unknown 'object';"; @@ -2068,10 +1218,10 @@ std::unique_ptr Scope::Create(const PtJson ¶ms) ret = params.GetObject("startLocation", &startLocation); if (ret == Result::SUCCESS) { obj = Location::Create(*startLocation); - if (obj != nullptr) { - scope->startLocation_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'startLocation' format error;"; + } else { + scope->startLocation_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'startLocation';"; @@ -2081,10 +1231,10 @@ std::unique_ptr Scope::Create(const PtJson ¶ms) ret = params.GetObject("endLocation", &endLocation); if (ret == Result::SUCCESS) { obj = Location::Create(*endLocation); - if (obj != nullptr) { - scope->endLocation_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'endLocation' format error;"; + } else { + scope->endLocation_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'endLocation';"; @@ -2098,185 +1248,28 @@ std::unique_ptr Scope::Create(const PtJson ¶ms) return scope; } -Local Scope::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "type")), - Local(StringRef::NewFromUtf8(ecmaVm, type_.c_str()))); - ASSERT(object_ != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "object")), - Local(object_->ToObject(ecmaVm))); - if (name_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "name")), - Local(StringRef::NewFromUtf8(ecmaVm, name_->c_str()))); - } - if (startLocation_) { - ASSERT(startLocation_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "startLocation")), - Local(startLocation_.value()->ToObject(ecmaVm))); - } - if (endLocation_) { - ASSERT(endLocation_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "endLocation")), - Local(endLocation_.value()->ToObject(ecmaVm))); - } - - return params; -} - std::unique_ptr Scope::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("type", type_.c_str()); - if (object_ != nullptr) { - result->Add("object", object_->ToJson()); - } + ASSERT(object_ != nullptr); + result->Add("object", object_->ToJson()); if (name_) { result->Add("name", name_->c_str()); } - if (startLocation_ && startLocation_.value() != nullptr) { + if (startLocation_) { + ASSERT(startLocation_.value() != nullptr); result->Add("startLocation", startLocation_.value()->ToJson()); } - if (endLocation_ && endLocation_.value() != nullptr) { + if (endLocation_) { + ASSERT(endLocation_.value() != nullptr); result->Add("endLocation", endLocation_.value()->ToJson()); } return result; } -std::unique_ptr CallFrame::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "CallFrame::Create params is nullptr"; - return nullptr; - } - std::string error; - auto callFrame = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "callFrameId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - callFrame->callFrameId_ = DebuggerApi::StringToInt(result); - } else { - error += "'callFrameId' should be a String;"; - } - } else { - error += "should contain 'callFrameId';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "functionName"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - callFrame->functionName_ = DebuggerApi::ToStdString(result); - } else { - error += "'functionName' should be a String;"; - } - } else { - error += "should contain 'functionName';"; - } - result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "functionLocation"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = Location::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'functionLocation' format error;"; - } else { - callFrame->functionLocation_ = std::move(obj); - } - } else { - error += "'functionLocation' should be an Object;"; - } - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "location"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = Location::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'location' format error;"; - } else { - callFrame->location_ = std::move(obj); - } - } else { - error += "'location' should be an Object;"; - } - } else { - error += "should contain 'location';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "url"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - callFrame->url_ = DebuggerApi::ToStdString(result); - } else { - error += "'url' should be a String;"; - } - } else { - error += "should contain 'url';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scopeChain"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t len = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < len; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr scope = Scope::Create(ecmaVm, resultValue); - if (resultValue.IsEmpty() || scope == nullptr) { - error += "'scopeChain' format invalid;"; - } - callFrame->scopeChain_.emplace_back(std::move(scope)); - } - } else { - error += "'scopeChain' should be an Array;"; - } - } else { - error += "should contain 'scopeChain';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "this"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'this' format error;"; - } else { - callFrame->this_ = std::move(obj); - } - } else { - error += "'this' should be an Object;"; - } - } else { - error += "should contain 'this';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "returnValue"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RemoteObject::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'returnValue' format error;"; - } else { - callFrame->returnValue_ = std::move(obj); - } - } else { - error += "'returnValue' should be an Object;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "CallFrame::Create " << error; - return nullptr; - } - - return callFrame; -} - std::unique_ptr CallFrame::Create(const PtJson ¶ms) { std::string error; @@ -2304,10 +1297,10 @@ std::unique_ptr CallFrame::Create(const PtJson ¶ms) ret = params.GetObject("functionLocation", &functionLocation); if (ret == Result::SUCCESS) { obj = Location::Create(*functionLocation); - if (obj != nullptr) { - callFrame->functionLocation_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'functionLocation' format error;"; + } else { + callFrame->functionLocation_ = std::move(obj); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'functionLocation';"; @@ -2317,10 +1310,10 @@ std::unique_ptr CallFrame::Create(const PtJson ¶ms) ret = params.GetObject("location", &location); if (ret == Result::SUCCESS) { obj = Location::Create(*location); - if (obj != nullptr) { - callFrame->location_ = std::move(obj); - } else { + if (obj == nullptr) { error += "'location' format error;"; + } else { + callFrame->location_ = std::move(obj); } } else { error += "Unknown 'location';"; @@ -2340,15 +1333,12 @@ std::unique_ptr CallFrame::Create(const PtJson ¶ms) int32_t len = scopeChain->GetSize(); for (int32_t i = 0; i < len; ++i) { std::unique_ptr arrayEle = scopeChain->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr scope = Scope::Create(*arrayEle); - if (scope != nullptr) { - callFrame->scopeChain_.emplace_back(std::move(scope)); - } else { - error += "'scopeChain' format error;"; - } + ASSERT(arrayEle != nullptr); + std::unique_ptr scope = Scope::Create(*arrayEle); + if (scope == nullptr) { + error += "'scopeChain' format error;"; } else { - error += "Unknown 'scopeChain';"; + callFrame->scopeChain_.emplace_back(std::move(scope)); } } } else { @@ -2360,10 +1350,10 @@ std::unique_ptr CallFrame::Create(const PtJson ¶ms) ret = params.GetObject("this", &thisObj); if (ret == Result::SUCCESS) { remoteObject = RemoteObject::Create(*thisObj); - if (remoteObject != nullptr) { - callFrame->this_ = std::move(remoteObject); - } else { + if (remoteObject == nullptr) { error += "'this' format error;"; + } else { + callFrame->this_ = std::move(remoteObject); } } else { error += "Unknown 'this';"; @@ -2373,10 +1363,10 @@ std::unique_ptr CallFrame::Create(const PtJson ¶ms) ret = params.GetObject("returnValue", &returnValue); if (ret == Result::SUCCESS) { remoteObject = RemoteObject::Create(*returnValue); - if (remoteObject != nullptr) { - callFrame->returnValue_ = std::move(remoteObject); - } else { + if (remoteObject == nullptr) { error += "'returnValue' format error;"; + } else { + callFrame->returnValue_ = std::move(remoteObject); } } else if (ret == Result::TYPE_ERROR) { error += "Unknown 'returnValue';"; @@ -2390,49 +1380,6 @@ std::unique_ptr CallFrame::Create(const PtJson ¶ms) return callFrame; } -Local CallFrame::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "callFrameId")), - Local(StringRef::NewFromUtf8(ecmaVm, std::to_string(callFrameId_).c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "functionName")), - Local(StringRef::NewFromUtf8(ecmaVm, functionName_.c_str()))); - if (functionLocation_) { - ASSERT(functionLocation_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "functionLocation")), - Local(functionLocation_.value()->ToObject(ecmaVm))); - } - ASSERT(location_ != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "location")), - Local(location_->ToObject(ecmaVm))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "url")), - Local(StringRef::NewFromUtf8(ecmaVm, url_.c_str()))); - size_t len = scopeChain_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - Local scope = scopeChain_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, scope); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scopeChain")), values); - ASSERT(this_ != nullptr); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "this")), - Local(this_->ToObject(ecmaVm))); - if (returnValue_) { - ASSERT(returnValue_.value() != nullptr); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "returnValue")), - Local(returnValue_.value()->ToObject(ecmaVm))); - } - - return params; -} - std::unique_ptr CallFrame::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -2440,12 +1387,12 @@ std::unique_ptr CallFrame::ToJson() const result->Add("callFrameId", std::to_string(callFrameId_).c_str()); result->Add("functionName", functionName_.c_str()); - if (functionLocation_ && functionLocation_.value() != nullptr) { + if (functionLocation_) { + ASSERT(functionLocation_.value() != nullptr); result->Add("functionLocation", functionLocation_.value()->ToJson()); } - if (location_ != nullptr) { - result->Add("location", location_->ToJson()); - } + ASSERT(location_ != nullptr); + result->Add("location", location_->ToJson()); result->Add("url", url_.c_str()); size_t len = scopeChain_.size(); @@ -2456,68 +1403,16 @@ std::unique_ptr CallFrame::ToJson() const } result->Add("scopeChain", values); - if (this_ != nullptr) { - result->Add("this", this_->ToJson()); - } - if (returnValue_ && returnValue_.value() != nullptr) { + ASSERT(this_ != nullptr); + result->Add("this", this_->ToJson()); + if (returnValue_) { + ASSERT(returnValue_.value() != nullptr); result->Add("returnValue", returnValue_.value()->ToJson()); } return result; } -std::unique_ptr SamplingHeapProfileSample::Create(const EcmaVM *ecmaVm, - const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "SamplingHeapProfileSample::Create params is nullptr"; - return nullptr; - } - std::string error; - auto samplingHeapProfileSample = std::make_unique(); - - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "size"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - samplingHeapProfileSample->size_ = static_cast(Local(result)->Value()); - } else { - error += "'size' should be a Number;"; - } - } else { - error += "should contain 'size';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "ordinal"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - samplingHeapProfileSample->ordinal_ = static_cast(Local(result)->Value()); - } else { - error += "'ordinal' should be a Number;"; - } - } else { - error += "should contain 'ordinal';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "nodeId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - samplingHeapProfileSample->nodeId_ = static_cast(Local(result)->Value()); - } else { - error += "'nodeId' should be a Number;"; - } - } else { - error += "should contain 'nodeId';"; - } - - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "SamplingHeapProfileSample::Create " << error; - return nullptr; - } - - return samplingHeapProfileSample; -} - std::unique_ptr SamplingHeapProfileSample::Create(const PtJson ¶ms) { std::string error; @@ -2553,104 +1448,17 @@ std::unique_ptr SamplingHeapProfileSample::Create(con return samplingHeapProfileSample; } -Local SamplingHeapProfileSample::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "size")), - IntegerRef::New(ecmaVm, size_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "ordinal")), - IntegerRef::New(ecmaVm, ordinal_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "nodeId")), - IntegerRef::New(ecmaVm, nodeId_)); - - return params; -} - std::unique_ptr SamplingHeapProfileSample::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - result->Add("size", static_cast(size_)); + result->Add("size", size_); result->Add("nodeId", nodeId_); - result->Add("ordinal", static_cast(ordinal_)); + result->Add("ordinal", ordinal_); return result; } -std::unique_ptr RuntimeCallFrame::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "RuntimeCallFrame::Create params is nullptr"; - return nullptr; - } - std::string error; - auto runtimeCallFrame = std::make_unique(); - - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "functionName"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - runtimeCallFrame->functionName_ = DebuggerApi::ToStdString(result); - } else { - error += "'functionName' should be a String;"; - } - } else { - error += "should contain 'functionName';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - runtimeCallFrame->scriptId_ = DebuggerApi::ToStdString(result); - } else { - error += "'scriptId' should be a String;"; - } - } else { - error += "should contain 'scriptId';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "url"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - runtimeCallFrame->url_ = DebuggerApi::ToStdString(result); - } else { - error += "'url' should be a String;"; - } - } else { - error += "should contain 'url';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - runtimeCallFrame->lineNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'lineNumber' should be a Number;"; - } - } else { - error += "should contain 'lineNumber';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - runtimeCallFrame->columnNumber_ = static_cast(Local(result)->Value()); - } else { - error += "'columnNumber' should be a Number;"; - } - } else { - error += "should contain 'columnNumber';"; - } - - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "RuntimeCallFrame::Create " << error; - return nullptr; - } - - return runtimeCallFrame; -} - std::unique_ptr RuntimeCallFrame::Create(const PtJson ¶ms) { std::string error; @@ -2715,28 +1523,6 @@ std::unique_ptr RuntimeCallFrame::FromFrameInfo(const FrameInf return runtimeCallFrame; } -Local RuntimeCallFrame::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "functionName")), - Local(StringRef::NewFromUtf8(ecmaVm, functionName_.c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, scriptId_.c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "url")), - Local(StringRef::NewFromUtf8(ecmaVm, url_.c_str()))); - - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "lineNumber")), - IntegerRef::New(ecmaVm, lineNumber_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "columnNumber")), - IntegerRef::New(ecmaVm, columnNumber_)); - - return params; -} - std::unique_ptr RuntimeCallFrame::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -2750,86 +1536,6 @@ std::unique_ptr RuntimeCallFrame::ToJson() const return result; } -std::unique_ptr SamplingHeapProfileNode::Create(const EcmaVM *ecmaVm, - const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "SamplingHeapProfileNode::Create params is nullptr"; - return nullptr; - } - - std::string error; - auto samplingHeapProfileNode = std::make_unique(); - - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "callFrame"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RuntimeCallFrame::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'callFrame' format error;"; - } else { - samplingHeapProfileNode->callFrame_ = std::move(obj); - } - } else { - error += "'callFrame' should be an Object;"; - } - } else { - error += "should contain 'callFrame';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "selfSize"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - samplingHeapProfileNode->selfSize_ = static_cast(Local(result)->Value()); - } else { - error += "'selfSize' should be a Number;"; - } - } else { - error += "should contain 'selfSize';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "id"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - samplingHeapProfileNode->id_ = static_cast(Local(result)->Value()); - } else { - error += "'id' should be a Number;"; - } - } else { - error += "should contain 'id';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "children"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t len = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < len; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr node = SamplingHeapProfileNode::Create(ecmaVm, resultValue); - if (resultValue.IsEmpty() || node == nullptr) { - error += "'children' format invalid;"; - } - samplingHeapProfileNode->children_.emplace_back(std::move(node)); - } - } else { - error += "'children' should be an Array;"; - } - } else { - error += "should contain 'children';"; - } - - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "SamplingHeapProfileNode::Create " << error; - return nullptr; - } - - return samplingHeapProfileNode; -} - std::unique_ptr SamplingHeapProfileNode::Create(const PtJson ¶ms) { std::string error; @@ -2852,7 +1558,7 @@ std::unique_ptr SamplingHeapProfileNode::Create(const P int32_t selfSize; ret = params.GetInt("selfSize", &selfSize); if (ret == Result::SUCCESS) { - samplingHeapProfileNode->selfSize_ = static_cast(selfSize); + samplingHeapProfileNode->selfSize_ = selfSize; } else { error += "Unknown 'selfSize';"; } @@ -2871,15 +1577,12 @@ std::unique_ptr SamplingHeapProfileNode::Create(const P int32_t len = children->GetSize(); for (int32_t i = 0; i < len; ++i) { std::unique_ptr arrayEle = children->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr node = SamplingHeapProfileNode::Create(*arrayEle); - if (node == nullptr) { - error += "'children' format invalid;"; - } else { - samplingHeapProfileNode->children_.emplace_back(std::move(node)); - } + ASSERT(arrayEle != nullptr); + std::unique_ptr node = SamplingHeapProfileNode::Create(*arrayEle); + if (node == nullptr) { + error += "'children' format invalid;"; } else { - error += "Unknown 'children';"; + samplingHeapProfileNode->children_.emplace_back(std::move(node)); } } } else { @@ -2894,108 +1597,22 @@ std::unique_ptr SamplingHeapProfileNode::Create(const P return samplingHeapProfileNode; } -Local SamplingHeapProfileNode::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - if (callFrame_ != nullptr) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "callFrame")), - Local(callFrame_->ToObject(ecmaVm))); - } - - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "selfSize")), - IntegerRef::New(ecmaVm, selfSize_)); - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "id")), - IntegerRef::New(ecmaVm, id_)); - - size_t len = children_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - if (children_[i] != nullptr) { - Local node = children_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, node); - } - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "children")), values); - - return params; -} - std::unique_ptr SamplingHeapProfileNode::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - if (callFrame_ != nullptr) { - result->Add("callFrame", callFrame_->ToJson()); - } - - result->Add("selfSize", static_cast(selfSize_)); + ASSERT(callFrame_ != nullptr); + result->Add("callFrame", callFrame_->ToJson()); + result->Add("selfSize", selfSize_); result->Add("id", id_); - + std::unique_ptr childrens = PtJson::CreateArray(); size_t len = children_.size(); for (size_t i = 0; i < len; i++) { childrens->Push(children_[i]->ToJson()); } result->Add("children", childrens); - return result; -} - -std::unique_ptr SamplingHeapProfile::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "SamplingHeapProfile::Create params is nullptr"; - return nullptr; - } - std::string error; - auto samplingHeapProfile = std::make_unique(); - Local result = Local(params)->Get(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "head"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = SamplingHeapProfileNode::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'head' format error;"; - } else { - samplingHeapProfile->head_ = std::move(obj); - } - } else { - error += "'head' should be an Object;"; - } - } else { - error += "should contain 'head';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "samples"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t len = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < len; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr node = SamplingHeapProfileSample::Create(ecmaVm, - resultValue); - if (resultValue.IsEmpty() || node == nullptr) { - error += "'samples' format invalid;"; - } - samplingHeapProfile->samples_.emplace_back(std::move(node)); - } - } else { - error += "'samples' should be an Array;"; - } - } else { - error += "should contain 'samples';"; - } - - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "SamplingHeapProfile::Create " << error; - return nullptr; - } - - return samplingHeapProfile; + return result; } std::unique_ptr SamplingHeapProfile::Create(const PtJson ¶ms) @@ -3023,15 +1640,12 @@ std::unique_ptr SamplingHeapProfile::Create(const PtJson &p int32_t len = samples->GetSize(); for (int32_t i = 0; i < len; ++i) { std::unique_ptr arrayEle = samples->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr pSample = SamplingHeapProfileSample::Create(*arrayEle); - if (pSample == nullptr) { - error += "'sample' format invalid;"; - } else { - samplingHeapProfile->samples_.emplace_back(std::move(pSample)); - } + ASSERT(arrayEle != nullptr); + std::unique_ptr pSample = SamplingHeapProfileSample::Create(*arrayEle); + if (pSample == nullptr) { + error += "'sample' format invalid;"; } else { - error += "Unknown 'samples';"; + samplingHeapProfile->samples_.emplace_back(std::move(pSample)); } } } else { @@ -3046,233 +1660,61 @@ std::unique_ptr SamplingHeapProfile::Create(const PtJson &p return samplingHeapProfile; } -Local SamplingHeapProfile::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - - if (head_ != nullptr) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "head")), - Local(head_->ToObject(ecmaVm))); - } - - size_t len = samples_.size(); - Local values = ArrayRef::New(ecmaVm, len); - for (size_t i = 0; i < len; i++) { - if (samples_[i] != nullptr) { - Local node = samples_[i]->ToObject(ecmaVm); - values->Set(ecmaVm, i, node); - } - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "samples")), values); - - return params; -} - std::unique_ptr SamplingHeapProfile::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); + ASSERT(head_ != nullptr); result->Add("head", head_->ToJson()); std::unique_ptr samples = PtJson::CreateArray(); size_t len = samples_.size(); for (size_t i = 0; i < len; i++) { - if (samples_[i] != nullptr) { - samples->Push(samples_[i]->ToJson()); - } + ASSERT(samples_[i] != nullptr); + samples->Push(samples_[i]->ToJson()); } result->Add("samples", samples); return result; } -std::unique_ptr PositionTickInfo::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "PositionTickInfo::Create params is nullptr"; - return nullptr; - } - std::string error; - auto positionTicks = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "line"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - positionTicks->line_ = static_cast(Local(result)->Value()); - } else { - error += "'line' should be a Number;"; - } - } else { - error += "should contain 'line';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "ticks"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - positionTicks->ticks_ = static_cast(Local(result)->Value()); - } else { - error += "'ticks' should be a Number;"; - } - } else { - error += "should contain 'ticks';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "PositionTickInfo::Create " << error; - return nullptr; - } - return positionTicks; -} - std::unique_ptr PositionTickInfo::Create(const PtJson ¶ms) { - std::string error; - auto positionTickInfo = std::make_unique(); - Result ret; - - int32_t line; - ret = params.GetInt("line", &line); - if (ret == Result::SUCCESS) { - positionTickInfo->line_ = line; - } else { - error += "Unknown 'line';"; - } - - int32_t ticks; - ret = params.GetInt("ticks", &ticks); - if (ret == Result::SUCCESS) { - positionTickInfo->ticks_ = ticks; - } else { - error += "Unknown 'ticks';"; - } - - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "PositionTickInfo::Create " << error; - return nullptr; - } - - return positionTickInfo; -} - -Local PositionTickInfo::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "line")), - IntegerRef::New(ecmaVm, line_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "ticks")), - IntegerRef::New(ecmaVm, ticks_)); - - return params; -} - -std::unique_ptr PositionTickInfo::ToJson() const -{ - std::unique_ptr result = PtJson::CreateObject(); - - result->Add("line", static_cast(line_)); - result->Add("ticks", static_cast(ticks_)); - - return result; -} - -std::unique_ptr ProfileNode::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "ProfileNode::Create params is nullptr"; - return nullptr; - } - std::string error; - auto profileNode = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "id"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - profileNode->id_ = static_cast(Local(result)->Value()); - } else { - error += "'id' should be a Number;"; - } - } else { - error += "should contain 'id';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "callFrame"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsObject()) { - std::unique_ptr obj = RuntimeCallFrame::Create(ecmaVm, result); - if (obj == nullptr) { - error += "'callFrame' format error;"; - } else { - profileNode->callFrame_ = std::move(obj); - } - } else { - error += "'callFrame' should be an Object;"; - } - } else { - error += "should contain 'callFrame';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "hitCount"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - profileNode->hitCount_ = static_cast(Local(result)->Value()); - } else { - error += "'hitCount' should be a Number;"; - } - } else { - error += "should contain 'hitCount';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "children"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t childrenLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < childrenLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - int32_t pChildren; - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - pChildren = resultValue->Int32Value(ecmaVm); - profileNode->children_.value()[i] = pChildren; - } - } else { - error += "'children' should be an Array;"; - } - } else { - error += "should contain 'children';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "positionTicks"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t positionTickLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < positionTickLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr positionTick = PositionTickInfo::Create(ecmaVm, resultValue); - profileNode->positionTicks_->emplace_back(std::move(positionTick)); - } - } else { - error += "'positionTicks' should be an Array;"; - } + std::string error; + auto positionTickInfo = std::make_unique(); + Result ret; + + int32_t line; + ret = params.GetInt("line", &line); + if (ret == Result::SUCCESS) { + positionTickInfo->line_ = line; } else { - error += "should contain 'positionTicks';"; + error += "Unknown 'line';"; } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "deoptReason"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - profileNode->deoptReason_ = DebuggerApi::ToStdString(result); - } else { - error += "'deoptReason' should be a String;"; - } + + int32_t ticks; + ret = params.GetInt("ticks", &ticks); + if (ret == Result::SUCCESS) { + positionTickInfo->ticks_ = ticks; } else { - error += "should contain 'deoptReason_';"; + error += "Unknown 'ticks';"; } + if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "ProfileNode::Create " << error; + LOG(ERROR, DEBUGGER) << "PositionTickInfo::Create " << error; return nullptr; } - return profileNode; + + return positionTickInfo; +} + +std::unique_ptr PositionTickInfo::ToJson() const +{ + std::unique_ptr result = PtJson::CreateObject(); + + result->Add("line", line_); + result->Add("ticks", ticks_); + + return result; } std::unique_ptr ProfileNode::Create(const PtJson ¶ms) @@ -3328,15 +1770,12 @@ std::unique_ptr ProfileNode::Create(const PtJson ¶ms) int32_t positionTicksLen = positionTicks->GetSize(); for (int32_t i = 0; i < positionTicksLen; ++i) { std::unique_ptr arrayEle = positionTicks->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr tmpPositionTicks = PositionTickInfo::Create(*arrayEle); - if (tmpPositionTicks == nullptr) { - error += "'positionTicks' format invalid;"; - } else { - profileNode->positionTicks_.value().emplace_back(std::move(tmpPositionTicks)); - } + ASSERT(arrayEle != nullptr); + std::unique_ptr tmpPositionTicks = PositionTickInfo::Create(*arrayEle); + if (tmpPositionTicks == nullptr) { + error += "'positionTicks' format invalid;"; } else { - error += "Unknown 'positionTicks';"; + profileNode->positionTicks_.value().emplace_back(std::move(tmpPositionTicks)); } } } else if (ret == Result::TYPE_ERROR) { @@ -3368,7 +1807,7 @@ std::unique_ptr ProfileNode::FromCpuProfileNode(const CpuProfileNod size_t childrenLen = cpuProfileNode.children.size(); std::vector tmpChildren; tmpChildren.reserve(childrenLen); - for (uint32_t i = 0; i < childrenLen; ++i) { + for (size_t i = 0; i < childrenLen; ++i) { tmpChildren.push_back(cpuProfileNode.children[i]); } profileNode->SetChildren(tmpChildren); @@ -3376,56 +1815,12 @@ std::unique_ptr ProfileNode::FromCpuProfileNode(const CpuProfileNod return profileNode; } -Local ProfileNode::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "id")), - IntegerRef::New(ecmaVm, id_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "callFrame")), - Local(callFrame_->ToObject(ecmaVm))); - - if (hitCount_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "hitCount")), - IntegerRef::New(ecmaVm, hitCount_.value())); - } - - if (children_) { - size_t childrenLen = children_->size(); - Local childrenValues = ArrayRef::New(ecmaVm, childrenLen); - for (size_t i = 0; i < childrenLen; i++) { - Local elem = IntegerRef::New(ecmaVm, children_.value()[i]); - childrenValues->Set(ecmaVm, i, elem); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "children")), childrenValues); - } - - if (positionTicks_) { - size_t positionTickLen = positionTicks_->size(); - Local positionValues = ArrayRef::New(ecmaVm, positionTickLen); - for (size_t i = 0; i < positionTickLen; i++) { - Local positionTick = positionTicks_.value()[i]->ToObject(ecmaVm); - positionValues->Set(ecmaVm, i, positionTick); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "positionTicks")), positionValues); - } - - if (deoptReason_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "deoptReason")), - Local(StringRef::NewFromUtf8(ecmaVm, deoptReason_->c_str()))); - } - - return params; -} - std::unique_ptr ProfileNode::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); result->Add("id", id_); + ASSERT(callFrame_ != nullptr); result->Add("callFrame", callFrame_->ToJson()); if (hitCount_) { result->Add("hitCount", hitCount_.value()); @@ -3442,9 +1837,8 @@ std::unique_ptr ProfileNode::ToJson() const std::unique_ptr positionTicks = PtJson::CreateArray(); size_t len = positionTicks_->size(); for (size_t i = 0; i < len; i++) { - if (positionTicks_.value()[i] != nullptr) { - positionTicks->Push(positionTicks_.value()[i]->ToJson()); - } + ASSERT(positionTicks_.value()[i] != nullptr); + positionTicks->Push(positionTicks_.value()[i]->ToJson()); } result->Add("positionTicks", positionTicks); } @@ -3456,99 +1850,6 @@ std::unique_ptr ProfileNode::ToJson() const return result; } -std::unique_ptr Profile::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "Profile::Create params is nullptr"; - return nullptr; - } - std::string error; - auto profile = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "nodes"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t nodesLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < nodesLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr node = ProfileNode::Create(ecmaVm, resultValue); - profile->nodes_.emplace_back(std::move(node)); - } - } else { - error += "'nodes' should be an Array;"; - } - } else { - error += "should contain 'nodes';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "startTime"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - profile->startTime_ = static_cast(Local(result)->Value()); - } else { - error += "'startTime' should be a Number;"; - } - } else { - error += "should contain 'startTime';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "endTime"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - profile->endTime_ = static_cast(Local(result)->Value()); - } else { - error += "'endTime' should be a Number;"; - } - } else { - error += "should contain 'endTime';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "samples"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t samplesLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < samplesLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - int32_t pSamples; - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - pSamples = resultValue->Int32Value(ecmaVm); - profile->samples_.value()[i] = pSamples; - } - } else { - error += "'samples' should be an Array;"; - } - } else { - error += "should contain 'samples';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "timeDeltas"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t timeDeltasLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < timeDeltasLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - int32_t pTime; - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - pTime = resultValue->Int32Value(ecmaVm); - profile->timeDeltas_.value()[i] = pTime; - } - } else { - error += "'timeDeltas' should be an Array;"; - } - } else { - error += "should contain 'timeDeltas';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "Profile::Create " << error; - return nullptr; - } - return profile; -} - std::unique_ptr Profile::Create(const PtJson ¶ms) { std::string error; @@ -3561,15 +1862,12 @@ std::unique_ptr Profile::Create(const PtJson ¶ms) int32_t nodesLen = nodes->GetSize(); for (int32_t i = 0; i < nodesLen; ++i) { std::unique_ptr arrayEle = nodes->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr profileNode = ProfileNode::Create(*arrayEle); - if (profileNode == nullptr) { - error += "'nodes' format invalid;"; - } else { - profile->nodes_.emplace_back(std::move(profileNode)); - } + ASSERT(arrayEle != nullptr); + std::unique_ptr profileNode = ProfileNode::Create(*arrayEle); + if (profileNode == nullptr) { + error += "'nodes' format invalid;"; } else { - error += "Unknown 'nodes';"; + profile->nodes_.emplace_back(std::move(profileNode)); } } } else { @@ -3632,7 +1930,7 @@ std::unique_ptr Profile::FromProfileInfo(const ProfileInfo &profileInfo size_t samplesLen = profileInfo.samples.size(); std::vector tmpSamples; tmpSamples.reserve(samplesLen); - for (uint32_t i = 0; i < samplesLen; ++i) { + for (size_t i = 0; i < samplesLen; ++i) { tmpSamples.push_back(profileInfo.samples[i]); } profile->SetSamples(tmpSamples); @@ -3640,14 +1938,14 @@ std::unique_ptr Profile::FromProfileInfo(const ProfileInfo &profileInfo size_t timeDeltasLen = profileInfo.timeDeltas.size(); std::vector tmpTimeDeltas; tmpTimeDeltas.reserve(timeDeltasLen); - for (uint32_t i = 0; i < timeDeltasLen; ++i) { + for (size_t i = 0; i < timeDeltasLen; ++i) { tmpTimeDeltas.push_back(profileInfo.timeDeltas[i]); } profile->SetTimeDeltas(tmpTimeDeltas); std::vector> profileNode; size_t nodesLen = profileInfo.nodes.size(); - for (uint32_t i = 0; i < nodesLen; ++i) { + for (size_t i = 0; i < nodesLen; ++i) { const auto &cpuProfileNode = profileInfo.nodes[i]; profileNode.push_back(ProfileNode::FromCpuProfileNode(cpuProfileNode)); } @@ -3655,46 +1953,6 @@ std::unique_ptr Profile::FromProfileInfo(const ProfileInfo &profileInfo return profile; } -Local Profile::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - size_t nodeLen = nodes_.size(); - Local nodeValues = ArrayRef::New(ecmaVm, nodeLen); - for (size_t i = 0; i < nodeLen; i++) { - Local profileNode = nodes_[i]->ToObject(ecmaVm); - nodeValues->Set(ecmaVm, i, profileNode); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "nodes")), nodeValues); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "startTime")), - NumberRef::New(ecmaVm, startTime_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "endTime")), - NumberRef::New(ecmaVm, endTime_)); - - if (samples_) { - size_t samplesLen = samples_->size(); - Local sampleValues = ArrayRef::New(ecmaVm, samplesLen); - for (size_t i = 0; i < samplesLen; i++) { - Local elem = IntegerRef::New(ecmaVm, samples_.value()[i]); - sampleValues->Set(ecmaVm, i, elem); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "samples")), sampleValues); - } - - if (timeDeltas_) { - size_t tdLen = timeDeltas_->size(); - Local timeValues = ArrayRef::New(ecmaVm, tdLen); - for (size_t i = 0; i < tdLen; i++) { - Local elem = IntegerRef::New(ecmaVm, timeDeltas_.value()[i]); - timeValues->Set(ecmaVm, i, elem); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "timeDeltas")), timeValues); - } - - return params; -} - std::unique_ptr Profile::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -3705,9 +1963,8 @@ std::unique_ptr Profile::ToJson() const std::unique_ptr nodes = PtJson::CreateArray(); size_t nodesLen = nodes_.size(); for (size_t i = 0; i < nodesLen; i++) { - if (nodes_[i] != nullptr) { - nodes->Push(nodes_[i]->ToJson()); - } + ASSERT(nodes_[i] != nullptr); + nodes->Push(nodes_[i]->ToJson()); } result->Add("nodes", nodes); @@ -3732,53 +1989,6 @@ std::unique_ptr Profile::ToJson() const return result; } -std::unique_ptr Coverage::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "Coverage::Create params is nullptr"; - return nullptr; - } - std::string error; - auto coverage = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "startOffset"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - coverage->startOffset_ = static_cast(Local(result)->Value()); - } else { - error += "'startOffset' should be a Number;"; - } - } else { - error += "should contain 'startOffset';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "endOffset"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - coverage->endOffset_ = static_cast(Local(result)->Value()); - } else { - error += "'endOffset' should be a Number;"; - } - } else { - error += "should contain 'endOffset';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "count"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - coverage->count_ = static_cast(Local(result)->Value()); - } else { - error += "'count' should be a Number;"; - } - } else { - error += "should contain 'count';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "Coverage::Create " << error; - return nullptr; - } - return coverage; -} - std::unique_ptr Coverage::Create(const PtJson ¶ms) { std::string error; @@ -3817,18 +2027,6 @@ std::unique_ptr Coverage::Create(const PtJson ¶ms) return coverage; } -Local Coverage::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "startOffset")), IntegerRef::New(ecmaVm, startOffset_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "endOffset")), IntegerRef::New(ecmaVm, endOffset_)); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "count")), IntegerRef::New(ecmaVm, count_)); - return params; -} - std::unique_ptr Coverage::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -3840,62 +2038,6 @@ std::unique_ptr Coverage::ToJson() const return result; } -std::unique_ptr FunctionCoverage::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "FunctionCoverage::Create params is nullptr"; - return nullptr; - } - std::string error; - auto functionCoverage = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "functionName"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - functionCoverage->functionName_ = DebuggerApi::ToStdString(result); - } else { - error += "'functionName' should be a String;"; - } - } else { - error += "should contain 'functionName';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "ranges"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t rangesLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < rangesLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr range = Coverage::Create(ecmaVm, resultValue); - functionCoverage->ranges_.emplace_back(std::move(range)); - } - } else { - error += "'ranges' should be an Array;"; - } - } else { - error += "should contain 'ranges';"; - } - - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, - "isBlockCoverage"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsBoolean()) { - functionCoverage->isBlockCoverage_ = result->IsTrue(); - } else { - error += "'isBlockCoverage' should be a Boolean;"; - } - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "FunctionCoverage::Create " << error; - return nullptr; - } - return functionCoverage; -} - std::unique_ptr FunctionCoverage::Create(const PtJson ¶ms) { std::string error; @@ -3916,15 +2058,12 @@ std::unique_ptr FunctionCoverage::Create(const PtJson ¶ms) int32_t len = ranges->GetSize(); for (int32_t i = 0; i < len; ++i) { std::unique_ptr arrayEle = ranges->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr pRanges = Coverage::Create(*arrayEle); - if (pRanges == nullptr) { - error += "'ranges' format invalid;"; - } else { - functionCoverage->ranges_.emplace_back(std::move(pRanges)); - } + ASSERT(arrayEle != nullptr); + std::unique_ptr pRanges = Coverage::Create(*arrayEle); + if (pRanges == nullptr) { + error += "'ranges' format invalid;"; } else { - error += "Unknown 'ranges';"; + functionCoverage->ranges_.emplace_back(std::move(pRanges)); } } } else { @@ -3947,28 +2086,6 @@ std::unique_ptr FunctionCoverage::Create(const PtJson ¶ms) return functionCoverage; } -Local FunctionCoverage::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "functionName")), - Local(StringRef::NewFromUtf8(ecmaVm, functionName_.c_str()))); - - size_t rangesLen = ranges_.size(); - Local rangesValues = ArrayRef::New(ecmaVm, rangesLen); - for (size_t i = 0; i < rangesLen; i++) { - Local coverage = ranges_[i]->ToObject(ecmaVm); - rangesValues->Set(ecmaVm, i, coverage); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "ranges")), rangesValues); - if (isBlockCoverage_) { - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "isBlockCoverage")), - BooleanRef::New(ecmaVm, isBlockCoverage_)); - } - return params; -} - std::unique_ptr FunctionCoverage::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -3978,9 +2095,8 @@ std::unique_ptr FunctionCoverage::ToJson() const std::unique_ptr ranges = PtJson::CreateArray(); size_t len = ranges_.size(); for (size_t i = 0; i < len; i++) { - if (ranges_[i] != nullptr) { - ranges->Push(ranges_[i]->ToJson()); - } + ASSERT(ranges_[i] != nullptr); + ranges->Push(ranges_[i]->ToJson()); } result->Add("ranges", ranges); @@ -3989,61 +2105,6 @@ std::unique_ptr FunctionCoverage::ToJson() const return result; } -std::unique_ptr ScriptCoverage::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "ScriptCoverage::Create params is nullptr"; - return nullptr; - } - std::string error; - auto scriptCoverage = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - scriptCoverage->scriptId_ = DebuggerApi::ToStdString(result); - } else { - error += "'scriptId' should be a String;"; - } - } else { - error += "should contain 'scriptId';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "url"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - scriptCoverage->url_ = DebuggerApi::ToStdString(result); - } else { - error += "'url' should be a String;"; - } - } else { - error += "should contain 'url';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "functions"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t functionsLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < functionsLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr function = FunctionCoverage::Create(ecmaVm, resultValue); - scriptCoverage->functions_.emplace_back(std::move(function)); - } - } else { - error += "'functions' should be an Array;"; - } - } else { - error += "should contain 'functions';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "ScriptCoverage::Create " << error; - return nullptr; - } - return scriptCoverage; -} - std::unique_ptr ScriptCoverage::Create(const PtJson ¶ms) { std::string error; @@ -4072,15 +2133,12 @@ std::unique_ptr ScriptCoverage::Create(const PtJson ¶ms) int32_t len = functions->GetSize(); for (int32_t i = 0; i < len; ++i) { std::unique_ptr arrayEle = functions->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr pFunctions = FunctionCoverage::Create(*arrayEle); - if (pFunctions == nullptr) { - error += "'functions' format invalid;"; - } else { - scriptCoverage->functions_.emplace_back(std::move(pFunctions)); - } + ASSERT(arrayEle != nullptr); + std::unique_ptr pFunctions = FunctionCoverage::Create(*arrayEle); + if (pFunctions == nullptr) { + error += "'functions' format invalid;"; } else { - error += "Unknown 'functions';"; + scriptCoverage->functions_.emplace_back(std::move(pFunctions)); } } } else { @@ -4095,25 +2153,6 @@ std::unique_ptr ScriptCoverage::Create(const PtJson ¶ms) return scriptCoverage; } -Local ScriptCoverage::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, scriptId_.c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "url")), - Local(StringRef::NewFromUtf8(ecmaVm, url_.c_str()))); - size_t functionsLen = functions_.size(); - Local rangesValues = ArrayRef::New(ecmaVm, functionsLen); - for (size_t i = 0; i < functionsLen; i++) { - Local functionCoverage = functions_[i]->ToObject(ecmaVm); - rangesValues->Set(ecmaVm, i, functionCoverage); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "functions")), rangesValues); - return params; -} - std::unique_ptr ScriptCoverage::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -4124,42 +2163,14 @@ std::unique_ptr ScriptCoverage::ToJson() const std::unique_ptr functions = PtJson::CreateArray(); size_t len = functions_.size(); for (size_t i = 0; i < len; i++) { - if (functions_[i] != nullptr) { - functions->Push(functions_[i]->ToJson()); - } + ASSERT(functions_[i] != nullptr); + functions->Push(functions_[i]->ToJson()); } result->Add("functions", functions); return result; } -std::unique_ptr TypeObject::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "TypeObject::Create params is nullptr"; - return nullptr; - } - std::string error; - auto typeObject = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "name"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - typeObject->name_ = DebuggerApi::ToStdString(result); - } else { - error += "'name' should be a String;"; - } - } else { - error += "should contain 'name';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "TypeObject::Create " << error; - return nullptr; - } - return typeObject; -} - std::unique_ptr TypeObject::Create(const PtJson ¶ms) { std::string error; @@ -4182,15 +2193,6 @@ std::unique_ptr TypeObject::Create(const PtJson ¶ms) return typeObject; } -Local TypeObject::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "name")), - Local(StringRef::NewFromUtf8(ecmaVm, name_.c_str()))); - return params; -} - std::unique_ptr TypeObject::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); @@ -4200,50 +2202,6 @@ std::unique_ptr TypeObject::ToJson() const return result; } -std::unique_ptr TypeProfileEntry::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "TypeProfileEntry::Create params is nullptr"; - return nullptr; - } - std::string error; - auto typeProfileEntry = std::make_unique(); - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "offset"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsNumber()) { - typeProfileEntry->offset_ = static_cast(Local(result)->Value()); - } else { - error += "'offset' should be a Number;"; - } - } else { - error += "should contain 'offset';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "types"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t typesLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < typesLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local resultValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr type = TypeObject::Create(ecmaVm, resultValue); - typeProfileEntry->types_.emplace_back(std::move(type)); - } - } else { - error += "'types' should be an Array;"; - } - } else { - error += "should contain 'types';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "TypeProfileEntry::Create " << error; - return nullptr; - } - return typeProfileEntry; -} - std::unique_ptr TypeProfileEntry::Create(const PtJson ¶ms) { std::string error; @@ -4264,15 +2222,12 @@ std::unique_ptr TypeProfileEntry::Create(const PtJson ¶ms) int32_t len = types->GetSize(); for (int32_t i = 0; i < len; ++i) { std::unique_ptr arrayEle = types->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr pTypes = TypeObject::Create(*arrayEle); - if (pTypes == nullptr) { - error += "'types' format invalid;"; - } else { - typeProfileEntry->types_.emplace_back(std::move(pTypes)); - } + ASSERT(arrayEle != nullptr); + std::unique_ptr pTypes = TypeObject::Create(*arrayEle); + if (pTypes == nullptr) { + error += "'types' format invalid;"; } else { - error += "Unknown 'types';"; + typeProfileEntry->types_.emplace_back(std::move(pTypes)); } } } else { @@ -4287,27 +2242,11 @@ std::unique_ptr TypeProfileEntry::Create(const PtJson ¶ms) return typeProfileEntry; } -Local TypeProfileEntry::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "offset")), - IntegerRef::New(ecmaVm, offset_)); - size_t typeLen = types_.size(); - Local typeValues = ArrayRef::New(ecmaVm, typeLen); - for (size_t i = 0; i < typeLen; i++) { - Local typeObject = types_[i]->ToObject(ecmaVm); - typeValues->Set(ecmaVm, i, typeObject); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "types")), typeValues); - return params; -} - std::unique_ptr TypeProfileEntry::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); - result->Add("offset", static_cast(offset_)); + result->Add("offset", offset_); std::unique_ptr types = PtJson::CreateArray(); size_t len = types_.size(); @@ -4319,62 +2258,6 @@ std::unique_ptr TypeProfileEntry::ToJson() const return result; } -std::unique_ptr ScriptTypeProfile::Create(const EcmaVM *ecmaVm, const Local ¶ms) -{ - if (params.IsEmpty() || !params->IsObject()) { - LOG(ERROR, DEBUGGER) << "ScriptTypeProfile::Create params is nullptr"; - return nullptr; - } - std::string error; - auto scriptTypeProfile = std::make_unique(); - - Local result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "scriptId"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - scriptTypeProfile->scriptId_ = DebuggerApi::ToStdString(result); - } else { - error += "'scriptId' should be a String;"; - } - } else { - error += "should contain 'scriptId';"; - } - result = - Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "url"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsString()) { - scriptTypeProfile->url_ = DebuggerApi::ToStdString(result); - } else { - error += "'url' should be a String;"; - } - } else { - error += "should contain 'url';"; - } - result = Local(params)->Get(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "entries"))); - if (!result.IsEmpty() && !result->IsUndefined()) { - if (result->IsArray(ecmaVm)) { - auto array = Local(result); - int32_t entriesLen = array->Length(ecmaVm); - Local key = JSValueRef::Undefined(ecmaVm); - for (int32_t i = 0; i < entriesLen; ++i) { - key = IntegerRef::New(ecmaVm, i); - Local entriesValue = Local(array)->Get(ecmaVm, key->ToString(ecmaVm)); - std::unique_ptr entries = TypeProfileEntry::Create(ecmaVm, entriesValue); - scriptTypeProfile->entries_.emplace_back(std::move(entries)); - } - } else { - error += "'entries' should be an Array;"; - } - } else { - error += "should contain 'entries';"; - } - if (!error.empty()) { - LOG(ERROR, DEBUGGER) << "ScriptTypeProfile::Create " << error; - return scriptTypeProfile; - } - return scriptTypeProfile; -} - std::unique_ptr ScriptTypeProfile::Create(const PtJson ¶ms) { std::string error; @@ -4403,15 +2286,12 @@ std::unique_ptr ScriptTypeProfile::Create(const PtJson ¶m int32_t len = entries->GetSize(); for (int32_t i = 0; i < len; ++i) { std::unique_ptr arrayEle = entries->Get(i); - if (arrayEle != nullptr) { - std::unique_ptr pEntries = TypeProfileEntry::Create(*arrayEle); - if (pEntries == nullptr) { - error += "'entries' format invalid;"; - } else { - scriptTypeProfile->entries_.emplace_back(std::move(pEntries)); - } + ASSERT(arrayEle != nullptr); + std::unique_ptr pEntries = TypeProfileEntry::Create(*arrayEle); + if (pEntries == nullptr) { + error += "'entries' format invalid;"; } else { - error += "Unknown 'entries';"; + scriptTypeProfile->entries_.emplace_back(std::move(pEntries)); } } } else { @@ -4426,25 +2306,6 @@ std::unique_ptr ScriptTypeProfile::Create(const PtJson ¶m return scriptTypeProfile; } -Local ScriptTypeProfile::ToObject(const EcmaVM *ecmaVm) const -{ - Local params = NewObject(ecmaVm); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "scriptId")), - Local(StringRef::NewFromUtf8(ecmaVm, scriptId_.c_str()))); - params->Set(ecmaVm, - Local(StringRef::NewFromUtf8(ecmaVm, "url")), - Local(StringRef::NewFromUtf8(ecmaVm, url_.c_str()))); - size_t entriesLen = entries_.size(); - Local entriesValues = ArrayRef::New(ecmaVm, entriesLen); - for (size_t i = 0; i < entriesLen; i++) { - Local typeProfileEntryObject = entries_[i]->ToObject(ecmaVm); - entriesValues->Set(ecmaVm, i, typeProfileEntryObject); - } - params->Set(ecmaVm, Local(StringRef::NewFromUtf8(ecmaVm, "entries")), entriesValues); - return params; -} - std::unique_ptr ScriptTypeProfile::ToJson() const { std::unique_ptr result = PtJson::CreateObject(); diff --git a/ecmascript/tooling/base/pt_types.h b/ecmascript/tooling/base/pt_types.h index c752210c..61a6654e 100644 --- a/ecmascript/tooling/base/pt_types.h +++ b/ecmascript/tooling/base/pt_types.h @@ -30,14 +30,7 @@ class PtBaseTypes { public: PtBaseTypes() = default; virtual ~PtBaseTypes() = default; - virtual Local ToObject(const EcmaVM *ecmaVm) const = 0; - virtual std::unique_ptr ToJson() const - { - return PtJson::CreateObject(); - } - -protected: - static Local NewObject(const EcmaVM *ecmaVm); + virtual std::unique_ptr ToJson() const = 0; private: NO_COPY_SEMANTIC(PtBaseTypes); @@ -112,10 +105,8 @@ public: RemoteObject() = default; ~RemoteObject() override = default; - static std::unique_ptr FromTagged(const EcmaVM *ecmaVm, const Local &tagged); - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); + static std::unique_ptr FromTagged(const EcmaVM *ecmaVm, Local tagged); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; /* @@ -173,7 +164,7 @@ public: return value_.value_or(Local()); } - RemoteObject &SetValue(const Local &value) + RemoteObject &SetValue(Local value) { value_ = value; return *this; @@ -338,72 +329,50 @@ private: class PrimitiveRemoteObject final : public RemoteObject { public: - explicit PrimitiveRemoteObject(const EcmaVM *ecmaVm, const Local &tagged); + PrimitiveRemoteObject(const EcmaVM *ecmaVm, Local tagged); ~PrimitiveRemoteObject() override = default; }; class StringRemoteObject final : public RemoteObject { public: - explicit StringRemoteObject([[maybe_unused]] const EcmaVM *ecmaVm, const Local &tagged) - { - SetType(RemoteObject::TypeName::String).SetValue(tagged); - } + StringRemoteObject(const EcmaVM *ecmaVm, Local tagged); virtual ~StringRemoteObject() = default; }; class SymbolRemoteObject final : public RemoteObject { public: - explicit SymbolRemoteObject(const EcmaVM *ecmaVm, const Local &tagged) - { - SetType(RemoteObject::TypeName::Symbol).SetDescription(DescriptionForSymbol(ecmaVm, Local(tagged))); - } + SymbolRemoteObject(const EcmaVM *ecmaVm, Local tagged); ~SymbolRemoteObject() override = default; private: - std::string DescriptionForSymbol(const EcmaVM *ecmaVm, const Local &tagged) const; + std::string DescriptionForSymbol(const EcmaVM *ecmaVm, Local tagged) const; }; class FunctionRemoteObject final : public RemoteObject { public: - FunctionRemoteObject(const EcmaVM *ecmaVm, const Local &tagged) - { - SetType(RemoteObject::TypeName::Function) - .SetClassName(RemoteObject::ClassName::Function) - .SetDescription(DescriptionForFunction(ecmaVm, tagged)); - } + FunctionRemoteObject(const EcmaVM *ecmaVm, Local tagged); ~FunctionRemoteObject() override = default; private: - std::string DescriptionForFunction(const EcmaVM *ecmaVm, const Local &tagged) const; + std::string DescriptionForFunction(const EcmaVM *ecmaVm, Local tagged) const; }; class ObjectRemoteObject final : public RemoteObject { public: - explicit ObjectRemoteObject(const EcmaVM *ecmaVm, const Local &tagged, const std::string &classname) - { - SetType(RemoteObject::TypeName::Object) - .SetClassName(classname) - .SetDescription(DescriptionForObject(ecmaVm, tagged)); - } - explicit ObjectRemoteObject(const EcmaVM *ecmaVm, const Local &tagged, const std::string &classname, - const std::string &subtype) - { - SetType(RemoteObject::TypeName::Object) - .SetSubType(subtype) - .SetClassName(classname) - .SetDescription(DescriptionForObject(ecmaVm, tagged)); - } + ObjectRemoteObject(const EcmaVM *ecmaVm, Local tagged, const std::string &classname); + ObjectRemoteObject(const EcmaVM *ecmaVm, Local tagged, const std::string &classname, + const std::string &subtype); ~ObjectRemoteObject() override = default; - static std::string DescriptionForObject(const EcmaVM *ecmaVm, const Local &tagged); + static std::string DescriptionForObject(const EcmaVM *ecmaVm, Local tagged); private: - static std::string DescriptionForArray(const EcmaVM *ecmaVm, const Local &tagged); - static std::string DescriptionForRegexp(const EcmaVM *ecmaVm, const Local &tagged); - static std::string DescriptionForDate(const EcmaVM *ecmaVm, const Local &tagged); - static std::string DescriptionForMap(const Local &tagged); - static std::string DescriptionForSet(const Local &tagged); - static std::string DescriptionForError(const EcmaVM *ecmaVm, const Local &tagged); - static std::string DescriptionForArrayBuffer(const EcmaVM *ecmaVm, const Local &tagged); + static std::string DescriptionForArray(const EcmaVM *ecmaVm, Local tagged); + static std::string DescriptionForRegexp(const EcmaVM *ecmaVm, Local tagged); + static std::string DescriptionForDate(const EcmaVM *ecmaVm, Local tagged); + static std::string DescriptionForMap(Local tagged); + static std::string DescriptionForSet(Local tagged); + static std::string DescriptionForError(const EcmaVM *ecmaVm, Local tagged); + static std::string DescriptionForArrayBuffer(const EcmaVM *ecmaVm, Local tagged); }; // Runtime.ExceptionDetails @@ -411,9 +380,7 @@ class ExceptionDetails final : public PtBaseTypes { public: ExceptionDetails() = default; ~ExceptionDetails() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; int32_t GetExceptionId() const @@ -548,9 +515,7 @@ public: InternalPropertyDescriptor() = default; ~InternalPropertyDescriptor() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const @@ -597,9 +562,7 @@ public: PrivatePropertyDescriptor() = default; ~PrivatePropertyDescriptor() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const @@ -686,11 +649,9 @@ public: PropertyDescriptor() = default; ~PropertyDescriptor() override = default; - static std::unique_ptr FromProperty(const EcmaVM *ecmaVm, const Local &name, + static std::unique_ptr FromProperty(const EcmaVM *ecmaVm, Local name, const PropertyAttribute &property); - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; std::string GetName() const @@ -873,10 +834,6 @@ public: ~CallArgument() override = default; static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject([[maybe_unused]] const EcmaVM *ecmaVm) const override - { - return Local(); - } std::unique_ptr ToJson() const override; Local GetValue() const @@ -884,7 +841,7 @@ public: return value_.value_or(Local()); } - CallArgument &SetValue(const Local &value) + CallArgument &SetValue(Local value) { value_ = value; return *this; @@ -960,9 +917,7 @@ public: Location() = default; ~Location() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; ScriptId GetScriptId() const @@ -1007,7 +962,7 @@ private: NO_COPY_SEMANTIC(Location); NO_MOVE_SEMANTIC(Location); - ScriptId scriptId_ {}; + ScriptId scriptId_ {0}; int32_t lineNumber_ {0}; std::optional columnNumber_ {}; }; @@ -1019,7 +974,6 @@ public: ~ScriptPosition() override = default; static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; int32_t GetLine() const @@ -1057,9 +1011,7 @@ class SearchMatch : public PtBaseTypes { public: SearchMatch() = default; ~SearchMatch() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; private: @@ -1077,7 +1029,6 @@ public: ~LocationRange() override = default; static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; ScriptId GetScriptId() const @@ -1117,7 +1068,7 @@ private: NO_COPY_SEMANTIC(LocationRange); NO_MOVE_SEMANTIC(LocationRange); - ScriptId scriptId_ {}; + ScriptId scriptId_ {0}; std::unique_ptr start_ {nullptr}; std::unique_ptr end_ {nullptr}; }; @@ -1128,9 +1079,7 @@ public: BreakLocation() = default; ~BreakLocation() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; ScriptId GetScriptId() const @@ -1214,7 +1163,7 @@ private: NO_COPY_SEMANTIC(BreakLocation); NO_MOVE_SEMANTIC(BreakLocation); - ScriptId scriptId_ {}; + ScriptId scriptId_ {0}; int32_t lineNumber_ {0}; std::optional columnNumber_ {}; std::optional type_ {}; @@ -1240,9 +1189,7 @@ public: Scope() = default; ~Scope() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; /* @@ -1391,9 +1338,7 @@ public: CallFrame() = default; ~CallFrame() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; CallFrameId GetCallFrameId() const @@ -1521,12 +1466,10 @@ class SamplingHeapProfileSample final : public PtBaseTypes { public: SamplingHeapProfileSample() = default; ~SamplingHeapProfileSample() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; - SamplingHeapProfileSample &SetSize(size_t size) + SamplingHeapProfileSample &SetSize(int32_t size) { size_ = size; return *this; @@ -1548,7 +1491,7 @@ public: return nodeId_; } - SamplingHeapProfileSample &SetOrdinal(size_t ordinal) + SamplingHeapProfileSample &SetOrdinal(int32_t ordinal) { ordinal_ = ordinal; return *this; @@ -1563,19 +1506,17 @@ private: NO_COPY_SEMANTIC(SamplingHeapProfileSample); NO_MOVE_SEMANTIC(SamplingHeapProfileSample); - size_t size_ {}; - int32_t nodeId_ {}; - size_t ordinal_ {}; + int32_t size_ {0}; + int32_t nodeId_ {0}; + int32_t ordinal_ {0}; }; class RuntimeCallFrame final : public PtBaseTypes { public: RuntimeCallFrame() = default; ~RuntimeCallFrame() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); static std::unique_ptr FromFrameInfo(const FrameInfo &cpuFrameInfo); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; RuntimeCallFrame &SetFunctionName(const std::string &functionName) @@ -1640,17 +1581,15 @@ private: std::string functionName_ {}; std::string scriptId_ {}; std::string url_ {}; - int32_t lineNumber_ {}; - int32_t columnNumber_ {}; + int32_t lineNumber_ {0}; + int32_t columnNumber_ {0}; }; class SamplingHeapProfileNode final : public PtBaseTypes { public: SamplingHeapProfileNode() = default; ~SamplingHeapProfileNode() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; SamplingHeapProfileNode &SetCallFrame(std::unique_ptr callFrame) @@ -1664,7 +1603,7 @@ public: return callFrame_.get(); } - SamplingHeapProfileNode &SetSelfSize(size_t selfSize) + SamplingHeapProfileNode &SetSelfSize(int32_t selfSize) { selfSize_ = selfSize; return *this; @@ -1702,8 +1641,8 @@ private: NO_MOVE_SEMANTIC(SamplingHeapProfileNode); std::unique_ptr callFrame_ {nullptr}; - size_t selfSize_ {}; - int32_t id_ {}; + int32_t selfSize_ {0}; + int32_t id_ {0}; std::vector> children_ {}; }; @@ -1711,9 +1650,7 @@ class SamplingHeapProfile final : public PtBaseTypes { public: SamplingHeapProfile() = default; ~SamplingHeapProfile() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; SamplingHeapProfile &SetHead(std::unique_ptr head) @@ -1753,9 +1690,7 @@ public: PositionTickInfo() = default; ~PositionTickInfo() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; int32_t GetLine() const @@ -1763,7 +1698,7 @@ public: return line_; } - PositionTickInfo &SetLine(size_t line) + PositionTickInfo &SetLine(int32_t line) { line_ = line; return *this; @@ -1774,7 +1709,7 @@ public: return ticks_; } - PositionTickInfo &SetTicks(size_t ticks) + PositionTickInfo &SetTicks(int32_t ticks) { ticks_ = ticks; return *this; @@ -1783,8 +1718,8 @@ public: private: NO_COPY_SEMANTIC(PositionTickInfo); NO_MOVE_SEMANTIC(PositionTickInfo); - size_t line_ {0}; - size_t ticks_ {0}; + int32_t line_ {0}; + int32_t ticks_ {0}; }; // Profiler.ProfileNode @@ -1793,10 +1728,8 @@ public: ProfileNode() = default; ~ProfileNode() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); static std::unique_ptr FromCpuProfileNode(const CpuProfileNode &cpuProfileNode); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; int32_t GetId() const @@ -1910,10 +1843,8 @@ public: Profile() = default; ~Profile() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); static std::unique_ptr FromProfileInfo(const ProfileInfo &profileInfo); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; int64_t GetStartTime() const @@ -2004,9 +1935,7 @@ public: Coverage() = default; ~Coverage() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; int32_t GetStartOffset() const @@ -2014,7 +1943,7 @@ public: return startOffset_; } - Coverage &SetStartOffset(size_t startOffset) + Coverage &SetStartOffset(int32_t startOffset) { startOffset_ = startOffset; return *this; @@ -2025,7 +1954,7 @@ public: return endOffset_; } - Coverage &SetEndOffset(size_t endOffset) + Coverage &SetEndOffset(int32_t endOffset) { endOffset_ = endOffset; return *this; @@ -2036,7 +1965,7 @@ public: return count_; } - Coverage &SetCount(size_t count) + Coverage &SetCount(int32_t count) { count_ = count; return *this; @@ -2057,9 +1986,7 @@ public: FunctionCoverage() = default; ~FunctionCoverage() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; const std::string &GetFunctionName() const @@ -2111,9 +2038,7 @@ public: ScriptCoverage() = default; ~ScriptCoverage() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; const std::string &GetScriptId() const @@ -2164,9 +2089,7 @@ public: TypeObject() = default; ~TypeObject() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; const std::string &GetName() const @@ -2193,9 +2116,7 @@ public: TypeProfileEntry() = default; ~TypeProfileEntry() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; int32_t GetOffset() const @@ -2203,7 +2124,7 @@ public: return offset_; } - TypeProfileEntry &SetOffset(size_t offset) + TypeProfileEntry &SetOffset(int32_t offset) { offset_ = offset; return *this; @@ -2224,7 +2145,7 @@ private: NO_COPY_SEMANTIC(TypeProfileEntry); NO_MOVE_SEMANTIC(TypeProfileEntry); - size_t offset_ {0}; + int32_t offset_ {0}; std::vector> types_ {}; }; @@ -2234,9 +2155,7 @@ public: ScriptTypeProfile() = default; ~ScriptTypeProfile() override = default; - static std::unique_ptr Create(const EcmaVM *ecmaVm, const Local ¶ms); static std::unique_ptr Create(const PtJson ¶ms); - Local ToObject(const EcmaVM *ecmaVm) const override; std::unique_ptr ToJson() const override; const std::string &GetScriptId() const diff --git a/ecmascript/tooling/dispatcher.cpp b/ecmascript/tooling/dispatcher.cpp index 2542c62c..0610855b 100644 --- a/ecmascript/tooling/dispatcher.cpp +++ b/ecmascript/tooling/dispatcher.cpp @@ -24,7 +24,7 @@ #include "ecmascript/tooling/protocol_channel.h" namespace panda::ecmascript::tooling { -DispatchRequest::DispatchRequest(const EcmaVM *ecmaVm, const std::string &message) : ecmaVm_(ecmaVm) +DispatchRequest::DispatchRequest(const std::string &message) { std::unique_ptr json = PtJson::Parse(message); if (json == nullptr || !json->IsObject()) { @@ -76,31 +76,6 @@ DispatchRequest::DispatchRequest(const EcmaVM *ecmaVm, const std::string &messag return; } params_ = std::move(params); - - // below code will delete soon - Local msgValue = JSON::Parse(ecmaVm, StringRef::NewFromUtf8(ecmaVm, message.c_str())); - if (msgValue->IsException()) { - DebuggerApi::ClearException(ecmaVm); - LOG(ERROR, DEBUGGER) << "json parse throw exception"; - return; - } - if (!msgValue->IsObject()) { - code_ = RequestCode::JSON_PARSE_ERROR; - LOG(ERROR, DEBUGGER) << "json parse error"; - return; - } - Local paramsStr = StringRef::NewFromUtf8(ecmaVm, "params"); - ObjectRef *msgObj = ObjectRef::Cast(*msgValue); - Local paramsValue = msgObj->Get(ecmaVm, paramsStr); - if (paramsValue.IsEmpty()) { - return; - } - if (!paramsValue->IsObject()) { - code_ = RequestCode::PARAMS_FORMAT_ERROR; - LOG(ERROR, DEBUGGER) << "params format error"; - return; - } - paramsObj_ = paramsValue; } DispatchRequest::~DispatchRequest() diff --git a/ecmascript/tooling/dispatcher.h b/ecmascript/tooling/dispatcher.h index 9a679c1e..b247ba8b 100644 --- a/ecmascript/tooling/dispatcher.h +++ b/ecmascript/tooling/dispatcher.h @@ -47,7 +47,7 @@ enum class ResponseCode : uint8_t { OK, NOK }; class DispatchRequest { public: - explicit DispatchRequest(const EcmaVM *ecmaVm, const std::string &message); + explicit DispatchRequest(const std::string &message); ~DispatchRequest(); bool IsValid() const @@ -58,10 +58,6 @@ public: { return callId_; } - Local GetParamsObj() const - { - return paramsObj_; - } const PtJson &GetParams() const { return *params_; @@ -74,17 +70,11 @@ public: { return method_; } - const EcmaVM *GetEcmaVM() const - { - return ecmaVm_; - } private: - const EcmaVM *ecmaVm_ {nullptr}; int32_t callId_ = -1; std::string domain_ {}; std::string method_ {}; - Local paramsObj_ {}; std::unique_ptr params_ = std::make_unique(); RequestCode code_ {RequestCode::OK}; std::string errorMsg_ {}; diff --git a/ecmascript/tooling/interface/js_debugger_manager.h b/ecmascript/tooling/interface/js_debugger_manager.h index 50f7bace..f036c8fb 100644 --- a/ecmascript/tooling/interface/js_debugger_manager.h +++ b/ecmascript/tooling/interface/js_debugger_manager.h @@ -28,7 +28,7 @@ class JsDebuggerManager { public: using LibraryHandle = os::library_loader::LibraryHandle; using ObjectUpdaterFunc = - std::function &)>; + std::function)>; JsDebuggerManager() = default; ~JsDebuggerManager() @@ -94,7 +94,7 @@ public: updaterFunc_ = updaterFunc; } - void NotifyLocalScopeUpdated(std::string_view varName, const Local &value) + void NotifyLocalScopeUpdated(std::string_view varName, Local value) { if (updaterFunc_ != nullptr) { (*updaterFunc_)(frameHandler_.get(), varName, value); diff --git a/ecmascript/tooling/protocol_handler.cpp b/ecmascript/tooling/protocol_handler.cpp index 48e18a06..be0597a3 100644 --- a/ecmascript/tooling/protocol_handler.cpp +++ b/ecmascript/tooling/protocol_handler.cpp @@ -15,7 +15,6 @@ #include "ecmascript/tooling/protocol_handler.h" -#include "ecmascript/base/string_helper.h" #include "ecmascript/tooling/agent/debugger_impl.h" #include "utils/logger.h" @@ -39,7 +38,7 @@ void ProtocolHandler::ProcessCommand(const std::string &msg) LOG(DEBUG, DEBUGGER) << "ProtocolHandler::ProcessCommand: " << msg; [[maybe_unused]] LocalScope scope(vm_); Local exception = DebuggerApi::GetAndClearException(vm_); - dispatcher_.Dispatch(DispatchRequest(vm_, msg)); + dispatcher_.Dispatch(DispatchRequest(msg)); DebuggerApi::SetException(vm_, exception); } @@ -49,51 +48,42 @@ void ProtocolHandler::SendResponse(const DispatchRequest &request, const Dispatc LOG(INFO, DEBUGGER) << "ProtocolHandler::SendResponse: " << (response.IsOk() ? "success" : "failed: " + response.GetMessage()); - Local reply = PtBaseTypes::NewObject(vm_); - reply->Set(vm_, StringRef::NewFromUtf8(vm_, "id"), IntegerRef::New(vm_, request.GetCallId())); - Local resultObj; + std::unique_ptr reply = PtJson::CreateObject(); + reply->Add("id", request.GetCallId()); + std::unique_ptr resultObj; if (response.IsOk()) { - resultObj = result.ToObject(vm_); + resultObj = result.ToJson(); } else { resultObj = CreateErrorReply(response); } - reply->Set(vm_, StringRef::NewFromUtf8(vm_, "result"), Local(resultObj)); - SendReply(reply); + reply->Add("result", resultObj); + SendReply(*reply); } void ProtocolHandler::SendNotification(const PtBaseEvents &events) { LOG(DEBUG, DEBUGGER) << "ProtocolHandler::SendNotification: " << events.GetName(); - SendReply(events.ToObject(vm_)); + SendReply(*events.ToJson()); } -void ProtocolHandler::SendReply(Local reply) +void ProtocolHandler::SendReply(const PtJson &reply) { - Local str = JSON::Stringify(vm_, reply); - if (str->IsException()) { - DebuggerApi::ClearException(vm_); - LOG(ERROR, DEBUGGER) << "json stringifier throw exception"; - return; - } - if (!str->IsString()) { + std::string str = reply.Stringify(); + if (str.empty()) { LOG(ERROR, DEBUGGER) << "ProtocolHandler::SendReply: json stringify error"; return; } - callback_(StringRef::Cast(*str)->ToString()); + callback_(str); } -Local ProtocolHandler::CreateErrorReply(const DispatchResponse &response) +std::unique_ptr ProtocolHandler::CreateErrorReply(const DispatchResponse &response) { - Local result = PtBaseTypes::NewObject(vm_); + std::unique_ptr result = PtJson::CreateObject(); if (!response.IsOk()) { - result->Set(vm_, - Local(StringRef::NewFromUtf8(vm_, "code")), - IntegerRef::New(vm_, static_cast(response.GetError()))); - result->Set(vm_, - Local(StringRef::NewFromUtf8(vm_, "message")), - Local(StringRef::NewFromUtf8(vm_, response.GetMessage().c_str()))); + result->Add("code", static_cast(response.GetError())); + result->Add("message", response.GetMessage().c_str()); } return result; diff --git a/ecmascript/tooling/protocol_handler.h b/ecmascript/tooling/protocol_handler.h index cffaf53e..08b44e89 100644 --- a/ecmascript/tooling/protocol_handler.h +++ b/ecmascript/tooling/protocol_handler.h @@ -39,8 +39,8 @@ public: private: NO_MOVE_SEMANTIC(ProtocolHandler); NO_COPY_SEMANTIC(ProtocolHandler); - Local CreateErrorReply(const DispatchResponse &response); - void SendReply(Local reply); + std::unique_ptr CreateErrorReply(const DispatchResponse &response); + void SendReply(const PtJson &reply); std::function callback_; Dispatcher dispatcher_; diff --git a/ecmascript/tooling/test/debugger_events_test.cpp b/ecmascript/tooling/test/debugger_events_test.cpp index ff1f8e93..b837dec5 100644 --- a/ecmascript/tooling/test/debugger_events_test.cpp +++ b/ecmascript/tooling/test/debugger_events_test.cpp @@ -60,33 +60,6 @@ protected: JSThread *thread {nullptr}; }; -HWTEST_F_L0(DebuggerEventsTest, BreakpointResolvedToObjectTest) -{ - BreakpointResolved breakpointResolved; - Local tmpStr = StringRef::NewFromUtf8(ecmaVm, "params"); - - auto location = std::make_unique(); - location->SetScriptId(2).SetLine(99); - breakpointResolved.SetBreakpointId("00").SetLocation(std::move(location)); - Local object1 = breakpointResolved.ToObject(ecmaVm); - Local result = object1->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - Local object = Local(result); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "breakpointId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("00", DebuggerApi::ToStdString(result)); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "location"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); -} - HWTEST_F_L0(DebuggerEventsTest, BreakpointResolvedToJsonTest) { BreakpointResolved breakpointResolved; @@ -111,6 +84,7 @@ HWTEST_F_L0(DebuggerEventsTest, BreakpointResolvedToJsonTest) EXPECT_EQ(lineNumber, 99); } +#ifdef CHANGE_TOJSON HWTEST_F_L0(DebuggerEventsTest, PausedToObjectTest) { Paused paused; @@ -129,7 +103,7 @@ HWTEST_F_L0(DebuggerEventsTest, PausedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("exception", DebuggerApi::ToStdString(result)); + EXPECT_EQ("exception", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "callFrames"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); @@ -149,7 +123,7 @@ HWTEST_F_L0(DebuggerEventsTest, ResumedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); Local result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(resumed.GetName(), DebuggerApi::ToStdString(result)); + EXPECT_EQ(resumed.GetName(), Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "params"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); @@ -188,13 +162,13 @@ HWTEST_F_L0(DebuggerEventsTest, ScriptFailedToParseToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("100", DebuggerApi::ToStdString(result)); + EXPECT_EQ("100", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "url"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("use/test.js", DebuggerApi::ToStdString(result)); + EXPECT_EQ("use/test.js", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "startLine"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); @@ -230,7 +204,7 @@ HWTEST_F_L0(DebuggerEventsTest, ScriptFailedToParseToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("hash0001", DebuggerApi::ToStdString(result)); + EXPECT_EQ("hash0001", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "executionContextAuxData"); ASSERT_FALSE(object->Has(ecmaVm, tmpStr)); @@ -239,7 +213,7 @@ HWTEST_F_L0(DebuggerEventsTest, ScriptFailedToParseToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("usr/", DebuggerApi::ToStdString(result)); + EXPECT_EQ("usr/", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "hasSourceURL"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); @@ -269,13 +243,13 @@ HWTEST_F_L0(DebuggerEventsTest, ScriptFailedToParseToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("JavaScript", DebuggerApi::ToStdString(result)); + EXPECT_EQ("JavaScript", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "embedderName"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("hh", DebuggerApi::ToStdString(result)); + EXPECT_EQ("hh", Local(result)->ToString()); } HWTEST_F_L0(DebuggerEventsTest, ScriptParsedToObjectTest) @@ -309,13 +283,13 @@ HWTEST_F_L0(DebuggerEventsTest, ScriptParsedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("10", DebuggerApi::ToStdString(result)); + EXPECT_EQ("10", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "url"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("use/test.js", DebuggerApi::ToStdString(result)); + EXPECT_EQ("use/test.js", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "startLine"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); @@ -351,7 +325,7 @@ HWTEST_F_L0(DebuggerEventsTest, ScriptParsedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("hash0001", DebuggerApi::ToStdString(result)); + EXPECT_EQ("hash0001", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "executionContextAuxData"); ASSERT_FALSE(object->Has(ecmaVm, tmpStr)); @@ -366,7 +340,7 @@ HWTEST_F_L0(DebuggerEventsTest, ScriptParsedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("usr/", DebuggerApi::ToStdString(result)); + EXPECT_EQ("usr/", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "hasSourceURL"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); @@ -396,13 +370,13 @@ HWTEST_F_L0(DebuggerEventsTest, ScriptParsedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("JavaScript", DebuggerApi::ToStdString(result)); + EXPECT_EQ("JavaScript", Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "embedderName"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("hh", DebuggerApi::ToStdString(result)); + EXPECT_EQ("hh", Local(result)->ToString()); } HWTEST_F_L0(DebuggerEventsTest, ConsoleProfileFinishedToObjectTest) @@ -430,7 +404,7 @@ HWTEST_F_L0(DebuggerEventsTest, ConsoleProfileFinishedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "11"); + EXPECT_EQ(Local(result)->ToString(), "11"); tmpStr = StringRef::NewFromUtf8(ecmaVm, "location"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); @@ -448,7 +422,7 @@ HWTEST_F_L0(DebuggerEventsTest, ConsoleProfileFinishedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "001"); + EXPECT_EQ(Local(result)->ToString(), "001"); } HWTEST_F_L0(DebuggerEventsTest, ConsoleProfileStartedToObjectTest) @@ -469,14 +443,14 @@ HWTEST_F_L0(DebuggerEventsTest, ConsoleProfileStartedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "12"); + EXPECT_EQ(Local(result)->ToString(), "12"); Local tmpObject = consoleProfileStarted.GetLocation()->ToObject(ecmaVm); tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); ASSERT_TRUE(tmpObject->Has(ecmaVm, tmpStr)); Local tmpResult = tmpObject->Get(ecmaVm, tmpStr); ASSERT_TRUE(!tmpResult.IsEmpty() && !tmpResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(tmpResult), "17"); + EXPECT_EQ(Local(tmpResult)->ToString(), "17"); tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); ASSERT_TRUE(tmpObject->Has(ecmaVm, tmpStr)); tmpResult = tmpObject->Get(ecmaVm, tmpStr); @@ -487,7 +461,7 @@ HWTEST_F_L0(DebuggerEventsTest, ConsoleProfileStartedToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "002"); + EXPECT_EQ(Local(result)->ToString(), "002"); } HWTEST_F_L0(DebuggerEventsTest, PreciseCoverageDeltaUpdateToObjectTest) @@ -514,7 +488,7 @@ HWTEST_F_L0(DebuggerEventsTest, PreciseCoverageDeltaUpdateToObjectTest) ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "percise"); + EXPECT_EQ(Local(result)->ToString(), "percise"); tmpStr = StringRef::NewFromUtf8(ecmaVm, "result"); ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); result = object->Get(ecmaVm, tmpStr); @@ -588,4 +562,5 @@ HWTEST_F_L0(DebuggerEventsTest, ReportHeapSnapshotProgressToObjectTest) ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); EXPECT_EQ(Local(result)->Value(), 100); } +#endif } // namespace panda::test \ No newline at end of file diff --git a/ecmascript/tooling/test/debugger_params_test.cpp b/ecmascript/tooling/test/debugger_params_test.cpp index 61825046..f0f55955 100644 --- a/ecmascript/tooling/test/debugger_params_test.cpp +++ b/ecmascript/tooling/test/debugger_params_test.cpp @@ -72,13 +72,13 @@ HWTEST_F_L0(DebuggerParamsTest, EnableParamsCreateTest) // abnormal msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - enableParams = EnableParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + enableParams = EnableParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(enableParams, nullptr); EXPECT_FALSE(enableParams->HasMaxScriptsCacheSize()); // normal msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"maxScriptsCacheSize":100}})"; - enableParams = EnableParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + enableParams = EnableParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(enableParams, nullptr); EXPECT_EQ(enableParams->GetMaxScriptsCacheSize(), 100); } @@ -90,29 +90,29 @@ HWTEST_F_L0(DebuggerParamsTest, StartSamplingParamsCreateTest) // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(startSamplingData, nullptr); EXPECT_EQ(startSamplingData->GetSamplingInterval(), 32768); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(startSamplingData, nullptr); EXPECT_EQ(startSamplingData->GetSamplingInterval(), 32768); // abnormal params of params.sub-key=["samplingInterval":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"samplingInterval":true}})"; - startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(startSamplingData, nullptr); // abnormal params of params.sub-key=["samplingInterval":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"samplingInterval":"Test"}})"; - startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(startSamplingData, nullptr); // abnormal params of params.sub-key = [ "size"=100,"nodeId"=1,"ordinal"=10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"samplingInterval":1000}})"; - startSamplingData = StartSamplingParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + startSamplingData = StartSamplingParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(startSamplingData, nullptr); EXPECT_EQ(startSamplingData->GetSamplingInterval(), 1000); } @@ -124,29 +124,29 @@ HWTEST_F_L0(DebuggerParamsTest, StartTrackingHeapObjectsParamsCreateTest) // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_FALSE(objectData->GetTrackAllocations()); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_FALSE(objectData->GetTrackAllocations()); // abnormal params of params.sub-key=["trackAllocations":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"trackAllocations":10}})"; - objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["trackAllocations":"Test"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"trackAllocations":"Test"}})"; - objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["trackAllocations":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"trackAllocations":true}})"; - objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_TRUE(objectData->GetTrackAllocations()); } @@ -158,7 +158,7 @@ HWTEST_F_L0(DebuggerParamsTest, StopTrackingHeapObjectsParamsCreateTest) // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_FALSE(objectData->GetReportProgress()); ASSERT_FALSE(objectData->GetTreatGlobalObjectsAsRoots()); @@ -166,7 +166,7 @@ HWTEST_F_L0(DebuggerParamsTest, StopTrackingHeapObjectsParamsCreateTest) // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_FALSE(objectData->GetReportProgress()); ASSERT_FALSE(objectData->GetTreatGlobalObjectsAsRoots()); @@ -176,21 +176,21 @@ HWTEST_F_L0(DebuggerParamsTest, StopTrackingHeapObjectsParamsCreateTest) "reportProgress":10, "treatGlobalObjectsAsRoots":10, "captureNumericValue":10}})"; - objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "reportProgress":"Test", "treatGlobalObjectsAsRoots":"Test", "captureNumericValue":"Test"}})"; - objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "reportProgress":true, "treatGlobalObjectsAsRoots":true, "captureNumericValue":true}})"; - objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StopTrackingHeapObjectsParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_TRUE(objectData->GetReportProgress()); ASSERT_TRUE(objectData->GetTreatGlobalObjectsAsRoots()); @@ -204,37 +204,37 @@ HWTEST_F_L0(DebuggerParamsTest, AddInspectedHeapObjectParamsCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["heapObjectId":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"heapObjectId":10}})"; - objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["heapObjectId":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"heapObjectId":true}})"; - objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["heapObjectId":“10”] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"heapObjectId":"10"}})"; - objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = AddInspectedHeapObjectParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ(objectData->GetHeapObjectId(), 10); } @@ -246,17 +246,17 @@ HWTEST_F_L0(DebuggerParamsTest, GetHeapObjectIdParamsCreateTest) // abnormal params of params.sub-key=["objectId":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":10}})"; - objectData = GetHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = GetHeapObjectIdParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["objectId":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":true}})"; - objectData = GetHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = GetHeapObjectIdParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["objectId":“10”] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":"10"}})"; - objectData = GetHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = GetHeapObjectIdParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ((int)objectData->GetObjectId(), 10); } @@ -268,23 +268,23 @@ HWTEST_F_L0(DebuggerParamsTest, GetObjectByHeapObjectIdParamsCreateTest) // abnormal params of params.sub-key=["objectId":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":10}})"; - objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["objectId":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":"10", "objectGroup":10}})"; - objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of params.sub-key=["objectId":“10”] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":"10"}})"; - objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ((int)objectData->GetObjectId(), 10); ASSERT_FALSE(objectData->HasObjectGroup()); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"objectId":"10", "objectGroup":"groupname"}})"; - objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = GetObjectByHeapObjectIdParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ((int)objectData->GetObjectId(), 10); EXPECT_EQ(objectData->GetObjectGroup(), "groupname"); @@ -297,33 +297,33 @@ HWTEST_F_L0(DebuggerParamsTest, StartPreciseCoverageParamCreateTest) // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "callCount":8, "detailed":8, "allowTriggeredUpdates":8}})"; - objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "callCount":"Test", "detailed":"Test", "allowTriggeredUpdates":"Test"}})"; - objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "callCount":true, "detailed":true, "allowTriggeredUpdates":true}})"; - objectData = StartPreciseCoverageParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = StartPreciseCoverageParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); ASSERT_TRUE(objectData->GetCallCount()); ASSERT_TRUE(objectData->GetDetailed()); @@ -337,31 +337,31 @@ HWTEST_F_L0(DebuggerParamsTest, SetSamplingIntervalParamsCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "interval":"500"}})"; - objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(objectData, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"interval":500}})"; - objectData = SetSamplingIntervalParams::Create(DispatchRequest(ecmaVm, msg).GetParams()); + objectData = SetSamplingIntervalParams::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(objectData, nullptr); EXPECT_EQ(objectData->GetInterval(), 500); } diff --git a/ecmascript/tooling/test/debugger_returns_test.cpp b/ecmascript/tooling/test/debugger_returns_test.cpp index 04cfa21d..0f9ca53d 100644 --- a/ecmascript/tooling/test/debugger_returns_test.cpp +++ b/ecmascript/tooling/test/debugger_returns_test.cpp @@ -60,6 +60,7 @@ protected: JSThread *thread {nullptr}; }; +#ifdef CHANGE_TOJSON HWTEST_F_L0(DebuggerReturnsTest, EnableReturnsToObjectTest) { std::unique_ptr enableReturns = std::make_unique(100U); @@ -69,7 +70,7 @@ HWTEST_F_L0(DebuggerReturnsTest, EnableReturnsToObjectTest) ASSERT_TRUE(enableObject->Has(ecmaVm, tmpStr)); Local result = enableObject->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string("100"), DebuggerApi::ToStdString(result)); + EXPECT_EQ(std::string("100"), Local(result)->ToString()); } HWTEST_F_L0(DebuggerReturnsTest, SetBreakpointByUrlReturnsToObjectTest) @@ -88,7 +89,7 @@ HWTEST_F_L0(DebuggerReturnsTest, SetBreakpointByUrlReturnsToObjectTest) ASSERT_TRUE(setObject->Has(ecmaVm, tmpStr)); Local result = setObject->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string("11"), DebuggerApi::ToStdString(result)); + EXPECT_EQ(std::string("11"), Local(result)->ToString()); } HWTEST_F_L0(DebuggerReturnsTest, EvaluateOnCallFrameReturnsToObjectTest) @@ -136,13 +137,13 @@ HWTEST_F_L0(DebuggerReturnsTest, GetScriptSourceReturnsToObjectTest) ASSERT_TRUE(scriptObject->Has(ecmaVm, tmpStr)); Local result = scriptObject->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string("source_1"), DebuggerApi::ToStdString(result)); + EXPECT_EQ(std::string("source_1"), Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "bytecode"); ASSERT_TRUE(scriptObject->Has(ecmaVm, tmpStr)); result = scriptObject->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string("bytecode_1"), DebuggerApi::ToStdString(result)); + EXPECT_EQ(std::string("bytecode_1"), Local(result)->ToString()); } HWTEST_F_L0(DebuggerReturnsTest, RestartFrameReturnsToObjectTest) @@ -170,7 +171,7 @@ HWTEST_F_L0(DebuggerReturnsTest, SetBreakpointReturnsToObjectTest) ASSERT_TRUE(breakObject->Has(ecmaVm, tmpStr)); Local result = breakObject->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string("breakpointId_1"), DebuggerApi::ToStdString(result)); + EXPECT_EQ(std::string("breakpointId_1"), Local(result)->ToString()); tmpStr = StringRef::NewFromUtf8(ecmaVm, "actualLocation"); ASSERT_TRUE(breakObject->Has(ecmaVm, tmpStr)); @@ -189,7 +190,7 @@ HWTEST_F_L0(DebuggerReturnsTest, SetInstrumentationBreakpointReturnsToObjectTest ASSERT_TRUE(instrumentationObject->Has(ecmaVm, tmpStr)); Local result = instrumentationObject->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string("111"), DebuggerApi::ToStdString(result)); + EXPECT_EQ(std::string("111"), Local(result)->ToString()); } HWTEST_F_L0(DebuggerReturnsTest, SetScriptSourceReturnsToObjectTest) @@ -246,7 +247,10 @@ HWTEST_F_L0(DebuggerReturnsTest, GetPropertiesReturnsToObjectTest) HWTEST_F_L0(DebuggerReturnsTest, StopSamplingReturnsToObjectTest) { + std::unique_ptr head = std::make_unique(); std::unique_ptr profile = std::make_unique(); + profile->SetHead(std::move(head)); + profile->SetSamples(); std::unique_ptr stopSamplingReturns = std::make_unique(std::move(profile)); ASSERT_NE(stopSamplingReturns, nullptr); @@ -268,7 +272,7 @@ HWTEST_F_L0(DebuggerReturnsTest, GetHeapObjectIdReturnsToObjectTest) Local result = object->Get(ecmaVm, tmpStr); ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string("10"), DebuggerApi::ToStdString(result)); + EXPECT_EQ(std::string("10"), Local(result)->ToString()); } HWTEST_F_L0(DebuggerReturnsTest, GetObjectByHeapObjectIdReturnsToObjectTest) @@ -381,4 +385,5 @@ HWTEST_F_L0(DebuggerReturnsTest, TakeTypeProfileturnsToObjectTest) ASSERT_TRUE(!tmpResult.IsEmpty() && !tmpResult->IsUndefined()); ASSERT_TRUE(tmpResult->IsArray(ecmaVm)); } +#endif } // namespace panda::test \ No newline at end of file diff --git a/ecmascript/tooling/test/debugger_types_test.cpp b/ecmascript/tooling/test/debugger_types_test.cpp index b505de45..2abb639c 100644 --- a/ecmascript/tooling/test/debugger_types_test.cpp +++ b/ecmascript/tooling/test/debugger_types_test.cpp @@ -69,60 +69,59 @@ HWTEST_F_L0(DebuggerTypesTest, RemoteObjectCreateTest) { std::string msg; std::unique_ptr remoteObject; - Local tmpStr; // abnormal params of null msg msg = std::string() + R"({})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of params.sub-key = [ type = 100, ] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":100}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of params.sub-key = [ type = [ "sub": "test" ] }, ] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":100}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // normal params of params.sub-key = [ type = "object", ] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"("}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); // abnormal params of params.sub-key = [ type = "object", subtype = "unknown"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","subtype":"unknown"}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of params.sub-key = [ type = "object", subtype = 100] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","subtype":100}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // normal params of params.sub-key = [ type = "object", subtype = "array"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::Array + R"("}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); ASSERT_TRUE(remoteObject->HasSubType()); @@ -131,19 +130,19 @@ HWTEST_F_L0(DebuggerTypesTest, RemoteObjectCreateTest) // abnormal params of params.sub-key = [ type = "object", className = 100] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","className":100}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of params.sub-key = [ type = "object", className = {"xx":"yy"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","className":{"xx":"yy"}}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // normal params of params.sub-key = [ type = "object", className = "TestClass"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","className":"TestClass"}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); ASSERT_TRUE(remoteObject->HasClassName()); @@ -152,48 +151,40 @@ HWTEST_F_L0(DebuggerTypesTest, RemoteObjectCreateTest) // normal params of params.sub-key = [ type = "object", value = 100] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","value":100}})"; - remoteObject = RemoteObject::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); - ASSERT_TRUE(remoteObject->HasValue()); - EXPECT_EQ(Local(remoteObject->GetValue())->Value(), 100.0); // normal params of params.sub-key = [ type = "object", value = {"xx":"yy"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","value":{"xx":"yy"}}})"; - remoteObject = RemoteObject::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); - ASSERT_TRUE(remoteObject->HasValue()); - ASSERT_TRUE(remoteObject->GetValue()->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "xx"); - ASSERT_TRUE(Local(remoteObject->GetValue())->Has(ecmaVm, Local(tmpStr))); // normal params of params.sub-key = [ type = "object", value = "Test"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","value":"Test"}})"; - remoteObject = RemoteObject::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); - ASSERT_TRUE(remoteObject->HasValue()); - EXPECT_EQ("Test", DebuggerApi::ToStdString(remoteObject->GetValue())); // abnormal params of params.sub-key = [ type = "object", unserializableValue = 100] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","unserializableValue":100}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of params.sub-key = [ type = "object", unserializableValue = {"xx":"yy"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","unserializableValue":{"xx":"yy"}}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // normal params of params.sub-key = [ type = "object", unserializableValue = "TestClass"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","unserializableValue":"Test"}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); ASSERT_TRUE(remoteObject->HasUnserializableValue()); @@ -202,19 +193,19 @@ HWTEST_F_L0(DebuggerTypesTest, RemoteObjectCreateTest) // abnormal params of params.sub-key = [ type = "object", description = 100] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","description":100}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of params.sub-key = [ type = "object", description = {"xx":"yy"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","description":{"xx":"yy"}}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // normal params of params.sub-key = [ type = "object", description = "Test"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","description":"Test"}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); ASSERT_TRUE(remoteObject->HasDescription()); @@ -223,75 +214,25 @@ HWTEST_F_L0(DebuggerTypesTest, RemoteObjectCreateTest) // abnormal params of params.sub-key = [ type = "object", objectId = 100] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","objectId":100}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // abnormal params of params.sub-key = [ type = "object", objectId = {"xx":"yy"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","objectId":{"xx":"yy"}}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(remoteObject, nullptr); // normal params of params.sub-key = [ type = "object", objectId = "id_1"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(","objectId":"1"}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); EXPECT_EQ(ObjectType::Object, remoteObject->GetType()); ASSERT_TRUE(remoteObject->HasObjectId()); EXPECT_EQ(remoteObject->GetObjectId(), 1); } -HWTEST_F_L0(DebuggerTypesTest, RemoteObjectToObjectTest) -{ - std::string msg; - std::unique_ptr remoteObject; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + - R"(", "subtype":")" + ObjectSubType::Array + - R"(","className":"TestClass","value":100, "unserializableValue":"Test","description":"Test","objectId":"1"}})"; - remoteObject = RemoteObject::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(remoteObject, nullptr); - Local object = remoteObject->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Array.c_str()), DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "className"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("TestClass", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "value"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 100.0); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "unserializableValue"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("Test", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "description"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("Test", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "objectId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("1", DebuggerApi::ToStdString(result)); -} - HWTEST_F_L0(DebuggerTypesTest, RemoteObjectToJsonTest) { std::string msg; @@ -302,7 +243,7 @@ HWTEST_F_L0(DebuggerTypesTest, RemoteObjectToJsonTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"type":")" + ObjectType::Object + R"(", "subtype":")" + ObjectSubType::Array + R"(","className":"TestClass","value":100, "unserializableValue":"Test","description":"Test","objectId":"1"}})"; - remoteObject = RemoteObject::Create(DispatchRequest(ecmaVm, msg).GetParams()); + remoteObject = RemoteObject::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(remoteObject, nullptr); auto objJson = remoteObject->ToJson(); @@ -338,76 +279,76 @@ HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = [ exceptionId="Test","text"="text0","lineNumber"=10,"columnNumber"=20] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":"Test","text":"text0","lineNumber":10,"columnNumber":20}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = [ exceptionId={"xx":"yy"},"text"="text0","lineNumber"=10,"columnNumber"=20] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":{"xx":"yy"},"text":"text0","lineNumber":10,"columnNumber":20}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = [ exceptionId=3,"text"=10,"lineNumber"=10,"columnNumber"=20] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":10,"lineNumber":10,"columnNumber":20}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = [ exceptionId=3,"text"=["text0"],"lineNumber"=10,"columnNumber"=20] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":["text0"],"lineNumber":10,"columnNumber":20}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = [ exceptionId=3,"text"="text0","lineNumber"="10","columnNumber"=20] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":"10","columnNumber":20}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = [ exceptionId=3,"text"="text0","lineNumber"=["10"],"columnNumber"=20] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":["10"],"columnNumber":20}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = [ exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"="20"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":"20"}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = [ exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=["20"]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":["20"]}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // normal params of params.sub-key = [ exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(exceptionMetaData, nullptr); EXPECT_EQ(exceptionMetaData->GetExceptionId(), 3); EXPECT_EQ("text0", exceptionMetaData->GetText()); @@ -418,21 +359,21 @@ HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsCreateTest) // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"scriptId"=10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"scriptId":10}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"scriptId"=["10"]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"scriptId":["10"]}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // normal params of params.sub-key = // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"scriptId"="id0"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"scriptId":"0"}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(exceptionMetaData, nullptr); EXPECT_EQ(exceptionMetaData->GetExceptionId(), 3); EXPECT_EQ("text0", exceptionMetaData->GetText()); @@ -444,21 +385,21 @@ HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsCreateTest) // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"url"=10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"url":10}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"url"=["10"]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"url":["10"]}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // normal params of params.sub-key = // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"url"="url0"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"url":"url0"}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(exceptionMetaData, nullptr); EXPECT_EQ(exceptionMetaData->GetExceptionId(), 3); EXPECT_EQ("text0", exceptionMetaData->GetText()); @@ -470,14 +411,14 @@ HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsCreateTest) // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"exception"=10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"exception":10}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"exception"=["10"]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"exception":["10"]}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // normal params of params.sub-key = @@ -485,7 +426,7 @@ HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsCreateTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"exception":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::Error + R"("}}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(exceptionMetaData, nullptr); EXPECT_EQ(exceptionMetaData->GetExceptionId(), 3); EXPECT_EQ("text0", exceptionMetaData->GetText()); @@ -500,21 +441,21 @@ HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsCreateTest) // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"executionContextId"="10"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"executionContextId":"10"}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // abnormal params of params.sub-key = // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"executionContextId"=["10"]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"executionContextId":["10"]}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(exceptionMetaData, nullptr); // normal params of params.sub-key = // [exceptionId=3,"text"="text0","lineNumber"=10,"columnNumber"=20,"executionContextId"=2] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "exceptionId":3,"text":"text0","lineNumber":10,"columnNumber":20,"executionContextId":2}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(exceptionMetaData, nullptr); EXPECT_EQ(exceptionMetaData->GetExceptionId(), 3); EXPECT_EQ("text0", exceptionMetaData->GetText()); @@ -523,72 +464,6 @@ HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsCreateTest) EXPECT_EQ(exceptionMetaData->GetExecutionContextId(), 2); } -HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsToObjectTest) -{ - std::string msg; - std::unique_ptr exceptionMetaData; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "exceptionId":5,"text":"text0","lineNumber":10,"columnNumber":20,"scriptId":"100","url":"url0", - "exception":{"type":")" + - ObjectType::Object + R"(","subtype":")" + ObjectSubType::Error + R"("},"executionContextId":30}})"; - exceptionMetaData = ExceptionDetails::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(exceptionMetaData, nullptr); - Local object = exceptionMetaData->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "exceptionId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 5); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "text"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("text0", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 10); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "columnNumber"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 20); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("100", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "url"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("url0", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "exception"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - Local subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Error.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "executionContextId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 30); -} - HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsToJsonTest) { std::string msg; @@ -602,7 +477,7 @@ HWTEST_F_L0(DebuggerTypesTest, ExceptionDetailsToJsonTest) "exceptionId":5,"text":"text0","lineNumber":10,"columnNumber":20,"scriptId":"100","url":"url0", "exception":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::Error + R"("},"executionContextId":30}})"; - exceptionMetaData = ExceptionDetails::Create(DispatchRequest(ecmaVm, msg).GetParams()); + exceptionMetaData = ExceptionDetails::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(exceptionMetaData, nullptr); auto objJson = exceptionMetaData->ToJson(); @@ -652,79 +527,79 @@ HWTEST_F_L0(DebuggerTypesTest, InternalPropertyDescriptorCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of unknown params.sub-key=["name":"name8"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":99}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of unknown params.sub-key=["name":"name8"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":99}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of unknown params.sub-key=["name":"name8","value":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":99}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of unknown params.sub-key=["name":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":99}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of unknown params.sub-key=["name":[99]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":[99]}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name7"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name7"}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(internalPropertyDescriptor, nullptr); EXPECT_EQ("name7", internalPropertyDescriptor->GetName()); // abnormal params of unknown params.sub-key=["name":"name8","value":{"type":"object","subtype":"map"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":"99"}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // abnormal params of unknown params.sub-key=["name":"name8","value":{"type":"object","subtype":"wrong"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":{"type":")" + ObjectType::Object + R"(","subtype":"wrong"}}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(internalPropertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name8","value":{"type":"object","subtype":"map"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::Map + R"("}}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(internalPropertyDescriptor, nullptr); EXPECT_EQ("name8", internalPropertyDescriptor->GetName()); ASSERT_TRUE(internalPropertyDescriptor->HasValue()); @@ -734,42 +609,6 @@ HWTEST_F_L0(DebuggerTypesTest, InternalPropertyDescriptorCreateTest) EXPECT_EQ(value->GetSubType(), ObjectSubType::Map); } -HWTEST_F_L0(DebuggerTypesTest, InternalPropertyDescriptorToObjectTest) -{ - std::string msg; - std::unique_ptr internalPropertyDescriptor; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "name":"name8","value":{"type":")" + - ObjectType::Object + R"(","subtype":")" + ObjectSubType::Map + R"("}}})"; - internalPropertyDescriptor = - InternalPropertyDescriptor::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(internalPropertyDescriptor, nullptr); - Local object = internalPropertyDescriptor->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "name"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("name8", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "value"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - Local subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Map.c_str()), DebuggerApi::ToStdString(subResult)); -} - HWTEST_F_L0(DebuggerTypesTest, InternalPropertyDescriptorToJsonTest) { std::string msg; @@ -781,7 +620,7 @@ HWTEST_F_L0(DebuggerTypesTest, InternalPropertyDescriptorToJsonTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name8","value":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::Map + R"("}}})"; - internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + internalPropertyDescriptor = InternalPropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(internalPropertyDescriptor, nullptr); auto objJson = internalPropertyDescriptor->ToJson(); @@ -807,77 +646,77 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":10,"configurable":true,"enumerable":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":10,"configurable":true,"enumerable":true,"value":10}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":["name85"],"configurable":true,"enumerable":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":["name85"],"configurable":true,"enumerable":true,"value":10}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":10,"enumerable":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":10,"enumerable":true}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":"true","enumerable":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":"true","enumerable":true}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":10}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":"true"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":"true"}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"value":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"value":10}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"value":{"ee":"11"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"value":{"ee":"11"}}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"value":{..}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"value":{"type":")" + ObjectType::Symbol + R"("}}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(propertyDescriptor, nullptr); EXPECT_EQ("name85", propertyDescriptor->GetName()); ASSERT_TRUE(propertyDescriptor->GetConfigurable()); @@ -889,19 +728,19 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorCreateTest) // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"writable":98] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"writable":98}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"writable":[true]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"writable":[true]}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"writable":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"writable":true}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(propertyDescriptor, nullptr); EXPECT_EQ("name85", propertyDescriptor->GetName()); ASSERT_TRUE(propertyDescriptor->GetConfigurable()); @@ -911,20 +750,20 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorCreateTest) // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"get":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"get":10}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"get":[10]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"get":[10]}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"get":{}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"get":{"type":")" + ObjectType::Function + R"("}}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(propertyDescriptor, nullptr); EXPECT_EQ("name85", propertyDescriptor->GetName()); ASSERT_TRUE(propertyDescriptor->GetConfigurable()); @@ -936,20 +775,20 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorCreateTest) // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"set":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"set":10}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"set":[10]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"set":[10]}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"set":{}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"set":{"type":")" + ObjectType::String + R"("}}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(propertyDescriptor, nullptr); EXPECT_EQ("name85", propertyDescriptor->GetName()); ASSERT_TRUE(propertyDescriptor->GetConfigurable()); @@ -961,19 +800,19 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorCreateTest) // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"wasThrown":98] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"wasThrown":98}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"wasThrown":[true]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"wasThrown":[true]}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"wasThrown":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"wasThrown":true}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(propertyDescriptor, nullptr); EXPECT_EQ("name85", propertyDescriptor->GetName()); ASSERT_TRUE(propertyDescriptor->GetConfigurable()); @@ -983,19 +822,19 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorCreateTest) // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"isOwn":98] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"isOwn":98}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"isOwn":[true]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"isOwn":[true]}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true,"isOwn":true] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"isOwn":true}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(propertyDescriptor, nullptr); EXPECT_EQ("name85", propertyDescriptor->GetName()); ASSERT_TRUE(propertyDescriptor->GetConfigurable()); @@ -1005,20 +844,20 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorCreateTest) // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true, "symbol":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"symbol":10}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // abnormal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true, "symbol":[10]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"symbol":[10]}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(propertyDescriptor, nullptr); // normal params of params.sub-key=["name":"name8","configurable":true,"enumerable":true, "symbol":{}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "name":"name85","configurable":true,"enumerable":true,"symbol":{"type":")" + ObjectType::Wasm + R"("}}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(propertyDescriptor, nullptr); EXPECT_EQ("name85", propertyDescriptor->GetName()); ASSERT_TRUE(propertyDescriptor->GetConfigurable()); @@ -1028,116 +867,6 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorCreateTest) EXPECT_EQ(symbol->GetType(), ObjectType::Wasm); } -HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorToObjectTest) -{ - std::string msg; - std::unique_ptr propertyDescriptor; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "name":"name8","value":{"type":")" + - ObjectType::Object + R"(","subtype":")" + ObjectSubType::Map + R"("}, - "writable":true,"get":{"type":")" + - ObjectType::Object + R"(","subtype":")" + ObjectSubType::Regexp + R"("},"set":{"type":")" + - ObjectType::Object + R"(","subtype":")" + ObjectSubType::Generator + - R"("},"configurable":true,"enumerable":true,"wasThrown":true,"isOwn":true,"symbol":{"type":")" + - ObjectType::Object + R"(","subtype":")" + ObjectSubType::Proxy + R"("}}})"; - propertyDescriptor = PropertyDescriptor::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(propertyDescriptor, nullptr); - Local object = propertyDescriptor->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "name"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("name8", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "value"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - Local subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Map.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "writable"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsTrue()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "get"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Regexp.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "set"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Generator.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "configurable"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsTrue()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "enumerable"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsTrue()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "wasThrown"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsTrue()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "isOwn"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsTrue()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "symbol"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Proxy.c_str()), DebuggerApi::ToStdString(subResult)); -} - HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorToJsonTest) { std::string msg; @@ -1155,7 +884,7 @@ HWTEST_F_L0(DebuggerTypesTest, PropertyDescriptorToJsonTest) ObjectType::Object + R"(","subtype":")" + ObjectSubType::Generator + R"("},"configurable":true,"enumerable":true,"wasThrown":true,"isOwn":true,"symbol":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::Proxy + R"("}}})"; - propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(ecmaVm, msg).GetParams()); + propertyDescriptor = PropertyDescriptor::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(propertyDescriptor, nullptr); auto objJson = propertyDescriptor->ToJson(); @@ -1231,57 +960,57 @@ HWTEST_F_L0(DebuggerTypesTest, LocationCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(location, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(location, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(location, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(location, nullptr); // abnormal params of params.sub-key=["scriptId":10,"lineNumber":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":10,"lineNumber":99 }})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(location, nullptr); // abnormal params of params.sub-key=["scriptId":["id3"],"lineNumber":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":["id3"],"lineNumber":99 }})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(location, nullptr); // abnormal params of params.sub-key=["scriptId":"222","lineNumber":"99"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":"99" }})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(location, nullptr); // abnormal params of params.sub-key=["scriptId":"222","lineNumber":[99]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":[99] }})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(location, nullptr); // normal params of params.sub-key=["scriptId":"2","lineNumber":99,"columnNumber":138] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":899,"columnNumber":138 }})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(location, nullptr); EXPECT_EQ(location->GetScriptId(), 222); EXPECT_EQ(location->GetLine(), 899); @@ -1291,42 +1020,12 @@ HWTEST_F_L0(DebuggerTypesTest, LocationCreateTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"2122","lineNumber":8299 }})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(location, nullptr); EXPECT_EQ(location->GetScriptId(), 2122); EXPECT_EQ(location->GetLine(), 8299); } -HWTEST_F_L0(DebuggerTypesTest, LocationToObjectTest) -{ - std::string msg; - std::unique_ptr location; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "scriptId":"2","lineNumber":99,"columnNumber":18 - }})"; - location = Location::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(location, nullptr); - Local object = location->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("2", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 99); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "columnNumber"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 18); -} - HWTEST_F_L0(DebuggerTypesTest, LocationToJsonTest) { std::string msg; @@ -1338,7 +1037,7 @@ HWTEST_F_L0(DebuggerTypesTest, LocationToJsonTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"2","lineNumber":99,"columnNumber":18 }})"; - location = Location::Create(DispatchRequest(ecmaVm, msg).GetParams()); + location = Location::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(location, nullptr); auto objJson = location->ToJson(); @@ -1362,78 +1061,78 @@ HWTEST_F_L0(DebuggerTypesTest, BreakLocationCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of params.sub-key=["scriptId":10,"lineNumber":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":10,"lineNumber":99 }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of params.sub-key=["scriptId":["id3"],"lineNumber":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":["id3"],"lineNumber":99 }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of params.sub-key=["scriptId":"222","lineNumber":"99"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":"99" }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of params.sub-key=["scriptId":"222","lineNumber":[99]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":[99] }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of params.sub-key=["scriptId":"2","lineNumber":99,"columnNumber":"18"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":899,"columnNumber":"18" }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of params.sub-key=["scriptId":"2","lineNumber":99,"columnNumber":"18","type":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":899,"columnNumber":"18","type":10 }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // abnormal params of params.sub-key=["scriptId":"2","lineNumber":99,"columnNumber":"18","type":"ee"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":899,"columnNumber":"18","type":"ee" }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(breakLocation, nullptr); // normal params of params.sub-key=["scriptId":"2","lineNumber":99,"columnNumber":138,"type":"return"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"222","lineNumber":899,"columnNumber":138,"type":"return" }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(breakLocation, nullptr); EXPECT_EQ(breakLocation->GetScriptId(), 222); EXPECT_EQ(breakLocation->GetLine(), 899); @@ -1444,47 +1143,12 @@ HWTEST_F_L0(DebuggerTypesTest, BreakLocationCreateTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"2122","lineNumber":8299 }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(breakLocation, nullptr); EXPECT_EQ(breakLocation->GetScriptId(), 2122); EXPECT_EQ(breakLocation->GetLine(), 8299); } -HWTEST_F_L0(DebuggerTypesTest, BreakLocationToObjectTest) -{ - std::string msg; - std::unique_ptr breakLocation; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "scriptId":"12","lineNumber":919,"columnNumber":148,"type":"call" - }})"; - breakLocation = BreakLocation::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(breakLocation, nullptr); - Local object = breakLocation->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("12", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 919); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "columnNumber"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 148); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("call", DebuggerApi::ToStdString(result)); -} - HWTEST_F_L0(DebuggerTypesTest, BreakLocationToJsonTest) { std::string msg; @@ -1496,7 +1160,7 @@ HWTEST_F_L0(DebuggerTypesTest, BreakLocationToJsonTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "scriptId":"12","lineNumber":919,"columnNumber":148,"type":"call" }})"; - breakLocation = BreakLocation::Create(DispatchRequest(ecmaVm, msg).GetParams()); + breakLocation = BreakLocation::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(breakLocation, nullptr); auto objJson = breakLocation->ToJson(); @@ -1524,70 +1188,70 @@ HWTEST_F_L0(DebuggerTypesTest, ScopeCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":"ss","object":{..}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"ss","object":{"type":")" + ObjectType::Bigint + R"("}}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":12,"object":{..}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":12,"object":{"type":")" + ObjectType::Bigint + R"("}}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":"global","object":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":10}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":"global","object":{..}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"ww":")" + ObjectType::Bigint + R"("}}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":"global","object":{..},"name":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"type":")" + ObjectType::Bigint + R"("},"name":10}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":"global","object":{..},"name":["10"]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"type":")" + ObjectType::Bigint + R"("},"name":["10"]}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // normal params of params.sub-key=["type":"global","object":{..},"name":"name128"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"type":")" + ObjectType::Bigint + R"("},"name":"name117"}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(scope, nullptr); EXPECT_EQ("name117", scope->GetName()); @@ -1595,35 +1259,35 @@ HWTEST_F_L0(DebuggerTypesTest, ScopeCreateTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"type":")" + ObjectType::Bigint + R"("},"startLocation":10}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":"global","object":{..},"startLocation":{"12":"34"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"type":")" + ObjectType::Bigint + R"("},"startLocation":{"12":"34"}}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":"global","object":{..},"endLocation":10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"type":")" + ObjectType::Bigint + R"("},"endLocation":10}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // abnormal params of params.sub-key=["type":"global","object":{..},"endLocation":{"12":"34"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"type":")" + ObjectType::Bigint + R"("},"endLocation":{"12":"34"}}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scope, nullptr); // normal params of params.sub-key=["type":"global","object":{..}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "type":"global","object":{"type":")" + ObjectType::Bigint + R"("}}})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(scope, nullptr); EXPECT_EQ("global", scope->GetType()); RemoteObject *object = scope->GetObject(); @@ -1631,79 +1295,6 @@ HWTEST_F_L0(DebuggerTypesTest, ScopeCreateTest) EXPECT_EQ(object->GetType(), ObjectType::Bigint); } -HWTEST_F_L0(DebuggerTypesTest, ScopeToObjectTest) -{ - std::string msg; - std::unique_ptr scope; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "type":"global","object":{"type":")" + - ObjectType::Object + R"(","subtype":")" + ObjectSubType::Dataview + R"("},"name":"name9", - "startLocation":{"scriptId":"2","lineNumber":99}, - "endLocation":{"scriptId":"13","lineNumber":146} - }})"; - scope = Scope::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(scope, nullptr); - Local object = scope->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("global", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "object"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - Local subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Dataview.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "name"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("name9", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "startLocation"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ("2", DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(Local(subResult)->Value(), 99); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "endLocation"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ("13", DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(Local(subResult)->Value(), 146); -} - HWTEST_F_L0(DebuggerTypesTest, ScopeToJsonTest) { std::string msg; @@ -1719,7 +1310,7 @@ HWTEST_F_L0(DebuggerTypesTest, ScopeToJsonTest) "startLocation":{"scriptId":"2","lineNumber":99}, "endLocation":{"scriptId":"13","lineNumber":146} }})"; - scope = Scope::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scope = Scope::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(scope, nullptr); auto objJson = scope->ToJson(); @@ -1769,22 +1360,22 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1794,7 +1385,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1804,7 +1395,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1814,7 +1405,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1824,7 +1415,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1834,7 +1425,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1844,7 +1435,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1854,7 +1445,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1864,7 +1455,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1874,7 +1465,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1884,7 +1475,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1892,7 +1483,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) "callFrameId":"0","functionName":"name0", "location":{"scriptId":"5","lineNumber":19}, "url":"url7","scopeChain":10,"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1902,7 +1493,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) {"type":"22","object":{"type":")" + ObjectType::Object + R"("}},"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1912,7 +1503,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":10}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1922,7 +1513,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"11":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1933,7 +1524,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}, "returnValue":10}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // abnormal params of params.sub-key=[..] @@ -1944,7 +1535,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}, "returnValue":{"type":"object","subtype":"11"}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(callFrame, nullptr); // normal params of params.sub-key=[..] @@ -1954,7 +1545,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) [{"type":"global","object":{"type":")" + ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(callFrame, nullptr); EXPECT_EQ(callFrame->GetCallFrameId(), 0); EXPECT_EQ("name0", callFrame->GetFunctionName()); @@ -1979,7 +1570,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::V128 + R"("},"returnValue":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::I32 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(callFrame, nullptr); EXPECT_EQ(callFrame->GetCallFrameId(), 10); EXPECT_EQ("name0", callFrame->GetFunctionName()); @@ -2002,107 +1593,6 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameCreateTest) EXPECT_EQ(returnObj->GetSubType(), ObjectSubType::I32); } -HWTEST_F_L0(DebuggerTypesTest, CallFrameToObjectTest) -{ - std::string msg; - std::unique_ptr callFrame; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "callFrameId":"0","functionName":"name0","functionLocation":{"scriptId":"3","lineNumber":16}, - "location":{"scriptId":"5","lineNumber":19},"url":"url7","scopeChain": - [{"type":"global","object":{"type":")" + - ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + - R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::Iterator + - R"("},"returnValue":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::I64 + R"("}}})"; - callFrame = CallFrame::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(callFrame, nullptr); - Local object = callFrame->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "callFrameId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("0", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "functionName"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("name0", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "functionLocation"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - Local subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ("3", DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(Local(subResult)->Value(), 16); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "location"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ("5", DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(Local(subResult)->Value(), 19); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "url"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ("url7", DebuggerApi::ToStdString(result)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scopeChain"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsArray(ecmaVm)); - - EXPECT_EQ(Local(result)->Length(ecmaVm), 2); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "this"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::Iterator.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "returnValue"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsObject()); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "type"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectType::Object.c_str()), DebuggerApi::ToStdString(subResult)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "subtype"); - ASSERT_TRUE(Local(result)->Has(ecmaVm, Local(tmpStr))); - subResult = Local(result)->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(std::string(ObjectSubType::I64.c_str()), DebuggerApi::ToStdString(subResult)); -} - HWTEST_F_L0(DebuggerTypesTest, CallFrameToJsonTest) { std::string msg; @@ -2119,7 +1609,7 @@ HWTEST_F_L0(DebuggerTypesTest, CallFrameToJsonTest) ObjectType::Object + R"("}}, {"type":"local","object":{"type":")" + ObjectType::Object + R"("}}],"this":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::Iterator + R"("},"returnValue":{"type":")" + ObjectType::Object + R"(","subtype":")" + ObjectSubType::I64 + R"("}}})"; - callFrame = CallFrame::Create(DispatchRequest(ecmaVm, msg).GetParams()); + callFrame = CallFrame::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(callFrame, nullptr); auto objJson = callFrame->ToJson(); @@ -2188,76 +1678,45 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileSampleCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileSample::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileSample::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileSample::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileSample::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of params.sub-key = [ "size"="Test","nodeId"="Test","ordinal"="Test"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "size":"Test","nodeId":"Test","ordinal":"Test"}})"; - object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileSample::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of params.sub-key = [ "size"={"xx":"yy"},"nodeId"={"xx":"yy"},"ordinal"={"xx":"yy"}] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "size":{"xx":"yy"},"nodeId":{"xx":"yy"},"ordinal":{"xx":"yy"}}})"; - object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileSample::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of params.sub-key = [ "size"=100,"nodeId"=1,"ordinal"=10] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"size":100,"nodeId":1,"ordinal":10}})"; - object = SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileSample::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(object, nullptr); EXPECT_EQ(object->GetSize(), 100); EXPECT_EQ(object->GetNodeId(), 1); EXPECT_EQ(object->GetOrdinal(), 10); } -HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileSampleToObjectTest) -{ - std::string msg; - std::unique_ptr samplingHeapProfileSampleData; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"size":100,"nodeId":1,"ordinal":10}})"; - samplingHeapProfileSampleData = - SamplingHeapProfileSample::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(samplingHeapProfileSampleData, nullptr); - Local object = samplingHeapProfileSampleData->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "size"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 100); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "nodeId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 1); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "ordinal"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 10); -} - HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileSampleToJsonTest) { std::string msg; @@ -2268,7 +1727,7 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileSampleToJsonTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"size":100,"nodeId":1,"ordinal":10}})"; samplingHeapProfileSampleData = - SamplingHeapProfileSample::Create(DispatchRequest(ecmaVm, msg).GetParams()); + SamplingHeapProfileSample::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(samplingHeapProfileSampleData, nullptr); auto json = samplingHeapProfileSampleData->ToJson(); @@ -2290,22 +1749,22 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileNode::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileNode::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileNode::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileNode::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ @@ -2314,7 +1773,7 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeCreateTest) "id":5, "children":[] }})"; - object = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfileNode::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(object, nullptr); RuntimeCallFrame *runTimeCallFrame = object->GetCallFrame(); ASSERT_NE(runTimeCallFrame, nullptr); @@ -2331,62 +1790,6 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeCreateTest) EXPECT_EQ((int)children->size(), 0); } -HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeToObjectTest) -{ - std::string msg; - std::unique_ptr samplingHeapProfileNode; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "callFrame": {"functionName":"Create", "scriptId":"10", "url":"url3", "lineNumber":100, "columnNumber":20}, - "selfSize":10, - "id":5, - "children":[] - }})"; - samplingHeapProfileNode = SamplingHeapProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(samplingHeapProfileNode, nullptr); - Local object = samplingHeapProfileNode->ToObject(ecmaVm); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "callFrame"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - - Local subObject = samplingHeapProfileNode->GetCallFrame()->ToObject(ecmaVm); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "functionName"); - ASSERT_TRUE(subObject->Has(ecmaVm, tmpStr)); - Local subResult = subObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(subResult), "Create"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(subObject->Has(ecmaVm, tmpStr)); - subResult = subObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(subResult), "10"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "url"); - ASSERT_TRUE(subObject->Has(ecmaVm, tmpStr)); - subResult = subObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(subResult), "url3"); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "selfSize"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 10); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "id"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 5); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "children"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsArray(ecmaVm)); -} - HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeToJsonTest) { std::string msg; @@ -2402,7 +1805,7 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileNodeToJsonTest) "id":5, "children":[] }})"; - samplingHeapProfileNode = SamplingHeapProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + samplingHeapProfileNode = SamplingHeapProfileNode::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(samplingHeapProfileNode, nullptr); auto json = samplingHeapProfileNode->ToJson(); @@ -2438,22 +1841,22 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfile::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfile::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfile::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfile::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(object, nullptr); msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ @@ -2465,7 +1868,7 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileCreateTest) }, "samples":[{"size":100, "nodeId":1, "ordinal":10}] }})"; - object = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + object = SamplingHeapProfile::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(object, nullptr); SamplingHeapProfileNode *head = object->GetHead(); ASSERT_NE(head, nullptr); @@ -2492,98 +1895,6 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileCreateTest) EXPECT_EQ(samples->data()->get()->GetOrdinal(), 10); } -HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileToObjectTest) -{ - std::string msg; - std::unique_ptr samplingHeapProfile; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "head": { - "callFrame": {"functionName":"Create", "scriptId":"10", "url":"url3", "lineNumber":100, "columnNumber":20}, - "selfSize":10, - "id":5, - "children":[] - }, - "samples":[{"size":100, "nodeId":1, "ordinal":10}] - }})"; - - samplingHeapProfile = SamplingHeapProfile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(samplingHeapProfile, nullptr); - Local object = samplingHeapProfile->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "head"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - - Local headObject = samplingHeapProfile->GetHead()->ToObject(ecmaVm); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "callFrame"); - ASSERT_TRUE(headObject->Has(ecmaVm, tmpStr)); - result = headObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - - Local callFrameObject = samplingHeapProfile->GetHead()->GetCallFrame()->ToObject(ecmaVm); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "functionName"); - ASSERT_TRUE(callFrameObject->Has(ecmaVm, tmpStr)); - Local subResult = callFrameObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(subResult), "Create"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(callFrameObject->Has(ecmaVm, tmpStr)); - subResult = callFrameObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(subResult), "10"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "url"); - ASSERT_TRUE(callFrameObject->Has(ecmaVm, tmpStr)); - subResult = callFrameObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!subResult.IsEmpty() && !subResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(subResult), "url3"); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "selfSize"); - ASSERT_TRUE(headObject->Has(ecmaVm, tmpStr)); - result = headObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 10); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "id"); - ASSERT_TRUE(headObject->Has(ecmaVm, tmpStr)); - result = headObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 5); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "children"); - ASSERT_TRUE(headObject->Has(ecmaVm, tmpStr)); - result = headObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsArray(ecmaVm)); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "samples"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsArray(ecmaVm)); - - Local samplesObject = samplingHeapProfile->GetSamples()->data()->get()->ToObject(ecmaVm); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "size"); - ASSERT_TRUE(samplesObject->Has(ecmaVm, tmpStr)); - result = samplesObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 100); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "nodeId"); - ASSERT_TRUE(samplesObject->Has(ecmaVm, tmpStr)); - result = samplesObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 1); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "ordinal"); - ASSERT_TRUE(samplesObject->Has(ecmaVm, tmpStr)); - result = samplesObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 10); -} - HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileToJsonTest) { std::string msg; @@ -2605,7 +1916,7 @@ HWTEST_F_L0(DebuggerTypesTest, SamplingHeapProfileToJsonTest) "samples":[{"size":100, "nodeId":1, "ordinal":10}] }})"; - samplingHeapProfile = SamplingHeapProfile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + samplingHeapProfile = SamplingHeapProfile::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(samplingHeapProfile, nullptr); auto json = samplingHeapProfile->ToJson(); @@ -2649,75 +1960,50 @@ HWTEST_F_L0(DebuggerTypesTest, PositionTickInfoCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of params.sub-key=["line":11,"ticks":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "line":"11","ticks":99}})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of params.sub-key=["line":"11","ticks":"99"] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "line":"11","ticks":"99"}})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // abnormal params of params.sub-key=["line":[11],"ticks":[99]] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "line":[11],"ticks":[99]}})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(positionTickInfo, nullptr); // normal params of params.sub-key=["line":11,"ticks":99] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"line":1,"ticks":0}})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(positionTickInfo, nullptr); EXPECT_EQ(positionTickInfo->GetLine(), 1); EXPECT_EQ(positionTickInfo->GetTicks(), 0); } - -HWTEST_F_L0(DebuggerTypesTest, PositionTickInfoToObjectTest) -{ - std::string msg; - std::unique_ptr positionTickInfo; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"line":1,"ticks":0}})"; - positionTickInfo = PositionTickInfo::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(positionTickInfo, nullptr); - Local object = positionTickInfo->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "line"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 1); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "ticks"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 0); -} - HWTEST_F_L0(DebuggerTypesTest, PositionTickInfoToJsonTest) { std::string msg; @@ -2726,7 +2012,7 @@ HWTEST_F_L0(DebuggerTypesTest, PositionTickInfoToJsonTest) Result ret; msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"line":1,"ticks":0}})"; - positionTickInfo = PositionTickInfo::Create(DispatchRequest(ecmaVm, msg).GetParams()); + positionTickInfo = PositionTickInfo::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(positionTickInfo, nullptr); auto json = positionTickInfo->ToJson(); @@ -2746,22 +2032,22 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileNodeCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profileNode = ProfileNode::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(profileNode, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profileNode = ProfileNode::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(profileNode, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profileNode = ProfileNode::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(profileNode, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profileNode = ProfileNode::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(profileNode, nullptr); // normal params of params.sub-key=[..] @@ -2769,7 +2055,7 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileNodeCreateTest) "id":10, "callFrame": {"functionName":"name0", "scriptId":"12", "url":"url15", "lineNumber":11, "columnNumber":20}, "hitCount":15,"children":[],"positionTicks":[],"deoptReason":"yyy"}})"; - profileNode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profileNode = ProfileNode::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(profileNode, nullptr); EXPECT_EQ(profileNode->GetId(), 10); @@ -2785,71 +2071,6 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileNodeCreateTest) EXPECT_EQ(profileNode->GetDeoptReason(), "yyy"); } -HWTEST_F_L0(DebuggerTypesTest, ProfileNodeToObjectTest) -{ - std::string msg; - std::unique_ptr profilenode; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "id":10, - "callFrame": {"functionName":"name0", "scriptId":"12", "url":"url15", "lineNumber":11, "columnNumber":20}, - "hitCount":15,"children":[],"positionTicks":[],"deoptReason":"yyy"}})"; - profilenode = ProfileNode::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(profilenode, nullptr); - Local object = profilenode->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "id"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 10); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "callFrame"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - - Local tmpObject = profilenode->GetCallFrame()->ToObject(ecmaVm); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "functionName"); - ASSERT_TRUE(tmpObject->Has(ecmaVm, tmpStr)); - Local tmpResult = tmpObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!tmpResult.IsEmpty() && !tmpResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(tmpResult), "name0"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(tmpObject->Has(ecmaVm, tmpStr)); - tmpResult = tmpObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!tmpResult.IsEmpty() && !tmpResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(tmpResult), "12"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "url"); - ASSERT_TRUE(tmpObject->Has(ecmaVm, tmpStr)); - tmpResult = tmpObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!tmpResult.IsEmpty() && !tmpResult->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(tmpResult), "url15"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "lineNumber"); - ASSERT_TRUE(tmpObject->Has(ecmaVm, tmpStr)); - tmpResult = tmpObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!tmpResult.IsEmpty() && !tmpResult->IsUndefined()); - EXPECT_EQ(Local(tmpResult)->Value(), 11); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "columnNumber"); - ASSERT_TRUE(tmpObject->Has(ecmaVm, tmpStr)); - tmpResult = tmpObject->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!tmpResult.IsEmpty() && !tmpResult->IsUndefined()); - EXPECT_EQ(Local(tmpResult)->Value(), 20); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "hitCount"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 15); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "deoptReason"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "yyy"); -} - HWTEST_F_L0(DebuggerTypesTest, ProfileNodeToJsonTest) { std::string msg; @@ -2863,7 +2084,7 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileNodeToJsonTest) "id":10, "callFrame": {"functionName":"name0", "scriptId":"12", "url":"url15", "lineNumber":11, "columnNumber":20}, "hitCount":15,"children":[],"positionTicks":[],"deoptReason":"yyy"}})"; - profilenode = ProfileNode::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profilenode = ProfileNode::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(profilenode, nullptr); auto json = profilenode->ToJson(); @@ -2906,22 +2127,22 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profile = Profile::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(profile, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profile = Profile::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(profile, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profile = Profile::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(profile, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profile = Profile::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(profile, nullptr); // abnormal params of params.sub-key=[..] @@ -2929,7 +2150,7 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileCreateTest) "startTime":10, "endTime":25, "nodes":[{"id":12, "callFrame": {"functionName":"Create", "scriptId":"10", "url":"url3", "lineNumber":100, "columnNumber":20}}], "samples":[],"timeDeltas":[]}})"; - profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profile = Profile::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(profile, nullptr); EXPECT_EQ(profile->GetStartTime(), 10LL); @@ -2939,36 +2160,6 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileCreateTest) EXPECT_EQ((int)profileNode->size(), 1); } -HWTEST_F_L0(DebuggerTypesTest, ProfileToObjectTest) -{ - std::string msg; - std::unique_ptr profile; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "startTime":10,"endTime":25,"nodes":[],"samples":[],"timeDeltas":[]}})"; - profile = Profile::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(profile, nullptr); - Local object = profile->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "startTime"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 10); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "endTime"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 25); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "nodes"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsArray(ecmaVm)); -} - HWTEST_F_L0(DebuggerTypesTest, ProfileToJsonTest) { std::string msg; @@ -2982,7 +2173,7 @@ HWTEST_F_L0(DebuggerTypesTest, ProfileToJsonTest) "startTime":10, "endTime":25, "nodes":[{"id":12, "callFrame": {"functionName":"Create", "scriptId":"10", "url":"url3", "lineNumber":100, "columnNumber":20}}], "samples":[],"timeDeltas":[]}})"; - profile = Profile::Create(DispatchRequest(ecmaVm, msg).GetParams()); + profile = Profile::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(profile, nullptr); auto json = profile->ToJson(); @@ -3002,66 +2193,34 @@ HWTEST_F_L0(DebuggerTypesTest, CoverageCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + coverage = Coverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(coverage, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + coverage = Coverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(coverage, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + coverage = Coverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(coverage, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + coverage = Coverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(coverage, nullptr); // normal params of params.sub-key=["startOffset":0,"endOffset":5,"count":13] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "startOffset":0,"endOffset":13,"count":13}})"; - coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + coverage = Coverage::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(coverage, nullptr); EXPECT_EQ(coverage->GetStartOffset(), 0); EXPECT_EQ(coverage->GetEndOffset(), 13); EXPECT_EQ(coverage->GetCount(), 13); } -HWTEST_F_L0(DebuggerTypesTest, CoverageToObjectTest) -{ - std::string msg; - std::unique_ptr coverage; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "startOffset":0,"endOffset":13,"count":13}})"; - coverage = Coverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(coverage, nullptr); - Local object = coverage->ToObject(ecmaVm); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "startOffset"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 0); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "endOffset"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 13); - - tmpStr = StringRef::NewFromUtf8(ecmaVm, "count"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(Local(result)->Value(), 13); -} - HWTEST_F_L0(DebuggerTypesTest, CoverageToJsonTest) { std::string msg; @@ -3072,7 +2231,7 @@ HWTEST_F_L0(DebuggerTypesTest, CoverageToJsonTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "startOffset":0,"endOffset":13,"count":13}})"; - coverage = Coverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + coverage = Coverage::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(coverage, nullptr); auto json = coverage->ToJson(); @@ -3096,28 +2255,28 @@ HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(functionCoverage, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(functionCoverage, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(functionCoverage, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(functionCoverage, nullptr); // normal params of params.sub-key=[..] msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "functionName":"Create0","ranges":[{"startOffset":0,"endOffset":13,"count":13}],"isBlockCoverage":true}})"; - functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(functionCoverage, nullptr); EXPECT_EQ(functionCoverage->GetFunctionName(), "Create0"); @@ -3127,35 +2286,6 @@ HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageCreateTest) ASSERT_TRUE(functionCoverage->GetIsBlockCoverage()); } -HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageToObjectTest) -{ - std::string msg; - std::unique_ptr functionCoverage; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "functionName":"Create0","ranges":[],"isBlockCoverage":true}})"; - functionCoverage = FunctionCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(functionCoverage, nullptr); - Local object = functionCoverage->ToObject(ecmaVm); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "functionName"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "Create0"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "ranges"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsArray(ecmaVm)); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "isBlockCoverage"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsTrue()); -} - HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageToJsonTest) { std::string msg; @@ -3167,7 +2297,7 @@ HWTEST_F_L0(DebuggerTypesTest, FunctionCoverageToJsonTest) msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ "functionName":"Create0","ranges":[{"startOffset":0,"endOffset":13,"count":13}],"isBlockCoverage":true}})"; - functionCoverage = FunctionCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + functionCoverage = FunctionCoverage::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(functionCoverage, nullptr); auto json = functionCoverage->ToJson(); @@ -3192,22 +2322,22 @@ HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageCreateTest) // abnormal params of null msg msg = std::string() + R"({})"; - scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scriptCoverage, nullptr); // abnormal params of unexist key params msg = std::string() + R"({"id":0,"method":"Debugger.Test"})"; - scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scriptCoverage, nullptr); // abnormal params of null params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{}})"; - scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scriptCoverage, nullptr); // abnormal params of unknown params.sub-key msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{"unknownKey":100}})"; - scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(msg).GetParams()); EXPECT_EQ(scriptCoverage, nullptr); // normal params of params.sub-key=[..] @@ -3217,7 +2347,7 @@ HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageCreateTest) "functions":[{"functionName":"Create0", "ranges":[{"startOffset":0, "endOffset":13, "count":13}], "isBlockCoverage":true}]}})"; - scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(scriptCoverage, nullptr); EXPECT_EQ(scriptCoverage->GetScriptId(), "1001"); EXPECT_EQ(scriptCoverage->GetUrl(), "url17"); @@ -3226,35 +2356,6 @@ HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageCreateTest) EXPECT_EQ((int)functions->size(), 1); } -HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageToObjectTest) -{ - std::string msg; - std::unique_ptr scriptCoverage; - Local tmpStr; - - msg = std::string() + R"({"id":0,"method":"Debugger.Test","params":{ - "scriptId":"1001","url":"url17","functions":[]}})"; - scriptCoverage = ScriptCoverage::Create(ecmaVm, DispatchRequest(ecmaVm, msg).GetParamsObj()); - ASSERT_NE(scriptCoverage, nullptr); - Local object = scriptCoverage->ToObject(ecmaVm); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "scriptId"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - Local result = object->Get(ecmaVm, tmpStr); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "1001"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "url"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - EXPECT_EQ(DebuggerApi::ToStdString(result), "url17"); - tmpStr = StringRef::NewFromUtf8(ecmaVm, "functions"); - ASSERT_TRUE(object->Has(ecmaVm, tmpStr)); - result = object->Get(ecmaVm, tmpStr); - ASSERT_TRUE(!result.IsEmpty() && !result->IsUndefined()); - ASSERT_TRUE(result->IsArray(ecmaVm)); -} - HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageToJsonTest) { std::string msg; @@ -3269,7 +2370,7 @@ HWTEST_F_L0(DebuggerTypesTest, ScriptCoverageToJsonTest) "functions": [{"functionName":"Create0", "ranges": [{"startOffset":0, "endOffset":13, "count":13}], "isBlockCoverage":true}]}})"; - scriptCoverage = ScriptCoverage::Create(DispatchRequest(ecmaVm, msg).GetParams()); + scriptCoverage = ScriptCoverage::Create(DispatchRequest(msg).GetParams()); ASSERT_NE(scriptCoverage, nullptr); auto json = scriptCoverage->ToJson(); -- Gitee From 89eb58c02a5b2b7e76bc065e93bf5749c4454604 Mon Sep 17 00:00:00 2001 From: zhangyukun8 Date: Thu, 16 Jun 2022 20:58:44 +0800 Subject: [PATCH 025/154] Throw exception when setter is undefined 1. stobjbyname should throw exception when setter and getter are not both defined Issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CO8F?from=project-issue Signed-off-by: zhangyukun8 Change-Id: I7a2c0c682d45027e70ea7b489d590fa990e49414 --- ecmascript/compiler/stub.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ecmascript/compiler/stub.cpp b/ecmascript/compiler/stub.cpp index 59d8a32c..ab8b6030 100644 --- a/ecmascript/compiler/stub.cpp +++ b/ecmascript/compiler/stub.cpp @@ -615,10 +615,10 @@ GateRef Stub::CallSetterHelper(GateRef glue, GateRef receiver, GateRef accessor, Label objIsUndefined(env); Label objNotUndefined(env); Branch(TaggedIsUndefined(setter), &objIsUndefined, &objNotUndefined); - // if getter is undefined, return undefiend Bind(&objIsUndefined); { - result = Undefined(); + CallRuntime(glue, RTSTUB_ID(ThrowSetterIsUndefinedException), {}); + result = Exception(); Jump(&exit); } Bind(&objNotUndefined); -- Gitee From 2282558cbca16dee71437cfd7b5631f56e0e49f9 Mon Sep 17 00:00:00 2001 From: huangfeijie Date: Thu, 9 Jun 2022 10:30:54 +0800 Subject: [PATCH 026/154] modify the SendReply interface in debugger 1.add the vm so that it can get the inspector in socket issue: https://gitee.com/openharmony/ark_js_runtime/issues/I5BG4Z Signed-off-by: huangfeijie --- ecmascript/tooling/debugger_service.cpp | 3 ++- ecmascript/tooling/debugger_service.h | 2 +- ecmascript/tooling/protocol_handler.cpp | 2 +- ecmascript/tooling/protocol_handler.h | 4 ++-- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/ecmascript/tooling/debugger_service.cpp b/ecmascript/tooling/debugger_service.cpp index 1e91a31d..68433e49 100644 --- a/ecmascript/tooling/debugger_service.cpp +++ b/ecmascript/tooling/debugger_service.cpp @@ -19,7 +19,8 @@ #include "ecmascript/tooling/interface/js_debugger_manager.h" namespace panda::ecmascript::tooling { -void InitializeDebugger(const std::function &onResponse, ::panda::ecmascript::EcmaVM *vm) +void InitializeDebugger(const std::function &onResponse, + ::panda::ecmascript::EcmaVM *vm) { ProtocolHandler *handler = vm->GetJsDebuggerManager()->GetDebuggerHandler(); if (handler != nullptr) { diff --git a/ecmascript/tooling/debugger_service.h b/ecmascript/tooling/debugger_service.h index 598614fb..6cbe757b 100644 --- a/ecmascript/tooling/debugger_service.h +++ b/ecmascript/tooling/debugger_service.h @@ -32,7 +32,7 @@ extern "C" { #endif #endif /* End of #ifdef __cplusplus */ -PUBLIC_API void InitializeDebugger(const std::function &on_response, +PUBLIC_API void InitializeDebugger(const std::function &on_response, ::panda::ecmascript::EcmaVM *vm); PUBLIC_API void UninitializeDebugger(::panda::ecmascript::EcmaVM *vm); diff --git a/ecmascript/tooling/protocol_handler.cpp b/ecmascript/tooling/protocol_handler.cpp index be0597a3..e35073d6 100644 --- a/ecmascript/tooling/protocol_handler.cpp +++ b/ecmascript/tooling/protocol_handler.cpp @@ -74,7 +74,7 @@ void ProtocolHandler::SendReply(const PtJson &reply) return; } - callback_(str); + callback_(reinterpret_cast(vm_), str); } std::unique_ptr ProtocolHandler::CreateErrorReply(const DispatchResponse &response) diff --git a/ecmascript/tooling/protocol_handler.h b/ecmascript/tooling/protocol_handler.h index 08b44e89..027b21e3 100644 --- a/ecmascript/tooling/protocol_handler.h +++ b/ecmascript/tooling/protocol_handler.h @@ -25,7 +25,7 @@ namespace panda::ecmascript::tooling { class ProtocolHandler final : public ProtocolChannel { public: - ProtocolHandler(std::function callback, const EcmaVM *vm) + ProtocolHandler(std::function callback, const EcmaVM *vm) : callback_(std::move(callback)), dispatcher_(vm, this), vm_(vm) {} ~ProtocolHandler() override = default; @@ -42,7 +42,7 @@ private: std::unique_ptr CreateErrorReply(const DispatchResponse &response); void SendReply(const PtJson &reply); - std::function callback_; + std::function callback_; Dispatcher dispatcher_; bool waitingForDebugger_ {false}; -- Gitee From bf6cffa180c4550c22d9822f1b28b6fb66c97ef7 Mon Sep 17 00:00:00 2001 From: lichenshuai Date: Thu, 16 Jun 2022 16:01:09 +0800 Subject: [PATCH 027/154] Fix Asm x64 262 Bug 1 1. Fix haveNewTarget in PushCallThis. 2. Dispatch to JSProxy::ConstructInternal when func is proxy in JSFunction::Construct. 3. Rebuild runtimeCallInfo in JSProxy::CallInternal to match future return. 4. ReturnIfAbrupt in JSProxy::OwnPropertyKeys to match ECMA 262 standard. Issue: #I5CMA1 Signed-off-by: lichenshuai Change-Id: Ie6eca69fb217974cd14df88c20169ad66df1047d --- .../compiler/trampoline/aarch64/assembler_stubs.cpp | 2 +- .../compiler/trampoline/x64/assembler_stubs_x64.cpp | 2 +- ecmascript/js_function.cpp | 9 ++++++++- ecmascript/js_proxy.cpp | 13 ++++++++----- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp b/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp index 9e9728ae..df7b4407 100644 --- a/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp +++ b/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp @@ -1433,7 +1433,7 @@ void AssemblerStubs::PushCallThis(ExtendedAssembler *assembler, JSCallMode mode) Label pushNewTarget; Label pushCallTarget; bool haveThis = kungfu::AssemblerModule::JSModeHaveThisArg(mode); - bool haveNewTarget = kungfu::AssemblerModule::JSModeHaveThisArg(mode); + bool haveNewTarget = kungfu::AssemblerModule::JSModeHaveNewTargetArg(mode); if (!haveThis) { __ Tst(callFieldRegister, LogicalImmediate::Create(CALL_TYPE_MASK, RegXSize)); __ B(Condition::EQ, &pushVregs); diff --git a/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp b/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp index a604b8e5..9c558506 100644 --- a/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp +++ b/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp @@ -1551,7 +1551,7 @@ void AssemblerStubsX64::PushCallThis(ExtendedAssembler *assembler, Label pushNewTarget; Label pushCallTarget; bool haveThis = kungfu::AssemblerModule::JSModeHaveThisArg(mode); - bool haveNewTarget = kungfu::AssemblerModule::JSModeHaveThisArg(mode); + bool haveNewTarget = kungfu::AssemblerModule::JSModeHaveNewTargetArg(mode); if (!haveThis) { __ Testb(CALL_TYPE_MASK, callFieldRegister); __ Jz(&pushVregs); diff --git a/ecmascript/js_function.cpp b/ecmascript/js_function.cpp index 402a8600..82e7a581 100644 --- a/ecmascript/js_function.cpp +++ b/ecmascript/js_function.cpp @@ -287,7 +287,14 @@ JSTaggedValue JSFunction::Construct(EcmaRuntimeCallInfo *info) THROW_TYPE_ERROR_AND_RETURN(thread, "Constructor is false", JSTaggedValue::Exception()); } - return JSFunction::ConstructInternal(info); + if (func->IsJSFunction()) { + return JSFunction::ConstructInternal(info); + } else if (func->IsJSProxy()) { + return JSProxy::ConstructInternal(info); + } else { + ASSERT(func->IsBoundFunction()); + return JSBoundFunction::ConstructInternal(info); + } } JSTaggedValue JSFunction::Invoke(EcmaRuntimeCallInfo *info, const JSHandle &key) diff --git a/ecmascript/js_proxy.cpp b/ecmascript/js_proxy.cpp index 87328e9f..a0935d67 100644 --- a/ecmascript/js_proxy.cpp +++ b/ecmascript/js_proxy.cpp @@ -731,6 +731,7 @@ JSHandle JSProxy::OwnPropertyKeys(JSThread *thread, const JSHandle< EcmaRuntimeCallInfo info = EcmaInterpreter::NewRuntimeCallInfo(thread, trap, handlerHandle, undefined, 1); info.SetCallArg(targetHandle.GetTaggedValue()); JSTaggedValue res = JSFunction::Call(&info); + RETURN_HANDLE_IF_ABRUPT_COMPLETION(TaggedArray, thread); JSHandle trap_res_arr(thread, res); // 9.Let trapResult be CreateListFromArrayLike(trapResultArray, «String, Symbol»). @@ -866,15 +867,19 @@ JSTaggedValue JSProxy::CallInternal(EcmaRuntimeCallInfo *info) // 6.ReturnIfAbrupt(trap). RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread); + size_t argc = info->GetArgsNumber(); + JSHandle thisArg = info->GetThis(); + JSHandle undefined = globalConst->GetHandledUndefined(); // 7.If trap is undefined, then // a.Return Call(target, thisArgument, argumentsList). if (method->IsUndefined()) { - info->SetFunction(target.GetTaggedValue()); - return JSFunction::Call(info); + EcmaRuntimeCallInfo runtimeInfo = + EcmaInterpreter::NewRuntimeCallInfo(thread, target, thisArg, undefined, argc); + runtimeInfo.SetCallArg(argc, 0, info, 0); + return JSFunction::Call(&runtimeInfo); } // 8.Let argArray be CreateArrayFromList(argumentsList). ObjectFactory *factory = thread->GetEcmaVM()->GetFactory(); - size_t argc = info->GetArgsNumber(); JSHandle taggedArray = factory->NewTaggedArray(static_cast(argc)); for (size_t index = 0; index < argc; ++index) { taggedArray->Set(thread, index, info->GetCallArg(index)); @@ -882,9 +887,7 @@ JSTaggedValue JSProxy::CallInternal(EcmaRuntimeCallInfo *info) JSHandle arrHandle = JSArray::CreateArrayFromList(thread, taggedArray); // 9.Return Call(trap, handler, «target, thisArgument, argArray»). - JSHandle thisArg = info->GetThis(); const size_t argsLength = 3; // 3: «target, thisArgument, argArray» - JSHandle undefined = globalConst->GetHandledUndefined(); EcmaRuntimeCallInfo runtimeInfo = EcmaInterpreter::NewRuntimeCallInfo(thread, method, handler, undefined, argsLength); runtimeInfo.SetCallArg(target.GetTaggedValue(), thisArg.GetTaggedValue(), arrHandle.GetTaggedValue()); -- Gitee From 21c2eb2fb58f80b893d43a24545ae0aedbf89037 Mon Sep 17 00:00:00 2001 From: Rtangyu Date: Fri, 17 Jun 2022 10:48:11 +0800 Subject: [PATCH 028/154] Cpupprofiler supports native method pointer printing issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CPNX Signed-off-by: Rtangyu --- ecmascript/dfx/cpu_profiler/cpu_profiler.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ecmascript/dfx/cpu_profiler/cpu_profiler.cpp b/ecmascript/dfx/cpu_profiler/cpu_profiler.cpp index 42c59f27..44b02565 100644 --- a/ecmascript/dfx/cpu_profiler/cpu_profiler.cpp +++ b/ecmascript/dfx/cpu_profiler/cpu_profiler.cpp @@ -252,10 +252,10 @@ void CpuProfiler::GetFrameStack(JSThread *thread) if (!SamplesRecord::staticGcState_) { FrameHandler frameHandler(thread); for (; frameHandler.HasFrame(); frameHandler.PrevInterpretedFrame()) { - if (frameHandler.IsEntryFrame()) { + if (!frameHandler.IsInterpretedFrame()) { continue; } - auto *method = frameHandler.GetMethod(); + auto method = frameHandler.CheckAndGetMethod(); if (method != nullptr && staticStackInfo_.count(method) == 0) { ParseMethodInfo(method, frameHandler); } @@ -269,7 +269,10 @@ void CpuProfiler::ParseMethodInfo(JSMethod *method, FrameHandler frameHandler) struct FrameInfo codeEntry; if (method != nullptr && method->IsNativeWithCallField()) { codeEntry.codeType = "other"; - codeEntry.functionName = "native"; + auto addr = method->GetNativePointer(); + std::stringstream strm; + strm << addr; + codeEntry.functionName = "native(" + strm.str() + ")"; staticStackInfo_.insert(std::make_pair(method, codeEntry)); } else if (method != nullptr) { codeEntry.codeType = "JS"; -- Gitee From c2f8615c4f3c81af82d9ddf486db08b55aefe246 Mon Sep 17 00:00:00 2001 From: Xiao Liu Date: Fri, 17 Jun 2022 11:28:26 +0800 Subject: [PATCH 029/154] Prefer constexpr in builtins.cpp Signed-off-by: Xiao Liu Change-Id: I8ca3fcc68ade5df66107fca16de8e83626c1332d --- ecmascript/builtins.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/ecmascript/builtins.cpp b/ecmascript/builtins.cpp index 8d2b5ef0..33ff8d06 100644 --- a/ecmascript/builtins.cpp +++ b/ecmascript/builtins.cpp @@ -830,7 +830,7 @@ void Builtins::InitializeBigInt(const JSHandle &env, const JSHandle &env, const JSHandle &objFuncDynclass) const { [[maybe_unused]] EcmaHandleScope scope(thread_); - const int utcLength = 7; + constexpr int utcLength = 7; // Date.prototype JSHandle dateFuncPrototype = factory_->NewJSObjectWithInit(objFuncDynclass); JSHandle dateFuncPrototypeValue(dateFuncPrototype); @@ -1900,7 +1900,7 @@ void Builtins::InitializeArray(const JSHandle &env, const JSHandle(arrayFunction), speciesSymbol, speciesGetter); - const int arrProtoLen = 0; + constexpr int arrProtoLen = 0; JSHandle key_string = thread_->GlobalConstants()->GetHandledLengthString(); PropertyDescriptor descriptor(thread_, JSHandle(thread_, JSTaggedValue(arrProtoLen)), true, false, false); @@ -2060,7 +2060,7 @@ void Builtins::InitializeInt8Array(const JSHandle &env, const JSHandl int8ArrayFunction->SetProtoOrDynClass(thread_, int8ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 1; + constexpr int bytesPerElement = 1; SetConstant(int8ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(int8ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetInt8ArrayFunction(thread_, int8ArrayFunction); @@ -2084,7 +2084,7 @@ void Builtins::InitializeUint8Array(const JSHandle &env, const JSHand uint8ArrayFunction->SetProtoOrDynClass(thread_, uint8ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 1; + constexpr int bytesPerElement = 1; SetConstant(uint8ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(uint8ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetUint8ArrayFunction(thread_, uint8ArrayFunction); @@ -2111,7 +2111,7 @@ void Builtins::InitializeUint8ClampedArray(const JSHandle &env, uint8ClampedArrayFunction->SetProtoOrDynClass(thread_, uint8ClampedArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 1; + constexpr int bytesPerElement = 1; SetConstant(uint8ClampedArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(uint8ClampedArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetUint8ClampedArrayFunction(thread_, uint8ClampedArrayFunction); @@ -2135,7 +2135,7 @@ void Builtins::InitializeInt16Array(const JSHandle &env, const JSHand int16ArrayFunction->SetProtoOrDynClass(thread_, int16ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 2; + constexpr int bytesPerElement = 2; SetConstant(int16ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(int16ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetInt16ArrayFunction(thread_, int16ArrayFunction); @@ -2159,7 +2159,7 @@ void Builtins::InitializeUint16Array(const JSHandle &env, const JSHan uint16ArrayFunction->SetProtoOrDynClass(thread_, uint16ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 2; + constexpr int bytesPerElement = 2; SetConstant(uint16ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(uint16ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetUint16ArrayFunction(thread_, uint16ArrayFunction); @@ -2183,7 +2183,7 @@ void Builtins::InitializeInt32Array(const JSHandle &env, const JSHand int32ArrayFunction->SetProtoOrDynClass(thread_, int32ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 4; + constexpr int bytesPerElement = 4; SetConstant(int32ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(int32ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetInt32ArrayFunction(thread_, int32ArrayFunction); @@ -2207,7 +2207,7 @@ void Builtins::InitializeUint32Array(const JSHandle &env, const JSHan uint32ArrayFunction->SetProtoOrDynClass(thread_, uint32ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 4; + constexpr int bytesPerElement = 4; SetConstant(uint32ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(uint32ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetUint32ArrayFunction(thread_, uint32ArrayFunction); @@ -2231,7 +2231,7 @@ void Builtins::InitializeFloat32Array(const JSHandle &env, const JSHa float32ArrayFunction->SetProtoOrDynClass(thread_, float32ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 4; + constexpr int bytesPerElement = 4; SetConstant(float32ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(float32ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetFloat32ArrayFunction(thread_, float32ArrayFunction); @@ -2255,7 +2255,7 @@ void Builtins::InitializeFloat64Array(const JSHandle &env, const JSHa float64ArrayFunction->SetProtoOrDynClass(thread_, float64ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 8; + constexpr int bytesPerElement = 8; SetConstant(float64ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(float64ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetFloat64ArrayFunction(thread_, float64ArrayFunction); @@ -2279,7 +2279,7 @@ void Builtins::InitializeBigInt64Array(const JSHandle &env, const JSH bigInt64ArrayFunction->SetProtoOrDynClass(thread_, bigInt64ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 8; + constexpr int bytesPerElement = 8; SetConstant(bigInt64ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(bigInt64ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetBigInt64ArrayFunction(thread_, bigInt64ArrayFunction); @@ -2303,7 +2303,7 @@ void Builtins::InitializeBigUint64Array(const JSHandle &env, const JS bigUint64ArrayFunction->SetProtoOrDynClass(thread_, bigUint64ArrFuncInstanceDynclass.GetTaggedValue()); - const int bytesPerElement = 8; + constexpr int bytesPerElement = 8; SetConstant(bigUint64ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); SetConstant(JSHandle(bigUint64ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement)); env->SetBigUint64ArrayFunction(thread_, bigUint64ArrayFunction); -- Gitee From 20994653e0e1e2ebcd3b9d6847c7fac9eec788ba Mon Sep 17 00:00:00 2001 From: dingwen Date: Fri, 17 Jun 2022 12:14:18 +0800 Subject: [PATCH 030/154] gc bugfix for MergeRSetForConcurrentSweeping Description:Delele the invoke of MergeRSetForConcurrentSweeping() when localspace merge issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CR1D Signed-off-by: dingwen Change-Id: I5779151d6029bb2eb7e6a4f2b864eafce910c42b --- ecmascript/mem/sparse_space.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/ecmascript/mem/sparse_space.cpp b/ecmascript/mem/sparse_space.cpp index 8d7defd2..71dfafd6 100644 --- a/ecmascript/mem/sparse_space.cpp +++ b/ecmascript/mem/sparse_space.cpp @@ -317,7 +317,6 @@ void OldSpace::Merge(LocalSpace *localSpace) localSpace->RemoveRegion(region); localSpace->DecreaseLiveObjectSize(region->AliveObject()); AddRegion(region); - region->MergeRSetForConcurrentSweeping(); IncreaseLiveObjectSize(region->AliveObject()); allocator_->CollectFreeObjectSet(region); }); -- Gitee From e49e448f77a58b06204c79c87ee5f4e1e15e844b Mon Sep 17 00:00:00 2001 From: dingwen Date: Tue, 14 Jun 2022 19:18:29 +0800 Subject: [PATCH 031/154] Snapshot support reusing global const and builtins object Description:Before serializing, cache all global const and builtins objects in a map. When serialzing object taggged field, firstly searching the field object in the map, if exist, record the index. Then when deserializing, we can quickly find the object by index. ISSUE:https://gitee.com/openharmony/ark_js_runtime/issues/I5CA56 Signed-off-by: dingwen Change-Id: I935cc445d50a1e5854b88a7d01445aaa87da2cbc --- ecmascript/base/config.h | 1 + ecmascript/ecma_vm.cpp | 4 +- ecmascript/global_env_constants.h | 6 -- ecmascript/js_hclass.h | 30 ++++++--- ecmascript/js_tagged_value-inl.h | 2 +- ecmascript/snapshot/mem/constants.h | 3 +- ecmascript/snapshot/mem/encode_bit.h | 49 +++++++------- ecmascript/snapshot/mem/snapshot.cpp | 5 +- ecmascript/snapshot/mem/snapshot.h | 1 - ecmascript/snapshot/mem/snapshot_env.cpp | 64 +++++++++++++++---- ecmascript/snapshot/mem/snapshot_env.h | 26 ++++++-- .../snapshot/mem/snapshot_processor.cpp | 44 ++++++------- ecmascript/snapshot/tests/snapshot_test.cpp | 5 +- 13 files changed, 150 insertions(+), 90 deletions(-) diff --git a/ecmascript/base/config.h b/ecmascript/base/config.h index 69ff97af..b3f81e7e 100644 --- a/ecmascript/base/config.h +++ b/ecmascript/base/config.h @@ -28,6 +28,7 @@ namespace panda::ecmascript { #define ECMASCRIPT_ENABLE_INTERPRETER_RUNTIME_STAT 0 #define ECMASCRIPT_ENABLE_BUILTINS_RUNTIME_STAT 0 #define ECMASCRIPT_ENABLE_ALLOCATE_AND_GC_RUNTIME_STAT 0 +#define ECMASCRIPT_ENABLE_SNAPSHOT 0 /* * 1. close ic diff --git a/ecmascript/ecma_vm.cpp b/ecmascript/ecma_vm.cpp index ddd3d437..edd829b2 100644 --- a/ecmascript/ecma_vm.cpp +++ b/ecmascript/ecma_vm.cpp @@ -49,7 +49,6 @@ #include "ecmascript/mem/mem.h" #include "ecmascript/mem/space.h" #include "ecmascript/mem/visitor.h" -#include "ecmascript/snapshot/mem/snapshot_env.h" #include "ecmascript/taskpool/task.h" #include "ecmascript/module/js_module_manager.h" #include "ecmascript/object_factory.h" @@ -177,6 +176,9 @@ bool EcmaVM::Initialize() debuggerManager_->Initialize(); tsLoader_ = new TSLoader(this); snapshotEnv_ = new SnapshotEnv(this); + if (!WIN_OR_MAC_PLATFORM) { + snapshotEnv_->Initialize(); + } fileLoader_ = new FileLoader(this); if (options_.GetEnableAsmInterpreter()) { LoadStubFile(); diff --git a/ecmascript/global_env_constants.h b/ecmascript/global_env_constants.h index 72a64c5b..00671abb 100644 --- a/ecmascript/global_env_constants.h +++ b/ecmascript/global_env_constants.h @@ -400,7 +400,6 @@ enum class ConstantIndex : size_t { READ_ONLY_CONSTATNT_END = CONSTATNT_END, JSAPI_CONTAINERS_BEGIN = ARRAYLIST_FUNCTION_INDEX, JSAPI_CONTAINERS_END = LINKED_LIST_ITERATOR_PROTOTYPE_INDEX, - HCLASS_END = CELL_RECORD_CLASS_INDEX, // ... }; // clang-format on @@ -456,11 +455,6 @@ public: return constants_[index]; } - size_t GetHClassEndIndex() const - { - return static_cast(ConstantIndex::HCLASS_END); - } - size_t GetConstantCount() const { return static_cast(ConstantIndex::CONSTATNT_COUNT); diff --git a/ecmascript/js_hclass.h b/ecmascript/js_hclass.h index 39f3a869..5228ee8e 100644 --- a/ecmascript/js_hclass.h +++ b/ecmascript/js_hclass.h @@ -240,19 +240,20 @@ enum class JSType : uint8_t { class JSHClass : public TaggedObject { public: static constexpr int TYPE_BITFIELD_NUM = 8; - using ObjectTypeBits = BitField; // 7 + using ObjectTypeBits = BitField; // 8 using CallableBit = ObjectTypeBits::NextFlag; - using ConstructorBit = CallableBit::NextFlag; // 9 + using ConstructorBit = CallableBit::NextFlag; // 10 using ExtensibleBit = ConstructorBit::NextFlag; using IsPrototypeBit = ExtensibleBit::NextFlag; using ElementRepresentationBits = IsPrototypeBit::NextField; // 3 means next 3 bit - using DictionaryElementBits = ElementRepresentationBits::NextFlag; // 15 - using IsDictionaryBit = DictionaryElementBits::NextFlag; // 16 - using IsStableElementsBit = IsDictionaryBit::NextFlag; // 17 - using HasConstructorBits = IsStableElementsBit::NextFlag; // 18 - using IsLiteralBit = HasConstructorBits::NextFlag; // 19 - using ClassConstructorBit = IsLiteralBit::NextFlag; // 20 - using ClassPrototypeBit = ClassConstructorBit::NextFlag; // 21 + using DictionaryElementBits = ElementRepresentationBits::NextFlag; // 16 + using IsDictionaryBit = DictionaryElementBits::NextFlag; // 17 + using IsStableElementsBit = IsDictionaryBit::NextFlag; // 18 + using HasConstructorBits = IsStableElementsBit::NextFlag; // 19 + using IsLiteralBit = HasConstructorBits::NextFlag; // 20 + using ClassConstructorBit = IsLiteralBit::NextFlag; // 21 + using ClassPrototypeBit = ClassConstructorBit::NextFlag; // 22 + using GlobalConstOrBuiltinsObjectBit = ClassPrototypeBit::NextFlag; // 23 static constexpr int DEFAULT_CAPACITY_OF_IN_OBJECTS = 4; static constexpr int MAX_CAPACITY_OF_OUT_OBJECTS = @@ -370,6 +371,11 @@ public: ClassPrototypeBit::Set(flag, GetBitFieldAddr()); } + inline void SetGlobalConstOrBuiltinsObject(bool flag) const + { + GlobalConstOrBuiltinsObjectBit::Set(flag, GetBitFieldAddr()); + } + inline void SetIsDictionaryMode(bool flag) const { IsDictionaryBit::Set(flag, GetBitFieldAddr()); @@ -924,6 +930,12 @@ public: return ClassPrototypeBit::Decode(bits); } + inline bool IsGlobalConstOrBuiltinsObject() const + { + uint32_t bits = GetBitField(); + return GlobalConstOrBuiltinsObjectBit::Decode(bits); + } + inline bool IsDictionaryMode() const { uint32_t bits = GetBitField(); diff --git a/ecmascript/js_tagged_value-inl.h b/ecmascript/js_tagged_value-inl.h index d7e4dc05..3cb5d5b7 100644 --- a/ecmascript/js_tagged_value-inl.h +++ b/ecmascript/js_tagged_value-inl.h @@ -1279,4 +1279,4 @@ inline JSTaggedNumber JSTaggedValue::StringToDouble(JSTaggedValue tagged) return JSTaggedNumber(d); } } // namespace panda::ecmascript -#endif // ECMASCRIPT_TAGGED_VALUE__INL_H +#endif // ECMASCRIPT_TAGGED_VALUE_INL_H diff --git a/ecmascript/snapshot/mem/constants.h b/ecmascript/snapshot/mem/constants.h index b29ce2b6..4413fa08 100644 --- a/ecmascript/snapshot/mem/constants.h +++ b/ecmascript/snapshot/mem/constants.h @@ -37,7 +37,8 @@ public: static constexpr size_t PAGE_SIZE_ALIGN_UP = 4_KB; static constexpr size_t MAX_UINT_16 = 0xFFFF; static constexpr size_t MAX_UINT_32 = 0xFFFFFFFF; - static constexpr size_t MAX_STRING_SIZE = 0x0FFFFFFF; + static constexpr size_t MAX_OBJECT_INDEX = 0x0FFFFFFF; + static constexpr size_t REGION_INDEX_MASK = 0x3FF; // 10 bits static constexpr int UINT_64_BITS_COUNT = 64; // builtins native method encode diff --git a/ecmascript/snapshot/mem/encode_bit.h b/ecmascript/snapshot/mem/encode_bit.h index 49299247..68b891fb 100644 --- a/ecmascript/snapshot/mem/encode_bit.h +++ b/ecmascript/snapshot/mem/encode_bit.h @@ -25,9 +25,9 @@ /* * EncodeBit: use uint64_t value to encode TaggedObject when serialize * - * |0000...000| |0000...000| |0| |0| |0000000| |0| |0000...000| |00...0| - * 16bit:is reference 10bit:native or builtins special obj type string 18bit:obj offset 10bit:region index - * global index + * |0000...000| |0000...00| |0| |0| |00000000| |0| |0000...000| |00...0| + * 16bit:is reference 9bit:unused builtins special obj type string 18bit:obj offset 10bit:region index + * */ namespace panda::ecmascript { @@ -45,10 +45,10 @@ public: static constexpr int REGION_INDEX_BIT_NUMBER = 10; // region index static constexpr int OBJECT_OFFSET_IN_REGION_NUMBER = 18; // object offset in current region static constexpr int OBJECT_TO_STRING_FLAG_NUMBER = 1; // 1 : reference to string - static constexpr int OBJECT_TYPE_BIT_NUMBER = 7; // js_type + static constexpr int OBJECT_TYPE_BIT_NUMBER = 8; // js_type static constexpr int OBJECT_SPECIAL = 1; // special - static constexpr int GLOBAL_ENV_CONST = 1; // global object which has initialized before snapshot - static constexpr int NATIVE_OR_GLOBAL_INDEX_NUMBER = 10; // native pointer or global object index + static constexpr int GLOBAL_CONST_OR_BUILTINS = 1; // is global const or builtins object + static constexpr int UNUSED_BIT_NUMBER = 9; // unused bit number static constexpr int IS_REFERENCE_BIT_NUMBER = 16; // [0x0000] is reference using RegionIndexBits = BitField; @@ -56,9 +56,9 @@ public: using ObjectToStringBits = ObjectOffsetInRegionBits::NextField; using ObjectTypeBits = ObjectToStringBits::NextField; using ObjectSpecialBits = ObjectTypeBits::NextField; - using GlobalEnvConstBits = ObjectSpecialBits::NextField; - using NativeOrGlobalIndexBits = GlobalEnvConstBits::NextField; - using IsReferenceBits = NativeOrGlobalIndexBits::NextField; + using GlobalConstOrBuiltinsBits = ObjectSpecialBits::NextField; + using UnusedBits = GlobalConstOrBuiltinsBits::NextField; + using IsReferenceBits = UnusedBits::NextField; void SetRegionIndex(size_t region_index) { @@ -85,11 +85,6 @@ public: ObjectTypeBits::Set(object_type, &value_); } - void SetNativeOrGlobalIndex(size_t native_or_global_index) - { - NativeOrGlobalIndexBits::Set(native_or_global_index, &value_); - } - uint64_t GetValue() const { return value_; @@ -105,7 +100,7 @@ public: return ObjectOffsetInRegionBits::Decode(value_); } - size_t GetStringIndex() const + size_t GetNativePointerOrObjectIndex() const { return (ObjectOffsetInRegionBits::Decode(value_) << REGION_INDEX_BIT_NUMBER) + RegionIndexBits::Decode(value_); } @@ -115,11 +110,6 @@ public: return ObjectTypeBits::Decode(value_); } - size_t GetNativeOrGlobalIndex() const - { - return NativeOrGlobalIndexBits::Decode(value_); - } - bool IsReference() const { return IsReferenceBits::Decode(value_) == 0; @@ -135,14 +125,23 @@ public: ObjectSpecialBits::Set(true, &value_); } - bool IsGlobalEnvConst() const + bool IsGlobalConstOrBuiltins() const + { + return GlobalConstOrBuiltinsBits::Decode(value_); + } + + void SetGlobalConstOrBuiltins() { - return GlobalEnvConstBits::Decode(value_); + GlobalConstOrBuiltinsBits::Set(true, &value_); } - void SetGlobalEnvConst() + // low 28 bits are used to record object location(region index and object offset), besides, it's + // used to record string index, global const and builtins object index, native pointer index + void SetNativePointerOrObjectIndex(size_t index) { - GlobalEnvConstBits::Set(true, &value_); + ASSERT(index < Constants::MAX_OBJECT_INDEX); + ObjectOffsetInRegionBits::Set(index >> REGION_INDEX_BIT_NUMBER, &value_); + RegionIndexBits::Set(index & Constants::REGION_INDEX_MASK, &value_); } void ClearObjectSpecialFlag() @@ -155,7 +154,7 @@ private: }; static_assert(EncodeBit::REGION_INDEX_BIT_NUMBER + EncodeBit::OBJECT_OFFSET_IN_REGION_NUMBER + EncodeBit::OBJECT_TO_STRING_FLAG_NUMBER + EncodeBit::OBJECT_TYPE_BIT_NUMBER + EncodeBit::OBJECT_SPECIAL + - EncodeBit::GLOBAL_ENV_CONST + EncodeBit::NATIVE_OR_GLOBAL_INDEX_NUMBER + + EncodeBit::GLOBAL_CONST_OR_BUILTINS + EncodeBit::UNUSED_BIT_NUMBER + EncodeBit::IS_REFERENCE_BIT_NUMBER == Constants::UINT_64_BITS_COUNT); } // namespace panda::ecmascript diff --git a/ecmascript/snapshot/mem/snapshot.cpp b/ecmascript/snapshot/mem/snapshot.cpp index 1f3186e5..36b5941a 100644 --- a/ecmascript/snapshot/mem/snapshot.cpp +++ b/ecmascript/snapshot/mem/snapshot.cpp @@ -30,6 +30,7 @@ #include "ecmascript/mem/c_containers.h" #include "ecmascript/mem/heap.h" #include "ecmascript/object_factory.h" +#include "ecmascript/snapshot/mem/snapshot_env.h" #include "ecmascript/ts_types/ts_loader.h" #include "libpandabase/mem/mem.h" @@ -48,7 +49,6 @@ void Snapshot::Serialize(TaggedObject *objectHeader, const panda_file::File *pf, SnapshotProcessor processor(vm_); processor.Initialize(); - vm_->GetSnapshotEnv()->Initialize(); std::unordered_map> data; CQueue objectQueue; @@ -61,7 +61,6 @@ void Snapshot::Serialize(TaggedObject *objectHeader, const panda_file::File *pf, size_t rootObjSize = objectQueue.size(); processor.ProcessObjectQueue(&objectQueue, &data); WriteToFile(writer, pf, rootObjSize, processor); - vm_->GetSnapshotEnv()->ClearEnvMap(); } void Snapshot::Serialize(uintptr_t startAddr, size_t size, const CString &fileName) @@ -78,7 +77,6 @@ void Snapshot::Serialize(uintptr_t startAddr, size_t size, const CString &fileNa SnapshotProcessor processor(vm_); processor.Initialize(); - vm_->GetSnapshotEnv()->Initialize(); std::unordered_map> data; CQueue objectQueue; @@ -89,7 +87,6 @@ void Snapshot::Serialize(uintptr_t startAddr, size_t size, const CString &fileNa processor.ProcessObjectQueue(&objectQueue, &data); WriteToFile(writer, nullptr, size, processor); - vm_->GetSnapshotEnv()->ClearEnvMap(); } void Snapshot::SerializeBuiltins(const CString &fileName) diff --git a/ecmascript/snapshot/mem/snapshot.h b/ecmascript/snapshot/mem/snapshot.h index 48493154..7f81cecb 100644 --- a/ecmascript/snapshot/mem/snapshot.h +++ b/ecmascript/snapshot/mem/snapshot.h @@ -21,7 +21,6 @@ #include "ecmascript/common.h" #include "ecmascript/snapshot/mem/encode_bit.h" -#include "ecmascript/snapshot/mem/snapshot_env.h" #include "ecmascript/snapshot/mem/snapshot_processor.h" #include "ecmascript/mem/c_string.h" diff --git a/ecmascript/snapshot/mem/snapshot_env.cpp b/ecmascript/snapshot/mem/snapshot_env.cpp index 362c47b5..a4c44760 100644 --- a/ecmascript/snapshot/mem/snapshot_env.cpp +++ b/ecmascript/snapshot/mem/snapshot_env.cpp @@ -20,29 +20,71 @@ namespace panda::ecmascript { void SnapshotEnv::Initialize() +{ +#if ECMASCRIPT_ENABLE_SNAPSHOT + InitGlobalConst(); + InitGlobalEnv(); +#endif +} + +void SnapshotEnv::InitGlobalConst() { auto globalConst = const_cast(vm_->GetJSThread()->GlobalConstants()); - size_t endIndex = globalConst->GetHClassEndIndex(); - for (size_t index = 0; index <= endIndex; index++) { + size_t constantCount = globalConst->GetConstantCount(); + for (size_t index = 0; index < constantCount; index++) { JSTaggedValue objectValue = globalConst->GetGlobalConstantObject(index); - envMap_.emplace(ToUintPtr(objectValue.GetTaggedObject()), index); + if (objectValue.IsHeapObject() && !objectValue.IsString()) { + TaggedObject *object = objectValue.GetTaggedObject(); + object->GetClass()->SetGlobalConstOrBuiltinsObject(true); + objectVector_.emplace_back(ToUintPtr(object)); + } } +} +void SnapshotEnv::InitGlobalEnv() +{ auto globalEnv = vm_->GetGlobalEnv(); - size_t globalEnvFieldSize = globalEnv->GetGlobalEnvFieldSize(); - for (size_t i = 0; i < globalEnvFieldSize; i++) { - uintptr_t address = globalEnv->ComputeObjectAddress(i); - JSHandle result(address); - if (result->IsHeapObject()) { - envMap_.emplace(ToUintPtr(result->GetTaggedObject()), i); + CQueue objectQueue; + std::set objectSet; + objectQueue.emplace(*globalEnv); + objectSet.emplace(*globalEnv); + while (!objectQueue.empty()) { + auto taggedObject = objectQueue.front(); + if (taggedObject == nullptr) { + break; } + taggedObject->GetClass()->SetGlobalConstOrBuiltinsObject(true); + objectVector_.emplace_back(ToUintPtr(taggedObject)); + objectQueue.pop(); + HandleObjectField(taggedObject, &objectQueue, &objectSet); } } +void SnapshotEnv::HandleObjectField(TaggedObject *objectHeader, CQueue *objectQueue, + std::set *objectSet) +{ + auto visitor = [objectQueue, objectSet]([[maybe_unused]]TaggedObject *root, ObjectSlot start, ObjectSlot end, + [[maybe_unused]]bool isNative) { + for (ObjectSlot slot = start; slot < end; slot++) { + auto fieldAddr = reinterpret_cast(slot.SlotAddress()); + JSTaggedValue fieldValue(*fieldAddr); + if (fieldValue.IsHeapObject() && !fieldValue.IsWeak() && !fieldValue.IsString() + && objectSet->find(fieldValue.GetTaggedObject()) == objectSet->end()) { + auto object = fieldValue.GetTaggedObject(); + objectQueue->emplace(object); + objectSet->emplace(object); + } + } + }; + objXRay_.VisitObjectBody(objectHeader, objectHeader->GetClass(), visitor); +} + void SnapshotEnv::Iterate(const RootVisitor &v) { - for (const auto &it : envMap_) { - v(Root::ROOT_VM, ObjectSlot(reinterpret_cast(&(it.first)))); + uint64_t length = objectVector_.size(); + for (uint64_t i = 0; i < length; i++) { + v(Root::ROOT_VM, ObjectSlot(reinterpret_cast(&(objectVector_.data()[i])))); } } } // namespace panda::ecmascript + diff --git a/ecmascript/snapshot/mem/snapshot_env.h b/ecmascript/snapshot/mem/snapshot_env.h index d2e7d846..6c509fce 100644 --- a/ecmascript/snapshot/mem/snapshot_env.h +++ b/ecmascript/snapshot/mem/snapshot_env.h @@ -16,6 +16,7 @@ #ifndef ECMASCRIPT_SNAPSHOT_MEM_SNAPSHOT_ENV_H #define ECMASCRIPT_SNAPSHOT_MEM_SNAPSHOT_ENV_H +#include "ecmascript/mem/object_xray.h" #include "ecmascript/mem/visitor.h" #include "libpandabase/macros.h" @@ -24,23 +25,32 @@ class EcmaVM; class SnapshotEnv final { public: - explicit SnapshotEnv(EcmaVM *vm) : vm_(vm) {} + explicit SnapshotEnv(EcmaVM *vm) : vm_(vm), objXRay_(vm) {} ~SnapshotEnv() = default; void Initialize(); + void Iterate(const RootVisitor &v); void ClearEnvMap() { - envMap_.clear(); + objectVector_.clear(); } size_t GetEnvObjectIndex(uintptr_t objectAddr) const { - if (envMap_.find(objectAddr) == envMap_.end()) { + auto it = std::find(objectVector_.begin(), objectVector_.end(), objectAddr); + if (it == objectVector_.end()) { return MAX_UINT_32; + } else { + return std::distance(objectVector_.begin(), it); } - return envMap_.find(objectAddr)->second; + } + + uintptr_t FindEnvObjectByIndex(size_t index) + { + ASSERT(index < objectVector_.size()); + return objectVector_.at(index); } static constexpr size_t MAX_UINT_32 = 0xFFFFFFFF; @@ -49,8 +59,14 @@ private: NO_MOVE_SEMANTIC(SnapshotEnv); NO_COPY_SEMANTIC(SnapshotEnv); + void HandleObjectField(TaggedObject *objectHeader, CQueue *objectQueue, + std::set *objectSet); + void InitGlobalConst(); + void InitGlobalEnv(); + EcmaVM *vm_; - std::unordered_map envMap_; // Cache global object which can reuse when serialize + ObjectXRay objXRay_; + CVector objectVector_; }; } // namespace panda::ecmascript #endif // ECMASCRIPT_SNAPSHOT_MEM_SNAPSHOT_ENV_H \ No newline at end of file diff --git a/ecmascript/snapshot/mem/snapshot_processor.cpp b/ecmascript/snapshot/mem/snapshot_processor.cpp index b317a5f4..abe6983c 100644 --- a/ecmascript/snapshot/mem/snapshot_processor.cpp +++ b/ecmascript/snapshot/mem/snapshot_processor.cpp @@ -1093,7 +1093,7 @@ void SnapshotProcessor::DeserializeString(uintptr_t stringBegin, uintptr_t strin if (strFromTable) { stringVector_.emplace_back(ToUintPtr(strFromTable)); } else { - uintptr_t newObj = oldSpace->Allocate(strSize); + uintptr_t newObj = oldSpace->Allocate(strSize, false); if (newObj == 0) { LOG_ECMA_MEM(FATAL) << "Snapshot Allocate OldLocalSpace OOM"; } @@ -1240,7 +1240,7 @@ void SnapshotProcessor::RelocateSpaceObject(Space* space, SnapshotType type, JSM auto objType = encodeBit.GetObjectType(); if (objType == Constants::MASK_METHOD_SPACE_BEGIN) { begin += sizeof(uint64_t); - others = encodeBit.GetNativeOrGlobalIndex(); + others = encodeBit.GetNativePointerOrObjectIndex(); DeserializePandaMethod(begin, end, methods, methodNums, others); break; } @@ -1316,11 +1316,9 @@ uint64_t SnapshotProcessor::SerializeTaggedField(JSTaggedType *tagged, CQueueGetGlobalEnv(); - auto globalEnvObjectValue = globalEnv->GetGlobalEnvObjectByIndex(index); - *value = ToUintPtr(globalEnvObjectValue->GetTaggedObject()); + if (!builtinsDeserialize_ && encodeBit.IsReference() && encodeBit.IsGlobalConstOrBuiltins()) { + size_t index = encodeBit.GetNativePointerOrObjectIndex(); + *value = vm_->GetSnapshotEnv()->FindEnvObjectByIndex(index); return; } if (encodeBit.IsReference() && !encodeBit.IsSpecial()) { @@ -1338,8 +1336,8 @@ void SnapshotProcessor::DeserializeTaggedField(uint64_t *value) void SnapshotProcessor::DeserializeClassWord(TaggedObject *object) { EncodeBit encodeBit(*reinterpret_cast(object)); - if (!builtinsDeserialize_ && encodeBit.IsGlobalEnvConst()) { - size_t hclassIndex = encodeBit.GetNativeOrGlobalIndex(); + if (!builtinsDeserialize_ && encodeBit.IsGlobalConstOrBuiltins()) { + size_t hclassIndex = encodeBit.GetNativePointerOrObjectIndex(); auto globalConst = const_cast(vm_->GetJSThread()->GlobalConstants()); JSTaggedValue hclassValue = globalConst->GetGlobalConstantObject(hclassIndex); ASSERT(hclassValue.IsJSHClass()); @@ -1382,14 +1380,14 @@ EncodeBit SnapshotProcessor::NativePointerToEncodeBit(void *nativePointer) } LOG_IF(index > Constants::MAX_C_POINTER_INDEX, FATAL, RUNTIME) << "MAX_C_POINTER_INDEX: " + ToCString(index); - native.SetNativeOrGlobalIndex(index); + native.SetNativePointerOrObjectIndex(index); } return native; } void *SnapshotProcessor::NativePointerEncodeBitToAddr(EncodeBit nativeBit) { - size_t index = nativeBit.GetNativeOrGlobalIndex(); + size_t index = nativeBit.GetNativePointerOrObjectIndex(); void *addr = nullptr; size_t nativeTableSize = GetNativeTableSize(); @@ -1428,7 +1426,7 @@ uintptr_t SnapshotProcessor::TaggedObjectEncodeBitToAddr(EncodeBit taggedBit) { ASSERT(taggedBit.IsReference()); if (!builtinsDeserialize_ && taggedBit.IsReferenceToString()) { - size_t stringIndex = taggedBit.GetStringIndex(); + size_t stringIndex = taggedBit.GetNativePointerOrObjectIndex(); return stringVector_[stringIndex]; } size_t regionIndex = taggedBit.GetRegionIndex(); @@ -1443,7 +1441,7 @@ uintptr_t SnapshotProcessor::TaggedObjectEncodeBitToAddr(EncodeBit taggedBit) void SnapshotProcessor::DeserializeNativePointer(uint64_t *value) { EncodeBit native(*value); - size_t index = native.GetNativeOrGlobalIndex(); + size_t index = native.GetNativePointerOrObjectIndex(); uintptr_t addr = 0U; size_t nativeTableSize = GetNativeTableSize(); @@ -1459,9 +1457,8 @@ void SnapshotProcessor::DeserializeNativePointer(uint64_t *value) void SnapshotProcessor::SerializePandaFileMethod() { - EncodeBit encodeBit(0); + EncodeBit encodeBit(pandaMethod_.size()); encodeBit.SetObjectType(Constants::MASK_METHOD_SPACE_BEGIN); - encodeBit.SetNativeOrGlobalIndex(pandaMethod_.size()); ObjectFactory *factory = vm_->GetFactory(); // panda method space begin @@ -1494,7 +1491,7 @@ EncodeBit SnapshotProcessor::EncodeTaggedObject(TaggedObject *objectHeader, CQue if (!builtinsSerialize_) { // String duplicate if (objectHeader->GetClass()->GetObjectType() == JSType::STRING) { - ASSERT(stringVector_.size() < Constants::MAX_STRING_SIZE); + ASSERT(stringVector_.size() < Constants::MAX_OBJECT_INDEX); EncodeBit encodeBit(stringVector_.size()); stringVector_.emplace_back(ToUintPtr(objectHeader)); data->emplace(ToUintPtr(objectHeader), std::make_pair(0U, encodeBit)); @@ -1502,13 +1499,14 @@ EncodeBit SnapshotProcessor::EncodeTaggedObject(TaggedObject *objectHeader, CQue } // builtins object reuse - size_t globalEnvIndex = vm_->GetSnapshotEnv()->GetEnvObjectIndex(ToUintPtr(objectHeader)); - if (globalEnvIndex != SnapshotEnv::MAX_UINT_32) { - EncodeBit encodeBit(0); - encodeBit.SetGlobalEnvConst(); - encodeBit.SetNativeOrGlobalIndex(globalEnvIndex); - data->emplace(ToUintPtr(objectHeader), std::make_pair(0U, encodeBit)); - return encodeBit; + if (objectHeader->GetClass()->IsGlobalConstOrBuiltinsObject()) { + size_t index = vm_->GetSnapshotEnv()->GetEnvObjectIndex(ToUintPtr(objectHeader)); + if (index != SnapshotEnv::MAX_UINT_32) { + EncodeBit encodeBit(index); + encodeBit.SetGlobalConstOrBuiltins(); + data->emplace(ToUintPtr(objectHeader), std::make_pair(0U, encodeBit)); + return encodeBit; + } } } queue->emplace(objectHeader); diff --git a/ecmascript/snapshot/tests/snapshot_test.cpp b/ecmascript/snapshot/tests/snapshot_test.cpp index 3c06db8e..df0bb67e 100644 --- a/ecmascript/snapshot/tests/snapshot_test.cpp +++ b/ecmascript/snapshot/tests/snapshot_test.cpp @@ -133,7 +133,6 @@ HWTEST_F_L0(SnapshotTest, SerializeConstPool) EXPECT_TRUE(constpool1->Get(0).IsJSFunction()); EXPECT_TRUE(constpool1->Get(1).IsJSFunction()); EXPECT_TRUE(constpool1->Get(3).IsJSFunction()); - EXPECT_EQ(constpool1->Get(0).GetRawData(), constpool1->Get(0).GetRawData()); EcmaString *str11 = reinterpret_cast(constpool1->Get(2).GetTaggedObject()); EcmaString *str22 = reinterpret_cast(constpool1->Get(4).GetTaggedObject()); EcmaString *str33 = reinterpret_cast(constpool1->Get(5).GetTaggedObject()); @@ -263,14 +262,14 @@ HWTEST_F_L0(SnapshotTest, SerializeBuiltins) EcmaVM *ecmaVm2 = EcmaVM::Create(options2); EXPECT_TRUE(ecmaVm2->GetGlobalEnv()->GetClass()->GetObjectType() == JSType::GLOBAL_ENV); auto globalConst = const_cast(ecmaVm2->GetJSThread()->GlobalConstants()); - size_t hclassEndIndex = globalConst->GetHClassEndIndex(); + size_t hclassEndIndex = static_cast(ConstantIndex::UNDEFINED_INDEX); size_t hclassIndex = 0; globalConst->VisitRangeSlot([&hclassIndex, &hclassEndIndex]([[maybe_unused]]Root type, ObjectSlot start, ObjectSlot end) { while (start < end) { JSTaggedValue object(start.GetTaggedType()); start++; - if (hclassIndex <= hclassEndIndex) { + if (hclassIndex < hclassEndIndex) { EXPECT_TRUE(object.IsJSHClass()); } hclassIndex++; -- Gitee From 9dd5612b4cb7cec9666f3499c567202398542a53 Mon Sep 17 00:00:00 2001 From: zhangyukun8 Date: Fri, 17 Jun 2022 16:02:23 +0800 Subject: [PATCH 032/154] Fix return value of resume uncaught exception 1. acc is changed when call resumeuncaughtandreturn Issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CTK3?from=project-issue Signed-off-by: zhangyukun8 Change-Id: Icd470fcd6e04da9f5f437804620643b2c109a19b --- ecmascript/compiler/call_signature.cpp | 7 ++++--- ecmascript/compiler/interpreter_stub.cpp | 2 +- ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp | 4 ++-- ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp | 4 ++-- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/ecmascript/compiler/call_signature.cpp b/ecmascript/compiler/call_signature.cpp index 94541158..b8a11483 100644 --- a/ecmascript/compiler/call_signature.cpp +++ b/ecmascript/compiler/call_signature.cpp @@ -677,12 +677,13 @@ DEF_CALL_SIGNATURE(ResumeCaughtFrameAndDispatch) DEF_CALL_SIGNATURE(ResumeUncaughtFrameAndReturn) { - // 1 : 1 input parameters - CallSignature resumeUncaughtFrameAndReturn("ResumeUncaughtFrameAndReturn", 0, 1, + // 2 : 2 input parameters + CallSignature resumeUncaughtFrameAndReturn("ResumeUncaughtFrameAndReturn", 0, 2, ArgumentsOrder::DEFAULT_ORDER, VariableType::VOID()); *callSign = resumeUncaughtFrameAndReturn; - std::array params = { // 1 : 1 input parameters + std::array params = { // 2 : 2 input parameters VariableType::NATIVE_POINTER(), + VariableType::JS_ANY(), }; callSign->SetParameters(params.data()); callSign->SetTargetKind(CallSignature::TargetKind::RUNTIME_STUB_NO_GC); diff --git a/ecmascript/compiler/interpreter_stub.cpp b/ecmascript/compiler/interpreter_stub.cpp index 9d703bc2..377ea056 100644 --- a/ecmascript/compiler/interpreter_stub.cpp +++ b/ecmascript/compiler/interpreter_stub.cpp @@ -4413,7 +4413,7 @@ DECLARE_ASM_HANDLER(ExceptionHandler) Branch(IntPtrEqual(*varPc, IntPtr(0)), &pcIsInvalid, &pcNotInvalid); Bind(&pcIsInvalid); { - CallNGCRuntime(glue, RTSTUB_ID(ResumeUncaughtFrameAndReturn), { glue }); + CallNGCRuntime(glue, RTSTUB_ID(ResumeUncaughtFrameAndReturn), { glue, *varAcc }); Return(); } Bind(&pcNotInvalid); diff --git a/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp b/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp index df7b4407..ebb0ce35 100644 --- a/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp +++ b/ecmascript/compiler/trampoline/aarch64/assembler_stubs.cpp @@ -1315,14 +1315,14 @@ void AssemblerStubs::ResumeCaughtFrameAndDispatch(ExtendedAssembler *assembler) // ResumeUncaughtFrameAndReturn(uintptr_t glue) // GHC calling convention // X19 - glue -// X23 - call(default) +// FP - acc void AssemblerStubs::ResumeUncaughtFrameAndReturn(ExtendedAssembler *assembler) { __ BindAssemblerStub(RTSTUB_ID(ResumeUncaughtFrameAndReturn)); Register glue(X19); Register fp(X5); - Register acc(X23); + Register acc(FP); Register cppRet(X0); __ Ldr(fp, MemoryOperand(glue, JSThread::GlueData::GetLastFpOffset(false))); diff --git a/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp b/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp index 9c558506..1d1a3237 100644 --- a/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp +++ b/ecmascript/compiler/trampoline/x64/assembler_stubs_x64.cpp @@ -2005,12 +2005,12 @@ void AssemblerStubsX64::ResumeCaughtFrameAndDispatch(ExtendedAssembler *assemble // ResumeUncaughtFrameAndReturn(uintptr_t glue) // GHC calling convention // %r13 - glue -// %rsi - acc +// %rbp - acc void AssemblerStubsX64::ResumeUncaughtFrameAndReturn(ExtendedAssembler *assembler) { __ BindAssemblerStub(RTSTUB_ID(ResumeUncaughtFrameAndReturn)); Register glueRegister = __ GlueRegister(); - Register acc(rsi); + Register acc(rbp); Register cppRet(rax); Label ret; -- Gitee From bfce3e93e526c354b622a6dff98d387f7ac88085 Mon Sep 17 00:00:00 2001 From: hjzhangcm Date: Fri, 17 Jun 2022 15:44:27 +0800 Subject: [PATCH 033/154] Test set disassembly issue:https://gitee.com/openharmony/ark_js_runtime/issues/I5CTBJ Signed-off-by: hjzhangcm --- ecmascript/builtins/tests/BUILD.gn | 27 ++++++++++++++++++++++--- ecmascript/tests/BUILD.gn | 28 +++++++++++++++++++++++--- test/resource/js_runtime/ohos_test.xml | 22 ++++++++++++++------ 3 files changed, 65 insertions(+), 12 deletions(-) diff --git a/ecmascript/builtins/tests/BUILD.gn b/ecmascript/builtins/tests/BUILD.gn index 01d58290..93b2ccc6 100755 --- a/ecmascript/builtins/tests/BUILD.gn +++ b/ecmascript/builtins/tests/BUILD.gn @@ -17,7 +17,7 @@ import("//build/test.gni") module_output_path = "ark/js_runtime" -host_unittest_action("BuiltinsInternationalTest") { +host_unittest_action("BuiltinsInternational_001_Test") { module_out_path = module_output_path sources = [ @@ -26,6 +26,25 @@ host_unittest_action("BuiltinsInternationalTest") { "builtins_collator_test.cpp", "builtins_date_time_format_test.cpp", "builtins_displaynames_test.cpp", + ] + + configs = [ + "//ark/js_runtime:ecma_test_config", + "//ark/js_runtime:icu_path_test_config", + ] + + deps = [ + "$ark_root/libpandabase:libarkbase", + "//ark/js_runtime:libark_jsruntime_test", + sdk_libc_secshared_dep, + ] +} + +host_unittest_action("BuiltinsInternational_002_Test") { + module_out_path = module_output_path + + sources = [ + # test file "builtins_intl_test.cpp", "builtins_list_format_test.cpp", "builtins_locale_test.cpp", @@ -94,7 +113,8 @@ group("unittest") { # deps file deps = [ - ":BuiltinsInternationalTest", + ":BuiltinsInternational_001_Test", + ":BuiltinsInternational_002_Test", ":BuiltinsNaturalTest", ] } @@ -104,7 +124,8 @@ group("host_unittest") { # deps file deps = [ - ":BuiltinsInternationalTestAction", + ":BuiltinsInternational_001_TestAction", + ":BuiltinsInternational_002_TestAction", ":BuiltinsNaturalTestAction", ] } diff --git a/ecmascript/tests/BUILD.gn b/ecmascript/tests/BUILD.gn index 4661b25d..956d7925 100644 --- a/ecmascript/tests/BUILD.gn +++ b/ecmascript/tests/BUILD.gn @@ -17,7 +17,7 @@ import("//build/test.gni") module_output_path = "ark/js_runtime" -host_unittest_action("EcmaVmTest") { +host_unittest_action("EcmaVm_001_Test") { module_out_path = module_output_path sources = [ @@ -57,6 +57,22 @@ host_unittest_action("EcmaVmTest") { "js_array_iterator_test.cpp", "js_array_test.cpp", "js_bigint_test.cpp", + ] + + configs = [ "//ark/js_runtime:ecma_test_config" ] + + deps = [ + "$ark_root/libpandabase:libarkbase", + "//ark/js_runtime:libark_jsruntime_test", + sdk_libc_secshared_dep, + ] +} + +host_unittest_action("EcmaVm_002_Test") { + module_out_path = module_output_path + + sources = [ + # test file "js_collator_test.cpp", "js_dataview_test.cpp", "js_date_test.cpp", @@ -110,12 +126,18 @@ group("unittest") { testonly = true # deps file - deps = [ ":EcmaVmTest" ] + deps = [ + ":EcmaVm_001_Test", + ":EcmaVm_002_Test", + ] } group("host_unittest") { testonly = true # deps file - deps = [ ":EcmaVmTestAction" ] + deps = [ + ":EcmaVm_001_TestAction", + ":EcmaVm_002_TestAction", + ] } diff --git a/test/resource/js_runtime/ohos_test.xml b/test/resource/js_runtime/ohos_test.xml index 5fbbb608..32eb9d54 100755 --- a/test/resource/js_runtime/ohos_test.xml +++ b/test/resource/js_runtime/ohos_test.xml @@ -33,12 +33,17 @@