Jsrt.cpp 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "JsrtPch.h"
  6. #include "JsrtInternal.h"
  7. #include "JsrtExternalObject.h"
  8. #include "JsrtExternalArrayBuffer.h"
  9. #include "jsrtHelper.h"
  10. #include "JsrtSourceHolder.h"
  11. #include "ByteCode/ByteCodeSerializer.h"
  12. #include "Common/ByteSwap.h"
  13. #include "Library/DataView.h"
  14. #include "Library/JavascriptSymbol.h"
  15. #include "Base/ThreadContextTlsEntry.h"
  16. #include "Codex/Utf8Helper.h"
  17. // Parser Includes
  18. #include "cmperr.h" // For ERRnoMemory
  19. #include "screrror.h" // For CompileScriptException
  20. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  21. #include "TestHooksRt.h"
  22. #endif
  23. struct CodexHeapAllocatorInterface
  24. {
  25. public:
  26. static void* allocate(size_t size)
  27. {
  28. return HeapNewArray(char, size);
  29. }
  30. static void free(void* ptr, size_t count)
  31. {
  32. HeapDeleteArray(count, (char*) ptr);
  33. }
  34. };
  35. typedef utf8::NarrowWideConverter<CodexHeapAllocatorInterface, LPCSTR, LPWSTR> NarrowToWideChakraHeap;
  36. typedef utf8::NarrowWideConverter<CodexHeapAllocatorInterface, LPCWSTR, LPSTR> WideToNarrowChakraHeap;
  37. JsErrorCode CheckContext(JsrtContext *currentContext, bool verifyRuntimeState, bool allowInObjectBeforeCollectCallback)
  38. {
  39. if (currentContext == nullptr)
  40. {
  41. return JsErrorNoCurrentContext;
  42. }
  43. Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
  44. Assert(scriptContext != nullptr);
  45. Recycler *recycler = scriptContext->GetRecycler();
  46. ThreadContext *threadContext = scriptContext->GetThreadContext();
  47. // We don't need parameter check if it's checked in previous wrapper.
  48. if (verifyRuntimeState)
  49. {
  50. if (recycler && recycler->IsHeapEnumInProgress())
  51. {
  52. return JsErrorHeapEnumInProgress;
  53. }
  54. else if (!allowInObjectBeforeCollectCallback && recycler && recycler->IsInObjectBeforeCollectCallback())
  55. {
  56. return JsErrorInObjectBeforeCollectCallback;
  57. }
  58. else if (threadContext->IsExecutionDisabled())
  59. {
  60. return JsErrorInDisabledState;
  61. }
  62. else if (scriptContext->IsInProfileCallback())
  63. {
  64. return JsErrorInProfileCallback;
  65. }
  66. else if (threadContext->IsInThreadServiceCallback())
  67. {
  68. return JsErrorInThreadServiceCallback;
  69. }
  70. // Make sure we don't have an outstanding exception.
  71. if (scriptContext->GetThreadContext()->GetRecordedException() != nullptr)
  72. {
  73. return JsErrorInExceptionState;
  74. }
  75. }
  76. return JsNoError;
  77. }
  78. /////////////////////
  79. //A create context function that we can funnel to for regular and record or debug aware creation
  80. JsErrorCode CreateContextCore(_In_ JsRuntimeHandle runtimeHandle, _In_ TTDRecorder& _actionEntryPopper, _In_ bool inRecordMode, _In_ bool activelyRecording, _In_ bool inReplayMode, _Out_ JsContextRef *newContext)
  81. {
  82. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  83. ThreadContext * threadContext = runtime->GetThreadContext();
  84. if(threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
  85. {
  86. return JsErrorHeapEnumInProgress;
  87. }
  88. else if(threadContext->IsInThreadServiceCallback())
  89. {
  90. return JsErrorInThreadServiceCallback;
  91. }
  92. ThreadContextScope scope(threadContext);
  93. if(!scope.IsValid())
  94. {
  95. return JsErrorWrongThread;
  96. }
  97. #if ENABLE_TTD
  98. TTD::NSLogEvents::EventLogEntry* createEvent = nullptr;
  99. if(activelyRecording)
  100. {
  101. createEvent = threadContext->TTDLog->RecordJsRTCreateScriptContext(_actionEntryPopper);
  102. }
  103. #endif
  104. JsrtContext * context = JsrtContext::New(runtime);
  105. #if ENABLE_TTD
  106. if(inRecordMode | inReplayMode)
  107. {
  108. Js::ScriptContext* scriptContext = context->GetScriptContext();
  109. HostScriptContextCallbackFunctor callbackFunctor(context, &JsrtContext::OnScriptLoad_TTDCallback);
  110. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  111. bool noNative = true;
  112. bool doDebug = true;
  113. #else
  114. bool noNative = TTD_FORCE_NOJIT_MODE || threadContext->TTDLog->IsDebugModeFlagSet();
  115. bool doDebug = TTD_FORCE_DEBUG_MODE || threadContext->TTDLog->IsDebugModeFlagSet();
  116. #endif
  117. threadContext->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionTTAction);
  118. if(inRecordMode)
  119. {
  120. threadContext->TTDContext->AddNewScriptContextRecord(context, scriptContext, callbackFunctor, noNative, doDebug);
  121. }
  122. else
  123. {
  124. threadContext->TTDContext->AddNewScriptContextReplay(context, scriptContext, callbackFunctor, noNative, doDebug);
  125. }
  126. threadContext->TTDLog->SetModeFlagsOnContext(scriptContext);
  127. threadContext->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionTTAction);
  128. }
  129. #endif
  130. JsrtDebugManager* jsrtDebugManager = runtime->GetJsrtDebugManager();
  131. if(jsrtDebugManager != nullptr)
  132. {
  133. Js::ScriptContext* scriptContext = context->GetScriptContext();
  134. scriptContext->InitializeDebugging();
  135. Js::DebugContext* debugContext = scriptContext->GetDebugContext();
  136. debugContext->SetHostDebugContext(jsrtDebugManager);
  137. Js::ProbeContainer* probeContainer = debugContext->GetProbeContainer();
  138. probeContainer->InitializeInlineBreakEngine(jsrtDebugManager);
  139. probeContainer->InitializeDebuggerScriptOptionCallback(jsrtDebugManager);
  140. threadContext->GetDebugManager()->SetLocalsDisplayFlags(Js::DebugManager::LocalsDisplayFlags::LocalsDisplayFlags_NoGroupMethods);
  141. }
  142. #if ENABLE_TTD
  143. if(activelyRecording)
  144. {
  145. threadContext->TTDLog->RecordJsRTCreateScriptContextResult(createEvent, context->GetScriptContext());
  146. }
  147. #endif
  148. *newContext = (JsContextRef)context;
  149. return JsNoError;
  150. }
  151. #if ENABLE_TTD
  152. void CALLBACK CreateExternalObject_TTDCallback(Js::ScriptContext* ctx, Js::Var* object)
  153. {
  154. TTDAssert(object != nullptr, "This should always be a valid location");
  155. *object = JsrtExternalObject::Create(nullptr, nullptr, ctx);
  156. }
  157. static void CALLBACK TTDDummyPromiseContinuationCallback(JsValueRef task, void *callbackState)
  158. {
  159. TTDAssert(false, "This should never actually be invoked!!!");
  160. }
  161. void CALLBACK CreateJsRTContext_TTDCallback(void* runtimeHandle, Js::ScriptContext** result)
  162. {
  163. JsContextRef newContext = nullptr;
  164. *result = nullptr;
  165. TTDRecorder dummyActionEntryPopper;
  166. JsErrorCode err = CreateContextCore(static_cast<JsRuntimeHandle>(runtimeHandle), dummyActionEntryPopper, false /*inRecordMode*/, false /*activelyRecording*/, true /*inReplayMode*/, &newContext);
  167. TTDAssert(err == JsNoError, "Shouldn't fail on us!!!");
  168. *result = static_cast<JsrtContext*>(newContext)->GetScriptContext();
  169. (*result)->GetLibrary()->SetNativeHostPromiseContinuationFunction((Js::JavascriptLibrary::PromiseContinuationCallback)TTDDummyPromiseContinuationCallback, nullptr);
  170. //To ensure we have a valid context active (when we next try and inflate into this context) set this as active by convention
  171. JsrtContext::TrySetCurrent(static_cast<JsrtContext*>(newContext));
  172. }
  173. void CALLBACK ReleaseJsRTContext_TTDCallback(FinalizableObject* jsrtCtx)
  174. {
  175. static_cast<JsrtContext*>(jsrtCtx)->GetScriptContext()->GetThreadContext()->GetRecycler()->RootRelease(jsrtCtx);
  176. JsrtContext::OnReplayDisposeContext_TTDCallback(jsrtCtx);
  177. }
  178. void CALLBACK SetActiveJsRTContext_TTDCallback(void* runtimeHandle, Js::ScriptContext* ctx)
  179. {
  180. JsrtRuntime * runtime = JsrtRuntime::FromHandle(static_cast<JsRuntimeHandle>(runtimeHandle));
  181. ThreadContext * threadContext = runtime->GetThreadContext();
  182. threadContext->TTDContext->SetActiveScriptContext(ctx);
  183. JsrtContext* runtimeCtx = (JsrtContext*)threadContext->TTDContext->GetRuntimeContextForScriptContext(ctx);
  184. JsrtContext::TrySetCurrent(runtimeCtx);
  185. }
  186. #endif
  187. //A create runtime function that we can funnel to for regular and record or debug aware creation
  188. JsErrorCode CreateRuntimeCore(_In_ JsRuntimeAttributes attributes,
  189. _In_opt_ const byte* optTTUri, size_t optTTUriCount, bool isRecord, bool isReplay, bool isDebug,
  190. _In_ UINT32 snapInterval, _In_ UINT32 snapHistoryLength,
  191. _In_opt_ JsTTDInitializeForWriteLogStreamCallback writeInitializeFunction,
  192. _In_opt_ TTDOpenResourceStreamCallback openResourceStream, _In_opt_ JsTTDReadBytesFromStreamCallback readBytesFromStream,
  193. _In_opt_ JsTTDWriteBytesToStreamCallback writeBytesToStream, _In_opt_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
  194. _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtimeHandle)
  195. {
  196. VALIDATE_ENTER_CURRENT_THREAD();
  197. PARAM_NOT_NULL(runtimeHandle);
  198. *runtimeHandle = nullptr;
  199. JsErrorCode runtimeResult = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  200. const JsRuntimeAttributes JsRuntimeAttributesAll =
  201. (JsRuntimeAttributes)(
  202. JsRuntimeAttributeDisableBackgroundWork |
  203. JsRuntimeAttributeAllowScriptInterrupt |
  204. JsRuntimeAttributeEnableIdleProcessing |
  205. JsRuntimeAttributeDisableEval |
  206. JsRuntimeAttributeDisableNativeCodeGeneration |
  207. JsRuntimeAttributeEnableExperimentalFeatures |
  208. JsRuntimeAttributeDispatchSetExceptionsToDebugger
  209. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  210. | JsRuntimeAttributeSerializeLibraryByteCode
  211. #endif
  212. );
  213. Assert((attributes & ~JsRuntimeAttributesAll) == 0);
  214. if ((attributes & ~JsRuntimeAttributesAll) != 0)
  215. {
  216. return JsErrorInvalidArgument;
  217. }
  218. CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 0, nullptr);
  219. AllocationPolicyManager * policyManager = HeapNew(AllocationPolicyManager, (attributes & JsRuntimeAttributeDisableBackgroundWork) == 0);
  220. bool enableExperimentalFeatures = (attributes & JsRuntimeAttributeEnableExperimentalFeatures) != 0;
  221. ThreadContext * threadContext = HeapNew(ThreadContext, policyManager, threadService, enableExperimentalFeatures);
  222. if (((attributes & JsRuntimeAttributeDisableBackgroundWork) != 0)
  223. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  224. && !Js::Configuration::Global.flags.ConcurrentRuntime
  225. #endif
  226. )
  227. {
  228. threadContext->OptimizeForManyInstances(true);
  229. #if ENABLE_NATIVE_CODEGEN
  230. threadContext->EnableBgJit(false);
  231. #endif
  232. }
  233. if (!threadContext->IsRentalThreadingEnabledInJSRT()
  234. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  235. || Js::Configuration::Global.flags.DisableRentalThreading
  236. #endif
  237. )
  238. {
  239. threadContext->SetIsThreadBound();
  240. }
  241. if (attributes & JsRuntimeAttributeAllowScriptInterrupt)
  242. {
  243. threadContext->SetThreadContextFlag(ThreadContextFlagCanDisableExecution);
  244. }
  245. if (attributes & JsRuntimeAttributeDisableEval)
  246. {
  247. threadContext->SetThreadContextFlag(ThreadContextFlagEvalDisabled);
  248. }
  249. if (attributes & JsRuntimeAttributeDisableNativeCodeGeneration)
  250. {
  251. threadContext->SetThreadContextFlag(ThreadContextFlagNoJIT);
  252. }
  253. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  254. if (Js::Configuration::Global.flags.PrimeRecycler)
  255. {
  256. threadContext->EnsureRecycler()->Prime();
  257. }
  258. #endif
  259. bool enableIdle = (attributes & JsRuntimeAttributeEnableIdleProcessing) == JsRuntimeAttributeEnableIdleProcessing;
  260. bool dispatchExceptions = (attributes & JsRuntimeAttributeDispatchSetExceptionsToDebugger) == JsRuntimeAttributeDispatchSetExceptionsToDebugger;
  261. JsrtRuntime * runtime = HeapNew(JsrtRuntime, threadContext, enableIdle, dispatchExceptions);
  262. threadContext->SetCurrentThreadId(ThreadContext::NoThread);
  263. *runtimeHandle = runtime->ToHandle();
  264. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  265. runtime->SetSerializeByteCodeForLibrary((attributes & JsRuntimeAttributeSerializeLibraryByteCode) != 0);
  266. #endif
  267. return JsNoError;
  268. });
  269. #if ENABLE_TTD
  270. if(runtimeResult != JsNoError)
  271. {
  272. return runtimeResult;
  273. }
  274. if(isRecord | isReplay | isDebug)
  275. {
  276. ThreadContext* threadContext = JsrtRuntime::FromHandle(*runtimeHandle)->GetThreadContext();
  277. if(isRecord && isReplay)
  278. {
  279. return JsErrorInvalidArgument; //A runtime can only be in 1 mode
  280. }
  281. if(isDebug && !isReplay)
  282. {
  283. return JsErrorInvalidArgument; //A debug runtime also needs to be in runtime mode (and we are going to be strict about it)
  284. }
  285. if(optTTUri == nullptr)
  286. {
  287. return JsErrorInvalidArgument; //We must have a location to store data into
  288. }
  289. runtimeResult = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  290. //Make sure the thread context recycler is allocated before we do anything else
  291. ThreadContextScope scope(threadContext);
  292. threadContext->EnsureRecycler();
  293. threadContext->InitTimeTravel(threadContext, *runtimeHandle, optTTUriCount, optTTUri, snapInterval, max<uint32>(2, snapHistoryLength));
  294. threadContext->InitHostFunctionsAndTTData(isRecord, isReplay, isDebug,
  295. writeInitializeFunction, openResourceStream, readBytesFromStream, writeBytesToStream, flushAndCloseStream,
  296. &CreateExternalObject_TTDCallback, &CreateJsRTContext_TTDCallback, &ReleaseJsRTContext_TTDCallback, &SetActiveJsRTContext_TTDCallback);
  297. return JsNoError;
  298. });
  299. }
  300. #endif
  301. return runtimeResult;
  302. }
  303. /////////////////////
  304. CHAKRA_API JsCreateRuntime(_In_ JsRuntimeAttributes attributes, _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtimeHandle)
  305. {
  306. return CreateRuntimeCore(attributes,
  307. nullptr /*optRecordUri*/, 0 /*optRecordUriCount */, false /*isRecord*/, false /*isReplay*/, false /*isDebug*/,
  308. UINT_MAX /*optSnapInterval*/, UINT_MAX /*optLogLength*/,
  309. nullptr, nullptr, nullptr, nullptr, nullptr, /*TTD IO handlers*/
  310. threadService, runtimeHandle);
  311. }
  312. template <CollectionFlags flags>
  313. JsErrorCode JsCollectGarbageCommon(JsRuntimeHandle runtimeHandle)
  314. {
  315. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  316. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  317. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  318. if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
  319. {
  320. return JsErrorHeapEnumInProgress;
  321. }
  322. else if (threadContext->IsInThreadServiceCallback())
  323. {
  324. return JsErrorInThreadServiceCallback;
  325. }
  326. ThreadContextScope scope(threadContext);
  327. if (!scope.IsValid())
  328. {
  329. return JsErrorWrongThread;
  330. }
  331. Recycler* recycler = threadContext->EnsureRecycler();
  332. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  333. if (flags & CollectOverride_SkipStack)
  334. {
  335. Recycler::AutoEnterExternalStackSkippingGCMode autoGC(recycler);
  336. recycler->CollectNow<flags>();
  337. }
  338. else
  339. #endif
  340. {
  341. recycler->CollectNow<flags>();
  342. }
  343. return JsNoError;
  344. });
  345. }
  346. CHAKRA_API JsCollectGarbage(_In_ JsRuntimeHandle runtimeHandle)
  347. {
  348. return JsCollectGarbageCommon<CollectNowExhaustive>(runtimeHandle);
  349. }
  350. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  351. CHAKRA_API JsPrivateCollectGarbageSkipStack(_In_ JsRuntimeHandle runtimeHandle)
  352. {
  353. return JsCollectGarbageCommon<CollectNowExhaustiveSkipStack>(runtimeHandle);
  354. }
  355. #endif
  356. CHAKRA_API JsDisposeRuntime(_In_ JsRuntimeHandle runtimeHandle)
  357. {
  358. return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode {
  359. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  360. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  361. ThreadContext * threadContext = runtime->GetThreadContext();
  362. ThreadContextScope scope(threadContext);
  363. // We should not dispose if the runtime is being used.
  364. if (!scope.IsValid() ||
  365. scope.WasInUse() ||
  366. (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress()))
  367. {
  368. return JsErrorRuntimeInUse;
  369. }
  370. else if (threadContext->IsInThreadServiceCallback())
  371. {
  372. return JsErrorInThreadServiceCallback;
  373. }
  374. // Invoke and clear the callbacks while the contexts and runtime are still available
  375. {
  376. Recycler* recycler = threadContext->GetRecycler();
  377. if (recycler != nullptr)
  378. {
  379. recycler->ClearObjectBeforeCollectCallbacks();
  380. }
  381. }
  382. if (runtime->GetJsrtDebugManager() != nullptr)
  383. {
  384. runtime->GetJsrtDebugManager()->ClearDebuggerObjects();
  385. }
  386. // Close any open Contexts.
  387. // We need to do this before recycler shutdown, because ScriptEngine->Close won't work then.
  388. runtime->CloseContexts();
  389. runtime->DeleteJsrtDebugManager();
  390. #if defined(CHECK_MEMORY_LEAK) || defined(LEAK_REPORT)
  391. bool doFinalGC = false;
  392. #if defined(LEAK_REPORT)
  393. if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
  394. {
  395. doFinalGC = true;
  396. }
  397. #endif
  398. #if defined(CHECK_MEMORY_LEAK)
  399. if (Js::Configuration::Global.flags.CheckMemoryLeak)
  400. {
  401. doFinalGC = true;
  402. }
  403. #endif
  404. if (doFinalGC)
  405. {
  406. Recycler *recycler = threadContext->GetRecycler();
  407. if (recycler)
  408. {
  409. recycler->EnsureNotCollecting();
  410. recycler->CollectNow<CollectNowFinalGC>();
  411. Assert(!recycler->CollectionInProgress());
  412. }
  413. }
  414. #endif
  415. runtime->SetBeforeCollectCallback(nullptr, nullptr);
  416. threadContext->CloseForJSRT();
  417. HeapDelete(threadContext);
  418. HeapDelete(runtime);
  419. scope.Invalidate();
  420. return JsNoError;
  421. });
  422. }
  423. CHAKRA_API JsAddRef(_In_ JsRef ref, _Out_opt_ unsigned int *count)
  424. {
  425. VALIDATE_JSREF(ref);
  426. if (count != nullptr)
  427. {
  428. *count = 0;
  429. }
  430. if (Js::TaggedNumber::Is(ref))
  431. {
  432. // The count is always one because these are never collected
  433. if (count)
  434. {
  435. *count = 1;
  436. }
  437. return JsNoError;
  438. }
  439. if (JsrtContext::Is(ref))
  440. {
  441. return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode
  442. {
  443. Recycler * recycler = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext()->GetRecycler();
  444. recycler->RootAddRef(ref, count);
  445. return JsNoError;
  446. });
  447. }
  448. else
  449. {
  450. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  451. if (threadContext == nullptr)
  452. {
  453. return JsErrorNoCurrentContext;
  454. }
  455. Recycler * recycler = threadContext->GetRecycler();
  456. return GlobalAPIWrapper([&] (TTDRecorder& _actionEntryPopper) -> JsErrorCode
  457. {
  458. // Note, some references may live in arena-allocated memory, so we need to do this check
  459. if (!recycler->IsValidObject(ref))
  460. {
  461. return JsNoError;
  462. }
  463. #if ENABLE_TTD
  464. unsigned int lCount = 0;
  465. recycler->RootAddRef(ref, &lCount);
  466. if (count != nullptr)
  467. {
  468. *count = lCount;
  469. }
  470. if((lCount == 1) && (threadContext->IsRuntimeInTTDMode()) && (!threadContext->TTDLog->IsPropertyRecordRef(ref)))
  471. {
  472. Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(ref);
  473. if(obj->GetScriptContext()->IsTTDRecordModeEnabled() && !TTD::ThreadContextTTD::IsSpecialRootObject(obj))
  474. {
  475. if(obj->GetScriptContext()->ShouldPerformRecordAction())
  476. {
  477. threadContext->TTDLog->RecordJsRTAddRootRef(_actionEntryPopper, (Js::Var)ref);
  478. }
  479. threadContext->TTDContext->AddTrackedRootGeneral(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(obj), obj);
  480. }
  481. }
  482. #else
  483. recycler->RootAddRef(ref, count);
  484. #endif
  485. return JsNoError;
  486. });
  487. }
  488. }
  489. CHAKRA_API JsRelease(_In_ JsRef ref, _Out_opt_ unsigned int *count)
  490. {
  491. VALIDATE_JSREF(ref);
  492. if (count != nullptr)
  493. {
  494. *count = 0;
  495. }
  496. if (Js::TaggedNumber::Is(ref))
  497. {
  498. // The count is always one because these are never collected
  499. if (count)
  500. {
  501. *count = 1;
  502. }
  503. return JsNoError;
  504. }
  505. if (JsrtContext::Is(ref))
  506. {
  507. return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode
  508. {
  509. Recycler * recycler = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext()->GetRecycler();
  510. recycler->RootRelease(ref, count);
  511. return JsNoError;
  512. });
  513. }
  514. else
  515. {
  516. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  517. if (threadContext == nullptr)
  518. {
  519. return JsErrorNoCurrentContext;
  520. }
  521. Recycler * recycler = threadContext->GetRecycler();
  522. return GlobalAPIWrapper([&](TTDRecorder& _actionEntryPopper) -> JsErrorCode
  523. {
  524. // Note, some references may live in arena-allocated memory, so we need to do this check
  525. if (!recycler->IsValidObject(ref))
  526. {
  527. return JsNoError;
  528. }
  529. #if ENABLE_TTD
  530. unsigned int lCount = 0;
  531. recycler->RootRelease(ref, &lCount);
  532. if (count != nullptr)
  533. {
  534. *count = lCount;
  535. }
  536. if((lCount == 0) && (threadContext->IsRuntimeInTTDMode()) && (!threadContext->TTDLog->IsPropertyRecordRef(ref)))
  537. {
  538. Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(ref);
  539. if(obj->GetScriptContext()->IsTTDRecordModeEnabled() && !TTD::ThreadContextTTD::IsSpecialRootObject(obj))
  540. {
  541. if(obj->GetScriptContext()->ShouldPerformRecordAction())
  542. {
  543. threadContext->TTDLog->RecordJsRTRemoveRootRef(_actionEntryPopper, (Js::Var)ref);
  544. }
  545. threadContext->TTDContext->RemoveTrackedRootGeneral(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(obj), obj);
  546. }
  547. }
  548. #else
  549. recycler->RootRelease(ref, count);
  550. #endif
  551. return JsNoError;
  552. });
  553. }
  554. }
  555. CHAKRA_API JsSetObjectBeforeCollectCallback(_In_ JsRef ref, _In_opt_ void *callbackState, _In_ JsObjectBeforeCollectCallback objectBeforeCollectCallback)
  556. {
  557. VALIDATE_JSREF(ref);
  558. if (Js::TaggedNumber::Is(ref))
  559. {
  560. return JsErrorInvalidArgument;
  561. }
  562. if (JsrtContext::Is(ref))
  563. {
  564. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  565. {
  566. ThreadContext* threadContext = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext();
  567. Recycler * recycler = threadContext->GetRecycler();
  568. recycler->SetObjectBeforeCollectCallback(ref, reinterpret_cast<Recycler::ObjectBeforeCollectCallback>(objectBeforeCollectCallback), callbackState,
  569. reinterpret_cast<Recycler::ObjectBeforeCollectCallbackWrapper>(JsrtCallbackState::ObjectBeforeCallectCallbackWrapper), threadContext);
  570. return JsNoError;
  571. });
  572. }
  573. else
  574. {
  575. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  576. if (threadContext == nullptr)
  577. {
  578. return JsErrorNoCurrentContext;
  579. }
  580. Recycler * recycler = threadContext->GetRecycler();
  581. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  582. {
  583. if (!recycler->IsValidObject(ref))
  584. {
  585. return JsErrorInvalidArgument;
  586. }
  587. recycler->SetObjectBeforeCollectCallback(ref, reinterpret_cast<Recycler::ObjectBeforeCollectCallback>(objectBeforeCollectCallback), callbackState,
  588. reinterpret_cast<Recycler::ObjectBeforeCollectCallbackWrapper>(JsrtCallbackState::ObjectBeforeCallectCallbackWrapper), threadContext);
  589. return JsNoError;
  590. });
  591. }
  592. }
  593. CHAKRA_API JsCreateContext(_In_ JsRuntimeHandle runtimeHandle, _Out_ JsContextRef *newContext)
  594. {
  595. return GlobalAPIWrapper([&](TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  596. PARAM_NOT_NULL(newContext);
  597. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  598. bool inRecord = false;
  599. bool activelyRecording = false;
  600. bool inReplay = false;
  601. #if ENABLE_TTD
  602. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  603. ThreadContext * threadContext = runtime->GetThreadContext();
  604. if(threadContext->IsRuntimeInTTDMode() && threadContext->TTDContext->GetActiveScriptContext() != nullptr)
  605. {
  606. Js::ScriptContext* currentCtx = threadContext->TTDContext->GetActiveScriptContext();
  607. inRecord = currentCtx->IsTTDRecordModeEnabled();
  608. activelyRecording = currentCtx->ShouldPerformRecordAction();
  609. inReplay = currentCtx->IsTTDReplayModeEnabled();
  610. }
  611. #endif
  612. return CreateContextCore(runtimeHandle, _actionEntryPopper, inRecord, activelyRecording, inReplay, newContext);
  613. });
  614. }
  615. CHAKRA_API JsGetCurrentContext(_Out_ JsContextRef *currentContext)
  616. {
  617. PARAM_NOT_NULL(currentContext);
  618. BEGIN_JSRT_NO_EXCEPTION
  619. {
  620. *currentContext = (JsContextRef)JsrtContext::GetCurrent();
  621. }
  622. END_JSRT_NO_EXCEPTION
  623. }
  624. CHAKRA_API JsSetCurrentContext(_In_ JsContextRef newContext)
  625. {
  626. VALIDATE_ENTER_CURRENT_THREAD();
  627. return GlobalAPIWrapper([&] (TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  628. JsrtContext *currentContext = JsrtContext::GetCurrent();
  629. Recycler* recycler = currentContext != nullptr ? currentContext->GetScriptContext()->GetRecycler() : nullptr;
  630. #if ENABLE_TTD
  631. Js::ScriptContext* newScriptContext = newContext != nullptr ? static_cast<JsrtContext*>(newContext)->GetScriptContext() : nullptr;
  632. if(newScriptContext == nullptr)
  633. {
  634. Js::ScriptContext* oldScriptContext = currentContext != nullptr ? static_cast<JsrtContext*>(currentContext)->GetScriptContext() : nullptr;
  635. if(currentContext != nullptr && oldScriptContext->IsTTDRecordModeEnabled())
  636. {
  637. if(oldScriptContext->ShouldPerformRecordAction())
  638. {
  639. oldScriptContext->GetThreadContext()->TTDLog->RecordJsRTSetCurrentContext(_actionEntryPopper, nullptr);
  640. }
  641. oldScriptContext->GetThreadContext()->TTDContext->SetActiveScriptContext(nullptr);
  642. }
  643. }
  644. else
  645. {
  646. if(newScriptContext->IsTTDRecordModeEnabled())
  647. {
  648. if(newScriptContext->ShouldPerformRecordAction())
  649. {
  650. newScriptContext->GetThreadContext()->TTDLog->RecordJsRTSetCurrentContext(_actionEntryPopper, newScriptContext->GetGlobalObject());
  651. }
  652. newScriptContext->GetThreadContext()->TTDContext->SetActiveScriptContext(newScriptContext);
  653. }
  654. }
  655. #endif
  656. if (currentContext && recycler->IsHeapEnumInProgress())
  657. {
  658. return JsErrorHeapEnumInProgress;
  659. }
  660. else if (currentContext && currentContext->GetRuntime()->GetThreadContext()->IsInThreadServiceCallback())
  661. {
  662. return JsErrorInThreadServiceCallback;
  663. }
  664. if (!JsrtContext::TrySetCurrent((JsrtContext *)newContext))
  665. {
  666. return JsErrorWrongThread;
  667. }
  668. return JsNoError;
  669. });
  670. }
  671. CHAKRA_API JsGetContextOfObject(_In_ JsValueRef object, _Out_ JsContextRef *context)
  672. {
  673. VALIDATE_JSREF(object);
  674. PARAM_NOT_NULL(context);
  675. BEGIN_JSRT_NO_EXCEPTION
  676. {
  677. if (!Js::RecyclableObject::Is(object))
  678. {
  679. RETURN_NO_EXCEPTION(JsErrorArgumentNotObject);
  680. }
  681. Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(object);
  682. *context = (JsContextRef)obj->GetScriptContext()->GetLibrary()->GetPinnedJsrtContextObject();
  683. }
  684. END_JSRT_NO_EXCEPTION
  685. }
  686. CHAKRA_API JsGetContextData(_In_ JsContextRef context, _Out_ void **data)
  687. {
  688. VALIDATE_JSREF(context);
  689. PARAM_NOT_NULL(data);
  690. BEGIN_JSRT_NO_EXCEPTION
  691. {
  692. if (!JsrtContext::Is(context))
  693. {
  694. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  695. }
  696. *data = static_cast<JsrtContext *>(context)->GetExternalData();
  697. }
  698. END_JSRT_NO_EXCEPTION
  699. }
  700. CHAKRA_API JsSetContextData(_In_ JsContextRef context, _In_ void *data)
  701. {
  702. VALIDATE_JSREF(context);
  703. BEGIN_JSRT_NO_EXCEPTION
  704. {
  705. if (!JsrtContext::Is(context))
  706. {
  707. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  708. }
  709. static_cast<JsrtContext *>(context)->SetExternalData(data);
  710. }
  711. END_JSRT_NO_EXCEPTION
  712. }
  713. void HandleScriptCompileError(Js::ScriptContext * scriptContext, CompileScriptException * se)
  714. {
  715. HRESULT hr = se->ei.scode;
  716. if (hr == E_OUTOFMEMORY || hr == VBSERR_OutOfMemory || hr == VBSERR_OutOfStack || hr == ERRnoMemory)
  717. {
  718. Js::Throw::OutOfMemory();
  719. }
  720. Js::JavascriptError* error = Js::JavascriptError::CreateFromCompileScriptException(scriptContext, se);
  721. Js::JavascriptExceptionObject * exceptionObject = RecyclerNew(scriptContext->GetRecycler(),
  722. Js::JavascriptExceptionObject, error, scriptContext, nullptr);
  723. scriptContext->GetThreadContext()->SetRecordedException(exceptionObject);
  724. }
  725. CHAKRA_API JsGetUndefinedValue(_Out_ JsValueRef *undefinedValue)
  726. {
  727. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
  728. PARAM_NOT_NULL(undefinedValue);
  729. *undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  730. return JsNoError;
  731. },
  732. /*allowInObjectBeforeCollectCallback*/true);
  733. }
  734. CHAKRA_API JsGetNullValue(_Out_ JsValueRef *nullValue)
  735. {
  736. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
  737. PARAM_NOT_NULL(nullValue);
  738. *nullValue = scriptContext->GetLibrary()->GetNull();
  739. return JsNoError;
  740. },
  741. /*allowInObjectBeforeCollectCallback*/true);
  742. }
  743. CHAKRA_API JsGetTrueValue(_Out_ JsValueRef *trueValue)
  744. {
  745. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
  746. PARAM_NOT_NULL(trueValue);
  747. *trueValue = scriptContext->GetLibrary()->GetTrue();
  748. return JsNoError;
  749. },
  750. /*allowInObjectBeforeCollectCallback*/true);
  751. }
  752. CHAKRA_API JsGetFalseValue(_Out_ JsValueRef *falseValue)
  753. {
  754. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
  755. PARAM_NOT_NULL(falseValue);
  756. *falseValue = scriptContext->GetLibrary()->GetFalse();
  757. return JsNoError;
  758. },
  759. /*allowInObjectBeforeCollectCallback*/true);
  760. }
  761. CHAKRA_API JsBoolToBoolean(_In_ bool value, _Out_ JsValueRef *booleanValue)
  762. {
  763. return ContextAPINoScriptWrapper([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  764. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateBoolean, value);
  765. PARAM_NOT_NULL(booleanValue);
  766. *booleanValue = value ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse();
  767. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, booleanValue);
  768. return JsNoError;
  769. },
  770. /*allowInObjectBeforeCollectCallback*/true);
  771. }
  772. CHAKRA_API JsBooleanToBool(_In_ JsValueRef value, _Out_ bool *boolValue)
  773. {
  774. VALIDATE_JSREF(value);
  775. PARAM_NOT_NULL(boolValue);
  776. BEGIN_JSRT_NO_EXCEPTION
  777. {
  778. if (!Js::JavascriptBoolean::Is(value))
  779. {
  780. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  781. }
  782. *boolValue = Js::JavascriptBoolean::FromVar(value)->GetValue() ? true : false;
  783. }
  784. END_JSRT_NO_EXCEPTION
  785. }
  786. CHAKRA_API JsConvertValueToBoolean(_In_ JsValueRef value, _Out_ JsValueRef *result)
  787. {
  788. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  789. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToBooleanConversion, (Js::Var)value);
  790. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  791. PARAM_NOT_NULL(result);
  792. if (Js::JavascriptConversion::ToBool((Js::Var)value, scriptContext))
  793. {
  794. *result = scriptContext->GetLibrary()->GetTrue();
  795. }
  796. else
  797. {
  798. *result = scriptContext->GetLibrary()->GetFalse();
  799. }
  800. //It is either true or false which we always track so no need to store result identity
  801. return JsNoError;
  802. });
  803. }
  804. CHAKRA_API JsGetValueType(_In_ JsValueRef value, _Out_ JsValueType *type)
  805. {
  806. VALIDATE_JSREF(value);
  807. PARAM_NOT_NULL(type);
  808. BEGIN_JSRT_NO_EXCEPTION
  809. {
  810. Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(value);
  811. switch (typeId)
  812. {
  813. case Js::TypeIds_Undefined:
  814. *type = JsUndefined;
  815. break;
  816. case Js::TypeIds_Null:
  817. *type = JsNull;
  818. break;
  819. case Js::TypeIds_Boolean:
  820. *type = JsBoolean;
  821. break;
  822. case Js::TypeIds_Integer:
  823. case Js::TypeIds_Number:
  824. case Js::TypeIds_Int64Number:
  825. case Js::TypeIds_UInt64Number:
  826. *type = JsNumber;
  827. break;
  828. case Js::TypeIds_String:
  829. *type = JsString;
  830. break;
  831. case Js::TypeIds_Function:
  832. *type = JsFunction;
  833. break;
  834. case Js::TypeIds_Error:
  835. *type = JsError;
  836. break;
  837. case Js::TypeIds_Array:
  838. case Js::TypeIds_NativeIntArray:
  839. #if ENABLE_COPYONACCESS_ARRAY
  840. case Js::TypeIds_CopyOnAccessNativeIntArray:
  841. #endif
  842. case Js::TypeIds_NativeFloatArray:
  843. case Js::TypeIds_ES5Array:
  844. *type = JsArray;
  845. break;
  846. case Js::TypeIds_Symbol:
  847. *type = JsSymbol;
  848. break;
  849. case Js::TypeIds_ArrayBuffer:
  850. *type = JsArrayBuffer;
  851. break;
  852. case Js::TypeIds_DataView:
  853. *type = JsDataView;
  854. break;
  855. default:
  856. if (Js::TypedArrayBase::Is(typeId))
  857. {
  858. *type = JsTypedArray;
  859. }
  860. else
  861. {
  862. *type = JsObject;
  863. }
  864. break;
  865. }
  866. }
  867. END_JSRT_NO_EXCEPTION
  868. }
  869. CHAKRA_API JsDoubleToNumber(_In_ double dbl, _Out_ JsValueRef *asValue)
  870. {
  871. PARAM_NOT_NULL(asValue);
  872. //If number is not heap allocated then we don't need to record/track the creation for time-travel
  873. if (Js::JavascriptNumber::TryToVarFastWithCheck(dbl, asValue))
  874. {
  875. return JsNoError;
  876. }
  877. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  878. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateNumber, dbl);
  879. *asValue = Js::JavascriptNumber::ToVarNoCheck(dbl, scriptContext);
  880. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, asValue);
  881. return JsNoError;
  882. });
  883. }
  884. CHAKRA_API JsIntToNumber(_In_ int intValue, _Out_ JsValueRef *asValue)
  885. {
  886. PARAM_NOT_NULL(asValue);
  887. //If number is not heap allocated then we don't need to record/track the creation for time-travel
  888. if (Js::JavascriptNumber::TryToVarFast(intValue, asValue))
  889. {
  890. return JsNoError;
  891. }
  892. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  893. #if !INT32VAR
  894. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateInteger, intValue);
  895. #endif
  896. *asValue = Js::JavascriptNumber::ToVar(intValue, scriptContext);
  897. #if !INT32VAR
  898. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, asValue);
  899. #endif
  900. return JsNoError;
  901. });
  902. }
  903. CHAKRA_API JsNumberToDouble(_In_ JsValueRef value, _Out_ double *asDouble)
  904. {
  905. VALIDATE_JSREF(value);
  906. PARAM_NOT_NULL(asDouble);
  907. BEGIN_JSRT_NO_EXCEPTION
  908. {
  909. if (Js::TaggedInt::Is(value))
  910. {
  911. *asDouble = Js::TaggedInt::ToDouble(value);
  912. }
  913. else if (Js::JavascriptNumber::Is_NoTaggedIntCheck(value))
  914. {
  915. *asDouble = Js::JavascriptNumber::GetValue(value);
  916. }
  917. else
  918. {
  919. *asDouble = 0;
  920. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  921. }
  922. }
  923. END_JSRT_NO_EXCEPTION
  924. }
  925. CHAKRA_API JsNumberToInt(_In_ JsValueRef value, _Out_ int *asInt)
  926. {
  927. VALIDATE_JSREF(value);
  928. PARAM_NOT_NULL(asInt);
  929. BEGIN_JSRT_NO_EXCEPTION
  930. {
  931. if (Js::TaggedInt::Is(value))
  932. {
  933. *asInt = Js::TaggedInt::ToInt32(value);
  934. }
  935. else if (Js::JavascriptNumber::Is_NoTaggedIntCheck(value))
  936. {
  937. *asInt = Js::JavascriptConversion::ToInt32(Js::JavascriptNumber::GetValue(value));
  938. }
  939. else
  940. {
  941. *asInt = 0;
  942. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  943. }
  944. }
  945. END_JSRT_NO_EXCEPTION
  946. }
  947. CHAKRA_API JsConvertValueToNumber(_In_ JsValueRef value, _Out_ JsValueRef *result)
  948. {
  949. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  950. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToNumberConversion, (Js::Var)value);
  951. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  952. PARAM_NOT_NULL(result);
  953. *result = (JsValueRef)Js::JavascriptOperators::ToNumber((Js::Var)value, scriptContext);
  954. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  955. return JsNoError;
  956. });
  957. }
  958. CHAKRA_API JsGetStringLength(_In_ JsValueRef value, _Out_ int *length)
  959. {
  960. VALIDATE_JSREF(value);
  961. PARAM_NOT_NULL(length);
  962. BEGIN_JSRT_NO_EXCEPTION
  963. {
  964. if (!Js::JavascriptString::Is(value))
  965. {
  966. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  967. }
  968. *length = Js::JavascriptString::FromVar(value)->GetLengthAsSignedInt();
  969. }
  970. END_JSRT_NO_EXCEPTION
  971. }
  972. CHAKRA_API JsPointerToString(_In_reads_(stringLength) const WCHAR *stringValue, _In_ size_t stringLength, _Out_ JsValueRef *string)
  973. {
  974. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  975. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateString, stringValue, stringLength);
  976. PARAM_NOT_NULL(stringValue);
  977. PARAM_NOT_NULL(string);
  978. if (!Js::IsValidCharCount(stringLength))
  979. {
  980. Js::JavascriptError::ThrowOutOfMemoryError(scriptContext);
  981. }
  982. *string = Js::JavascriptString::NewCopyBuffer(stringValue, static_cast<charcount_t>(stringLength), scriptContext);
  983. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, string);
  984. return JsNoError;
  985. });
  986. }
  987. // TODO: The annotation of stringPtr is wrong. Need to fix definition in chakrart.h
  988. // The warning is '*stringPtr' could be '0' : this does not adhere to the specification for the function 'JsStringToPointer'.
  989. #pragma warning(suppress:6387)
  990. CHAKRA_API JsStringToPointer(_In_ JsValueRef stringValue, _Outptr_result_buffer_(*stringLength) const WCHAR **stringPtr, _Out_ size_t *stringLength)
  991. {
  992. VALIDATE_JSREF(stringValue);
  993. PARAM_NOT_NULL(stringPtr);
  994. *stringPtr = nullptr;
  995. PARAM_NOT_NULL(stringLength);
  996. *stringLength = 0;
  997. if (!Js::JavascriptString::Is(stringValue))
  998. {
  999. return JsErrorInvalidArgument;
  1000. }
  1001. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  1002. Js::JavascriptString *jsString = Js::JavascriptString::FromVar(stringValue);
  1003. *stringPtr = jsString->GetSz();
  1004. *stringLength = jsString->GetLength();
  1005. return JsNoError;
  1006. });
  1007. }
  1008. CHAKRA_API JsConvertValueToString(_In_ JsValueRef value, _Out_ JsValueRef *result)
  1009. {
  1010. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1011. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToStringConversion, (Js::Var)value);
  1012. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1013. PARAM_NOT_NULL(result);
  1014. *result = nullptr;
  1015. *result = (JsValueRef) Js::JavascriptConversion::ToString((Js::Var)value, scriptContext);
  1016. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1017. return JsNoError;
  1018. });
  1019. }
  1020. CHAKRA_API JsGetGlobalObject(_Out_ JsValueRef *globalObject)
  1021. {
  1022. return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
  1023. PARAM_NOT_NULL(globalObject);
  1024. *globalObject = (JsValueRef)scriptContext->GetGlobalObject();
  1025. return JsNoError;
  1026. },
  1027. /*allowInObjectBeforeCollectCallback*/true);
  1028. }
  1029. CHAKRA_API JsCreateObject(_Out_ JsValueRef *object)
  1030. {
  1031. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1032. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateBasicObject);
  1033. PARAM_NOT_NULL(object);
  1034. *object = scriptContext->GetLibrary()->CreateObject();
  1035. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, object);
  1036. return JsNoError;
  1037. });
  1038. }
  1039. CHAKRA_API JsCreateExternalObject(_In_opt_ void *data, _In_opt_ JsFinalizeCallback finalizeCallback, _Out_ JsValueRef *object)
  1040. {
  1041. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1042. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateExternalObject);
  1043. PARAM_NOT_NULL(object);
  1044. *object = JsrtExternalObject::Create(data, finalizeCallback, scriptContext);
  1045. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, object);
  1046. return JsNoError;
  1047. });
  1048. }
  1049. CHAKRA_API JsConvertValueToObject(_In_ JsValueRef value, _Out_ JsValueRef *result)
  1050. {
  1051. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1052. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToObjectConversion, (Js::Var)value);
  1053. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1054. PARAM_NOT_NULL(result);
  1055. *result = (JsValueRef)Js::JavascriptOperators::ToObject((Js::Var)value, scriptContext);
  1056. Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
  1057. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1058. return JsNoError;
  1059. });
  1060. }
  1061. CHAKRA_API JsGetPrototype(_In_ JsValueRef object, _Out_ JsValueRef *prototypeObject)
  1062. {
  1063. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1064. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetPrototype, object);
  1065. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1066. PARAM_NOT_NULL(prototypeObject);
  1067. *prototypeObject = (JsValueRef)Js::JavascriptOperators::OP_GetPrototype(object, scriptContext);
  1068. Assert(*prototypeObject == nullptr || !Js::CrossSite::NeedMarshalVar(*prototypeObject, scriptContext));
  1069. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, prototypeObject);
  1070. return JsNoError;
  1071. });
  1072. }
  1073. CHAKRA_API JsSetPrototype(_In_ JsValueRef object, _In_ JsValueRef prototypeObject)
  1074. {
  1075. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1076. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetPrototype, object, prototypeObject);
  1077. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1078. VALIDATE_INCOMING_OBJECT_OR_NULL(prototypeObject, scriptContext);
  1079. // We're not allowed to set this.
  1080. if (object == scriptContext->GetLibrary()->GetObjectPrototype())
  1081. {
  1082. return JsErrorInvalidArgument;
  1083. }
  1084. Js::JavascriptObject::ChangePrototype(Js::RecyclableObject::FromVar(object), Js::RecyclableObject::FromVar(prototypeObject), true, scriptContext);
  1085. return JsNoError;
  1086. });
  1087. }
  1088. CHAKRA_API JsInstanceOf(_In_ JsValueRef object, _In_ JsValueRef constructor, _Out_ bool *result) {
  1089. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1090. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTInstanceOf, object, constructor);
  1091. VALIDATE_INCOMING_REFERENCE(object, scriptContext);
  1092. VALIDATE_INCOMING_REFERENCE(constructor, scriptContext);
  1093. PARAM_NOT_NULL(result);
  1094. *result = Js::RecyclableObject::FromVar(constructor)->HasInstance(object, scriptContext) ? true : false;
  1095. return JsNoError;
  1096. });
  1097. }
  1098. CHAKRA_API JsGetExtensionAllowed(_In_ JsValueRef object, _Out_ bool *value)
  1099. {
  1100. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1101. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1102. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1103. PARAM_NOT_NULL(value);
  1104. *value = nullptr;
  1105. *value = Js::RecyclableObject::FromVar(object)->IsExtensible() != 0;
  1106. return JsNoError;
  1107. });
  1108. }
  1109. CHAKRA_API JsPreventExtension(_In_ JsValueRef object)
  1110. {
  1111. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1112. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1113. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1114. Js::RecyclableObject::FromVar(object)->PreventExtensions();
  1115. return JsNoError;
  1116. });
  1117. }
  1118. CHAKRA_API JsGetProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *value)
  1119. {
  1120. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1121. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetProperty, (Js::PropertyRecord *)propertyId, object);
  1122. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1123. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1124. PARAM_NOT_NULL(value);
  1125. *value = nullptr;
  1126. *value = Js::JavascriptOperators::OP_GetProperty((Js::Var)object, ((Js::PropertyRecord *)propertyId)->GetPropertyId(), scriptContext);
  1127. Assert(*value == nullptr || !Js::CrossSite::NeedMarshalVar(*value, scriptContext));
  1128. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, value);
  1129. return JsNoError;
  1130. });
  1131. }
  1132. CHAKRA_API JsGetOwnPropertyDescriptor(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *propertyDescriptor)
  1133. {
  1134. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1135. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertyInfo, (Js::PropertyRecord *)propertyId, object);
  1136. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1137. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1138. PARAM_NOT_NULL(propertyDescriptor);
  1139. *propertyDescriptor = nullptr;
  1140. Js::PropertyDescriptor propertyDescriptorValue;
  1141. if (Js::JavascriptOperators::GetOwnPropertyDescriptor(Js::RecyclableObject::FromVar(object), ((Js::PropertyRecord *)propertyId)->GetPropertyId(), scriptContext, &propertyDescriptorValue))
  1142. {
  1143. *propertyDescriptor = Js::JavascriptOperators::FromPropertyDescriptor(propertyDescriptorValue, scriptContext);
  1144. }
  1145. else
  1146. {
  1147. *propertyDescriptor = scriptContext->GetLibrary()->GetUndefined();
  1148. }
  1149. Assert(*propertyDescriptor == nullptr || !Js::CrossSite::NeedMarshalVar(*propertyDescriptor, scriptContext));
  1150. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertyDescriptor);
  1151. return JsNoError;
  1152. });
  1153. }
  1154. CHAKRA_API JsGetOwnPropertyNames(_In_ JsValueRef object, _Out_ JsValueRef *propertyNames)
  1155. {
  1156. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1157. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertyNamesInfo, object);
  1158. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1159. PARAM_NOT_NULL(propertyNames);
  1160. *propertyNames = nullptr;
  1161. *propertyNames = Js::JavascriptOperators::GetOwnPropertyNames(object, scriptContext);
  1162. Assert(*propertyNames == nullptr || !Js::CrossSite::NeedMarshalVar(*propertyNames, scriptContext));
  1163. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertyNames);
  1164. return JsNoError;
  1165. });
  1166. }
  1167. CHAKRA_API JsGetOwnPropertySymbols(_In_ JsValueRef object, _Out_ JsValueRef *propertySymbols)
  1168. {
  1169. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1170. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertySymbolsInfo, object);
  1171. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1172. PARAM_NOT_NULL(propertySymbols);
  1173. *propertySymbols = Js::JavascriptOperators::GetOwnPropertySymbols(object, scriptContext);
  1174. Assert(*propertySymbols == nullptr || !Js::CrossSite::NeedMarshalVar(*propertySymbols, scriptContext));
  1175. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertySymbols);
  1176. return JsNoError;
  1177. });
  1178. }
  1179. CHAKRA_API JsSetProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _In_ JsValueRef value, _In_ bool useStrictRules)
  1180. {
  1181. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1182. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetProperty, object, (Js::PropertyRecord *)propertyId, value, useStrictRules);
  1183. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1184. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1185. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1186. Js::JavascriptOperators::OP_SetProperty(object, ((Js::PropertyRecord *)propertyId)->GetPropertyId(), value, scriptContext,
  1187. nullptr, useStrictRules ? Js::PropertyOperation_StrictMode : Js::PropertyOperation_None);
  1188. return JsNoError;
  1189. });
  1190. }
  1191. CHAKRA_API JsHasProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ bool *hasProperty)
  1192. {
  1193. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1194. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTHasProperty, (Js::PropertyRecord *)propertyId, object);
  1195. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1196. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1197. PARAM_NOT_NULL(hasProperty);
  1198. *hasProperty = nullptr;
  1199. *hasProperty = Js::JavascriptOperators::OP_HasProperty(object, ((Js::PropertyRecord *)propertyId)->GetPropertyId(), scriptContext) != 0;
  1200. return JsNoError;
  1201. });
  1202. }
  1203. CHAKRA_API JsDeleteProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _In_ bool useStrictRules, _Out_ JsValueRef *result)
  1204. {
  1205. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1206. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTDeleteProperty, object, (Js::PropertyRecord *)propertyId, useStrictRules);
  1207. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1208. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1209. PARAM_NOT_NULL(result);
  1210. *result = nullptr;
  1211. *result = Js::JavascriptOperators::OP_DeleteProperty((Js::Var)object, ((Js::PropertyRecord *)propertyId)->GetPropertyId(),
  1212. scriptContext, useStrictRules ? Js::PropertyOperation_StrictMode : Js::PropertyOperation_None);
  1213. Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
  1214. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1215. return JsNoError;
  1216. });
  1217. }
  1218. CHAKRA_API JsDefineProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _In_ JsValueRef propertyDescriptor, _Out_ bool *result)
  1219. {
  1220. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1221. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTDefineProperty, object, (Js::PropertyRecord *)propertyId, propertyDescriptor);
  1222. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1223. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1224. VALIDATE_INCOMING_OBJECT(propertyDescriptor, scriptContext);
  1225. PARAM_NOT_NULL(result);
  1226. *result = nullptr;
  1227. Js::PropertyDescriptor propertyDescriptorValue;
  1228. if (!Js::JavascriptOperators::ToPropertyDescriptor(propertyDescriptor, &propertyDescriptorValue, scriptContext))
  1229. {
  1230. return JsErrorInvalidArgument;
  1231. }
  1232. *result = Js::JavascriptOperators::DefineOwnPropertyDescriptor(
  1233. Js::RecyclableObject::FromVar(object), ((Js::PropertyRecord *)propertyId)->GetPropertyId(), propertyDescriptorValue,
  1234. true, scriptContext) != 0;
  1235. return JsNoError;
  1236. });
  1237. }
  1238. CHAKRA_API JsCreateArray(_In_ unsigned int length, _Out_ JsValueRef *result)
  1239. {
  1240. return ContextAPINoScriptWrapper([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1241. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateBasicArray, length);
  1242. PARAM_NOT_NULL(result);
  1243. *result = nullptr;
  1244. *result = scriptContext->GetLibrary()->CreateArray(length);
  1245. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1246. return JsNoError;
  1247. });
  1248. }
  1249. CHAKRA_API JsCreateArrayBuffer(_In_ unsigned int byteLength, _Out_ JsValueRef *result)
  1250. {
  1251. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1252. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateArrayBuffer, byteLength);
  1253. PARAM_NOT_NULL(result);
  1254. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1255. *result = library->CreateArrayBuffer(byteLength);
  1256. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1257. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1258. return JsNoError;
  1259. });
  1260. }
  1261. CHAKRA_API JsCreateExternalArrayBuffer(_Pre_maybenull_ _Pre_writable_byte_size_(byteLength) void *data, _In_ unsigned int byteLength,
  1262. _In_opt_ JsFinalizeCallback finalizeCallback, _In_opt_ void *callbackState, _Out_ JsValueRef *result)
  1263. {
  1264. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1265. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateExternalArrayBuffer, reinterpret_cast<BYTE*>(data), byteLength);
  1266. PARAM_NOT_NULL(result);
  1267. if (data == nullptr && byteLength > 0)
  1268. {
  1269. return JsErrorInvalidArgument;
  1270. }
  1271. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1272. *result = Js::JsrtExternalArrayBuffer::New(
  1273. reinterpret_cast<BYTE*>(data),
  1274. byteLength,
  1275. finalizeCallback,
  1276. callbackState,
  1277. library->GetArrayBufferType());
  1278. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1279. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1280. return JsNoError;
  1281. });
  1282. }
  1283. CHAKRA_API JsCreateTypedArray(_In_ JsTypedArrayType arrayType, _In_ JsValueRef baseArray, _In_ unsigned int byteOffset,
  1284. _In_ unsigned int elementLength, _Out_ JsValueRef *result)
  1285. {
  1286. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1287. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1288. if (baseArray != JS_INVALID_REFERENCE)
  1289. {
  1290. VALIDATE_INCOMING_REFERENCE(baseArray, scriptContext);
  1291. }
  1292. PARAM_NOT_NULL(result);
  1293. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1294. const bool fromArrayBuffer = (baseArray != JS_INVALID_REFERENCE && Js::ArrayBuffer::Is(baseArray));
  1295. if (byteOffset != 0 && !fromArrayBuffer)
  1296. {
  1297. return JsErrorInvalidArgument;
  1298. }
  1299. if (elementLength != 0 && !(baseArray == JS_INVALID_REFERENCE || fromArrayBuffer))
  1300. {
  1301. return JsErrorInvalidArgument;
  1302. }
  1303. Js::JavascriptFunction* constructorFunc = nullptr;
  1304. Js::Var values[4] =
  1305. {
  1306. library->GetUndefined(),
  1307. baseArray != nullptr ? baseArray : Js::JavascriptNumber::ToVar(elementLength, scriptContext)
  1308. };
  1309. if (fromArrayBuffer)
  1310. {
  1311. values[2] = Js::JavascriptNumber::ToVar(byteOffset, scriptContext);
  1312. values[3] = Js::JavascriptNumber::ToVar(elementLength, scriptContext);
  1313. }
  1314. Js::CallInfo info(Js::CallFlags_New, fromArrayBuffer ? 4 : 2);
  1315. Js::Arguments args(info, values);
  1316. switch (arrayType)
  1317. {
  1318. case JsArrayTypeInt8:
  1319. constructorFunc = library->GetInt8ArrayConstructor();
  1320. break;
  1321. case JsArrayTypeUint8:
  1322. constructorFunc = library->GetUint8ArrayConstructor();
  1323. break;
  1324. case JsArrayTypeUint8Clamped:
  1325. constructorFunc = library->GetUint8ClampedArrayConstructor();
  1326. break;
  1327. case JsArrayTypeInt16:
  1328. constructorFunc = library->GetInt16ArrayConstructor();
  1329. break;
  1330. case JsArrayTypeUint16:
  1331. constructorFunc = library->GetUint16ArrayConstructor();
  1332. break;
  1333. case JsArrayTypeInt32:
  1334. constructorFunc = library->GetInt32ArrayConstructor();
  1335. break;
  1336. case JsArrayTypeUint32:
  1337. constructorFunc = library->GetUint32ArrayConstructor();
  1338. break;
  1339. case JsArrayTypeFloat32:
  1340. constructorFunc = library->GetFloat32ArrayConstructor();
  1341. break;
  1342. case JsArrayTypeFloat64:
  1343. constructorFunc = library->GetFloat64ArrayConstructor();
  1344. break;
  1345. default:
  1346. return JsErrorInvalidArgument;
  1347. }
  1348. *result = Js::JavascriptFunction::CallAsConstructor(constructorFunc, /* overridingNewTarget = */nullptr, args, scriptContext);
  1349. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1350. return JsNoError;
  1351. });
  1352. }
  1353. CHAKRA_API JsCreateDataView(_In_ JsValueRef arrayBuffer, _In_ unsigned int byteOffset, _In_ unsigned int byteLength, _Out_ JsValueRef *result)
  1354. {
  1355. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1356. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1357. VALIDATE_INCOMING_REFERENCE(arrayBuffer, scriptContext);
  1358. PARAM_NOT_NULL(result);
  1359. if (!Js::ArrayBuffer::Is(arrayBuffer))
  1360. {
  1361. return JsErrorInvalidArgument;
  1362. }
  1363. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1364. *result = library->CreateDataView(Js::ArrayBuffer::FromVar(arrayBuffer), byteOffset, byteLength);
  1365. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1366. return JsNoError;
  1367. });
  1368. }
  1369. C_ASSERT(JsArrayTypeUint8 - Js::TypeIds_Uint8Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1370. C_ASSERT(JsArrayTypeUint8Clamped - Js::TypeIds_Uint8ClampedArray == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1371. C_ASSERT(JsArrayTypeInt16 - Js::TypeIds_Int16Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1372. C_ASSERT(JsArrayTypeUint16 - Js::TypeIds_Uint16Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1373. C_ASSERT(JsArrayTypeInt32 - Js::TypeIds_Int32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1374. C_ASSERT(JsArrayTypeUint32 - Js::TypeIds_Uint32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1375. C_ASSERT(JsArrayTypeFloat32 - Js::TypeIds_Float32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1376. C_ASSERT(JsArrayTypeFloat64 - Js::TypeIds_Float64Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1377. inline JsTypedArrayType GetTypedArrayType(Js::TypeId typeId)
  1378. {
  1379. Assert(Js::TypedArrayBase::Is(typeId));
  1380. return static_cast<JsTypedArrayType>(typeId + (JsArrayTypeInt8 - Js::TypeIds_Int8Array));
  1381. }
  1382. CHAKRA_API JsGetTypedArrayInfo(_In_ JsValueRef typedArray, _Out_opt_ JsTypedArrayType *arrayType, _Out_opt_ JsValueRef *arrayBuffer,
  1383. _Out_opt_ unsigned int *byteOffset, _Out_opt_ unsigned int *byteLength)
  1384. {
  1385. VALIDATE_JSREF(typedArray);
  1386. BEGIN_JSRT_NO_EXCEPTION
  1387. {
  1388. const Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(typedArray);
  1389. if (!Js::TypedArrayBase::Is(typeId))
  1390. {
  1391. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1392. }
  1393. if (arrayType != nullptr) {
  1394. *arrayType = GetTypedArrayType(typeId);
  1395. }
  1396. Js::TypedArrayBase* typedArrayBase = Js::TypedArrayBase::FromVar(typedArray);
  1397. if (arrayBuffer != nullptr) {
  1398. *arrayBuffer = typedArrayBase->GetArrayBuffer();
  1399. }
  1400. if (byteOffset != nullptr) {
  1401. *byteOffset = typedArrayBase->GetByteOffset();
  1402. }
  1403. if (byteLength != nullptr) {
  1404. *byteLength = typedArrayBase->GetByteLength();
  1405. }
  1406. }
  1407. #if ENABLE_TTD
  1408. Js::ScriptContext* scriptContext = Js::RecyclableObject::FromVar(typedArray)->GetScriptContext();
  1409. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext) && arrayBuffer != nullptr)
  1410. {
  1411. scriptContext->GetThreadContext()->TTDLog->RecordJsRTGetTypedArrayInfo(typedArray, *arrayBuffer);
  1412. }
  1413. #endif
  1414. END_JSRT_NO_EXCEPTION
  1415. }
  1416. CHAKRA_API JsGetArrayBufferStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer,
  1417. _Out_ unsigned int *bufferLength)
  1418. {
  1419. VALIDATE_JSREF(instance);
  1420. PARAM_NOT_NULL(buffer);
  1421. PARAM_NOT_NULL(bufferLength);
  1422. BEGIN_JSRT_NO_EXCEPTION
  1423. {
  1424. if (!Js::ArrayBuffer::Is(instance))
  1425. {
  1426. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1427. }
  1428. Js::ArrayBuffer* arrayBuffer = Js::ArrayBuffer::FromVar(instance);
  1429. *buffer = arrayBuffer->GetBuffer();
  1430. *bufferLength = arrayBuffer->GetByteLength();
  1431. }
  1432. END_JSRT_NO_EXCEPTION
  1433. }
  1434. CHAKRA_API JsGetTypedArrayStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer,
  1435. _Out_ unsigned int *bufferLength, _Out_opt_ JsTypedArrayType *typedArrayType, _Out_opt_ int *elementSize)
  1436. {
  1437. VALIDATE_JSREF(instance);
  1438. PARAM_NOT_NULL(buffer);
  1439. PARAM_NOT_NULL(bufferLength);
  1440. BEGIN_JSRT_NO_EXCEPTION
  1441. {
  1442. const Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(instance);
  1443. if (!Js::TypedArrayBase::Is(typeId))
  1444. {
  1445. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1446. }
  1447. Js::TypedArrayBase* typedArrayBase = Js::TypedArrayBase::FromVar(instance);
  1448. *buffer = typedArrayBase->GetByteBuffer();
  1449. *bufferLength = typedArrayBase->GetByteLength();
  1450. if (typedArrayType)
  1451. {
  1452. *typedArrayType = GetTypedArrayType(typeId);
  1453. }
  1454. if (elementSize)
  1455. {
  1456. switch (typeId)
  1457. {
  1458. case Js::TypeIds_Int8Array:
  1459. *elementSize = sizeof(int8);
  1460. break;
  1461. case Js::TypeIds_Uint8Array:
  1462. *elementSize = sizeof(uint8);
  1463. break;
  1464. case Js::TypeIds_Uint8ClampedArray:
  1465. *elementSize = sizeof(uint8);
  1466. break;
  1467. case Js::TypeIds_Int16Array:
  1468. *elementSize = sizeof(int16);
  1469. break;
  1470. case Js::TypeIds_Uint16Array:
  1471. *elementSize = sizeof(uint16);
  1472. break;
  1473. case Js::TypeIds_Int32Array:
  1474. *elementSize = sizeof(int32);
  1475. break;
  1476. case Js::TypeIds_Uint32Array:
  1477. *elementSize = sizeof(uint32);
  1478. break;
  1479. case Js::TypeIds_Float32Array:
  1480. *elementSize = sizeof(float);
  1481. break;
  1482. case Js::TypeIds_Float64Array:
  1483. *elementSize = sizeof(double);
  1484. break;
  1485. default:
  1486. AssertMsg(FALSE, "invalid typed array type");
  1487. *elementSize = 1;
  1488. RETURN_NO_EXCEPTION(JsErrorFatal);
  1489. }
  1490. }
  1491. }
  1492. END_JSRT_NO_EXCEPTION
  1493. }
  1494. CHAKRA_API JsGetDataViewStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer, _Out_ unsigned int *bufferLength)
  1495. {
  1496. VALIDATE_JSREF(instance);
  1497. PARAM_NOT_NULL(buffer);
  1498. PARAM_NOT_NULL(bufferLength);
  1499. BEGIN_JSRT_NO_EXCEPTION
  1500. {
  1501. if (!Js::DataView::Is(instance))
  1502. {
  1503. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1504. }
  1505. Js::DataView* dataView = Js::DataView::FromVar(instance);
  1506. *buffer = dataView->GetArrayBuffer()->GetBuffer() + dataView->GetByteOffset();
  1507. *bufferLength = dataView->GetLength();
  1508. }
  1509. END_JSRT_NO_EXCEPTION
  1510. }
  1511. CHAKRA_API JsCreateSymbol(_In_ JsValueRef description, _Out_ JsValueRef *result)
  1512. {
  1513. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1514. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateSymbol, description);
  1515. PARAM_NOT_NULL(result);
  1516. *result = nullptr;
  1517. Js::JavascriptString* descriptionString;
  1518. if (description != JS_INVALID_REFERENCE)
  1519. {
  1520. VALIDATE_INCOMING_REFERENCE(description, scriptContext);
  1521. descriptionString = Js::JavascriptConversion::ToString(description, scriptContext);
  1522. }
  1523. else
  1524. {
  1525. descriptionString = scriptContext->GetLibrary()->GetEmptyString();
  1526. }
  1527. *result = scriptContext->GetLibrary()->CreateSymbol(descriptionString);
  1528. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1529. return JsNoError;
  1530. });
  1531. }
  1532. CHAKRA_API JsHasIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _Out_ bool *result)
  1533. {
  1534. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1535. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1536. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1537. VALIDATE_INCOMING_REFERENCE(index, scriptContext);
  1538. PARAM_NOT_NULL(result);
  1539. *result = false;
  1540. *result = Js::JavascriptOperators::OP_HasItem((Js::Var)object, (Js::Var)index, scriptContext) != 0;
  1541. return JsNoError;
  1542. });
  1543. }
  1544. CHAKRA_API JsGetIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _Out_ JsValueRef *result)
  1545. {
  1546. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1547. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetIndex, index, object);
  1548. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1549. VALIDATE_INCOMING_REFERENCE(index, scriptContext);
  1550. PARAM_NOT_NULL(result);
  1551. *result = nullptr;
  1552. *result = (JsValueRef)Js::JavascriptOperators::OP_GetElementI((Js::Var)object, (Js::Var)index, scriptContext);
  1553. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1554. return JsNoError;
  1555. });
  1556. }
  1557. CHAKRA_API JsSetIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _In_ JsValueRef value)
  1558. {
  1559. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1560. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetIndex, object, index, value);
  1561. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1562. VALIDATE_INCOMING_REFERENCE(index, scriptContext);
  1563. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1564. Js::JavascriptOperators::OP_SetElementI((Js::Var)object, (Js::Var)index, (Js::Var)value, scriptContext);
  1565. return JsNoError;
  1566. });
  1567. }
  1568. CHAKRA_API JsDeleteIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index)
  1569. {
  1570. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1571. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1572. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1573. VALIDATE_INCOMING_REFERENCE(index, scriptContext);
  1574. Js::JavascriptOperators::OP_DeleteElementI((Js::Var)object, (Js::Var)index, scriptContext);
  1575. return JsNoError;
  1576. });
  1577. }
  1578. template <class T, bool clamped = false> struct TypedArrayTypeTraits { static const JsTypedArrayType cTypedArrayType; };
  1579. template<> struct TypedArrayTypeTraits<int8> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt8; };
  1580. template<> struct TypedArrayTypeTraits<uint8, false> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint8; };
  1581. template<> struct TypedArrayTypeTraits<uint8, true> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint8Clamped; };
  1582. template<> struct TypedArrayTypeTraits<int16> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt16; };
  1583. template<> struct TypedArrayTypeTraits<uint16> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint16; };
  1584. template<> struct TypedArrayTypeTraits<int32> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt32; };
  1585. template<> struct TypedArrayTypeTraits<uint32> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint32; };
  1586. template<> struct TypedArrayTypeTraits<float> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeFloat32; };
  1587. template<> struct TypedArrayTypeTraits<double> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeFloat64; };
  1588. template <class T, bool clamped = false>
  1589. Js::ArrayObject* CreateTypedArray(Js::ScriptContext *scriptContext, void* data, unsigned int length)
  1590. {
  1591. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1592. Js::ArrayBufferBase* arrayBuffer = RecyclerNew(
  1593. scriptContext->GetRecycler(),
  1594. Js::ExternalArrayBuffer,
  1595. reinterpret_cast<BYTE*>(data),
  1596. length * sizeof(T),
  1597. library->GetArrayBufferType());
  1598. return static_cast<Js::ArrayObject*>(Js::TypedArray<T, clamped>::Create(arrayBuffer, 0, length, library));
  1599. }
  1600. template <class T, bool clamped = false>
  1601. void GetObjectArrayData(Js::ArrayObject* objectArray, void** data, JsTypedArrayType* arrayType, uint* length)
  1602. {
  1603. Js::TypedArray<T, clamped>* typedArray = Js::TypedArray<T, clamped>::FromVar(objectArray);
  1604. *data = typedArray->GetArrayBuffer()->GetBuffer();
  1605. *arrayType = TypedArrayTypeTraits<T, clamped>::cTypedArrayType;
  1606. *length = typedArray->GetLength();
  1607. }
  1608. CHAKRA_API JsSetIndexedPropertiesToExternalData(
  1609. _In_ JsValueRef object,
  1610. _In_ void* data,
  1611. _In_ JsTypedArrayType arrayType,
  1612. _In_ unsigned int elementLength)
  1613. {
  1614. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1615. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1616. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1617. // Don't support doing this on array or array-like object
  1618. Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(object);
  1619. if (!Js::DynamicType::Is(typeId)
  1620. || Js::DynamicObject::IsAnyArrayTypeId(typeId)
  1621. || (typeId >= Js::TypeIds_TypedArrayMin && typeId <= Js::TypeIds_TypedArrayMax)
  1622. || typeId == Js::TypeIds_ArrayBuffer
  1623. || typeId == Js::TypeIds_DataView
  1624. || Js::RecyclableObject::FromVar(object)->IsExternal()
  1625. )
  1626. {
  1627. return JsErrorInvalidArgument;
  1628. }
  1629. if (data == nullptr && elementLength > 0)
  1630. {
  1631. return JsErrorInvalidArgument;
  1632. }
  1633. Js::ArrayObject* newTypedArray = nullptr;
  1634. switch (arrayType)
  1635. {
  1636. case JsArrayTypeInt8:
  1637. newTypedArray = CreateTypedArray<int8>(scriptContext, data, elementLength);
  1638. break;
  1639. case JsArrayTypeUint8:
  1640. newTypedArray = CreateTypedArray<uint8>(scriptContext, data, elementLength);
  1641. break;
  1642. case JsArrayTypeUint8Clamped:
  1643. newTypedArray = CreateTypedArray<uint8, true>(scriptContext, data, elementLength);
  1644. break;
  1645. case JsArrayTypeInt16:
  1646. newTypedArray = CreateTypedArray<int16>(scriptContext, data, elementLength);
  1647. break;
  1648. case JsArrayTypeUint16:
  1649. newTypedArray = CreateTypedArray<uint16>(scriptContext, data, elementLength);
  1650. break;
  1651. case JsArrayTypeInt32:
  1652. newTypedArray = CreateTypedArray<int32>(scriptContext, data, elementLength);
  1653. break;
  1654. case JsArrayTypeUint32:
  1655. newTypedArray = CreateTypedArray<uint32>(scriptContext, data, elementLength);
  1656. break;
  1657. case JsArrayTypeFloat32:
  1658. newTypedArray = CreateTypedArray<float>(scriptContext, data, elementLength);
  1659. break;
  1660. case JsArrayTypeFloat64:
  1661. newTypedArray = CreateTypedArray<double>(scriptContext, data, elementLength);
  1662. break;
  1663. default:
  1664. return JsErrorInvalidArgument;
  1665. }
  1666. Js::DynamicObject* dynamicObject = Js::DynamicObject::FromVar(object);
  1667. dynamicObject->SetObjectArray(newTypedArray);
  1668. return JsNoError;
  1669. });
  1670. }
  1671. CHAKRA_API JsHasIndexedPropertiesExternalData(_In_ JsValueRef object, _Out_ bool *value)
  1672. {
  1673. VALIDATE_JSREF(object);
  1674. PARAM_NOT_NULL(value);
  1675. BEGIN_JSRT_NO_EXCEPTION
  1676. {
  1677. *value = false;
  1678. if (Js::DynamicType::Is(Js::JavascriptOperators::GetTypeId(object)))
  1679. {
  1680. Js::DynamicObject* dynamicObject = Js::DynamicObject::FromVar(object);
  1681. Js::ArrayObject* objectArray = dynamicObject->GetObjectArray();
  1682. *value = (objectArray && !Js::DynamicObject::IsAnyArray(objectArray));
  1683. }
  1684. }
  1685. END_JSRT_NO_EXCEPTION
  1686. }
  1687. CHAKRA_API JsGetIndexedPropertiesExternalData(
  1688. _In_ JsValueRef object,
  1689. _Out_ void** buffer,
  1690. _Out_ JsTypedArrayType* arrayType,
  1691. _Out_ unsigned int* elementLength)
  1692. {
  1693. VALIDATE_JSREF(object);
  1694. PARAM_NOT_NULL(buffer);
  1695. PARAM_NOT_NULL(arrayType);
  1696. PARAM_NOT_NULL(elementLength);
  1697. BEGIN_JSRT_NO_EXCEPTION
  1698. {
  1699. if (!Js::DynamicType::Is(Js::JavascriptOperators::GetTypeId(object)))
  1700. {
  1701. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1702. }
  1703. *buffer = nullptr;
  1704. *arrayType = JsTypedArrayType();
  1705. *elementLength = 0;
  1706. Js::DynamicObject* dynamicObject = Js::DynamicObject::FromVar(object);
  1707. Js::ArrayObject* objectArray = dynamicObject->GetObjectArray();
  1708. if (!objectArray)
  1709. {
  1710. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1711. }
  1712. switch (Js::JavascriptOperators::GetTypeId(objectArray))
  1713. {
  1714. case Js::TypeIds_Int8Array:
  1715. GetObjectArrayData<int8>(objectArray, buffer, arrayType, elementLength);
  1716. break;
  1717. case Js::TypeIds_Uint8Array:
  1718. GetObjectArrayData<uint8>(objectArray, buffer, arrayType, elementLength);
  1719. break;
  1720. case Js::TypeIds_Uint8ClampedArray:
  1721. GetObjectArrayData<uint8, true>(objectArray, buffer, arrayType, elementLength);
  1722. break;
  1723. case Js::TypeIds_Int16Array:
  1724. GetObjectArrayData<int16>(objectArray, buffer, arrayType, elementLength);
  1725. break;
  1726. case Js::TypeIds_Uint16Array:
  1727. GetObjectArrayData<uint16>(objectArray, buffer, arrayType, elementLength);
  1728. break;
  1729. case Js::TypeIds_Int32Array:
  1730. GetObjectArrayData<int32>(objectArray, buffer, arrayType, elementLength);
  1731. break;
  1732. case Js::TypeIds_Uint32Array:
  1733. GetObjectArrayData<uint32>(objectArray, buffer, arrayType, elementLength);
  1734. break;
  1735. case Js::TypeIds_Float32Array:
  1736. GetObjectArrayData<float>(objectArray, buffer, arrayType, elementLength);
  1737. break;
  1738. case Js::TypeIds_Float64Array:
  1739. GetObjectArrayData<double>(objectArray, buffer, arrayType, elementLength);
  1740. break;
  1741. default:
  1742. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1743. }
  1744. }
  1745. END_JSRT_NO_EXCEPTION
  1746. }
  1747. CHAKRA_API JsEquals(_In_ JsValueRef object1, _In_ JsValueRef object2, _Out_ bool *result)
  1748. {
  1749. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1750. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTEquals, object1, object2, false);
  1751. VALIDATE_INCOMING_REFERENCE(object1, scriptContext);
  1752. VALIDATE_INCOMING_REFERENCE(object2, scriptContext);
  1753. PARAM_NOT_NULL(result);
  1754. *result = Js::JavascriptOperators::Equal((Js::Var)object1, (Js::Var)object2, scriptContext) != 0;
  1755. return JsNoError;
  1756. });
  1757. }
  1758. CHAKRA_API JsStrictEquals(_In_ JsValueRef object1, _In_ JsValueRef object2, _Out_ bool *result)
  1759. {
  1760. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1761. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTEquals, object1, object2, true);
  1762. VALIDATE_INCOMING_REFERENCE(object1, scriptContext);
  1763. VALIDATE_INCOMING_REFERENCE(object2, scriptContext);
  1764. PARAM_NOT_NULL(result);
  1765. *result = Js::JavascriptOperators::StrictEqual((Js::Var)object1, (Js::Var)object2, scriptContext) != 0;
  1766. return JsNoError;
  1767. });
  1768. }
  1769. CHAKRA_API JsHasExternalData(_In_ JsValueRef object, _Out_ bool *value)
  1770. {
  1771. VALIDATE_JSREF(object);
  1772. PARAM_NOT_NULL(value);
  1773. BEGIN_JSRT_NO_EXCEPTION
  1774. {
  1775. *value = JsrtExternalObject::Is(object);
  1776. }
  1777. END_JSRT_NO_EXCEPTION
  1778. }
  1779. CHAKRA_API JsGetExternalData(_In_ JsValueRef object, _Out_ void **data)
  1780. {
  1781. VALIDATE_JSREF(object);
  1782. PARAM_NOT_NULL(data);
  1783. BEGIN_JSRT_NO_EXCEPTION
  1784. {
  1785. if (JsrtExternalObject::Is(object))
  1786. {
  1787. *data = JsrtExternalObject::FromVar(object)->GetSlotData();
  1788. }
  1789. else
  1790. {
  1791. *data = nullptr;
  1792. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1793. }
  1794. }
  1795. END_JSRT_NO_EXCEPTION
  1796. }
  1797. CHAKRA_API JsSetExternalData(_In_ JsValueRef object, _In_opt_ void *data)
  1798. {
  1799. VALIDATE_JSREF(object);
  1800. BEGIN_JSRT_NO_EXCEPTION
  1801. {
  1802. if (JsrtExternalObject::Is(object))
  1803. {
  1804. JsrtExternalObject::FromVar(object)->SetSlotData(data);
  1805. }
  1806. else
  1807. {
  1808. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1809. }
  1810. }
  1811. END_JSRT_NO_EXCEPTION
  1812. }
  1813. CHAKRA_API JsCallFunction(_In_ JsValueRef function, _In_reads_(cargs) JsValueRef *args, _In_ ushort cargs, _Out_opt_ JsValueRef *result)
  1814. {
  1815. if(result != nullptr)
  1816. {
  1817. *result = nullptr;
  1818. }
  1819. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1820. #if ENABLE_TTD
  1821. TTD::TTDJsRTFunctionCallActionPopperRecorder callInfoPopper;
  1822. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  1823. {
  1824. TTD::NSLogEvents::EventLogEntry* callEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCallFunction(_actionEntryPopper, scriptContext->GetThreadContext()->TTDRootNestingCount, function, cargs, args);
  1825. callInfoPopper.InitializeForRecording(scriptContext, callEvent);
  1826. if(scriptContext->GetThreadContext()->TTDRootNestingCount == 0)
  1827. {
  1828. TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
  1829. elog->ResetCallStackForTopLevelCall(elog->GetLastEventTime());
  1830. }
  1831. }
  1832. #endif
  1833. VALIDATE_INCOMING_FUNCTION(function, scriptContext);
  1834. if(cargs == 0 || args == nullptr)
  1835. {
  1836. return JsErrorInvalidArgument;
  1837. }
  1838. for(int index = 0; index < cargs; index++)
  1839. {
  1840. VALIDATE_INCOMING_REFERENCE(args[index], scriptContext);
  1841. }
  1842. Js::JavascriptFunction *jsFunction = Js::JavascriptFunction::FromVar(function);
  1843. Js::CallInfo callInfo(cargs);
  1844. Js::Arguments jsArgs(callInfo, reinterpret_cast<Js::Var *>(args));
  1845. Js::Var varResult = jsFunction->CallRootFunction(jsArgs, scriptContext, true);
  1846. if(result != nullptr)
  1847. {
  1848. *result = varResult;
  1849. Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
  1850. }
  1851. #if ENABLE_TTD
  1852. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  1853. {
  1854. _actionEntryPopper.SetResult(result);
  1855. }
  1856. #endif
  1857. return JsNoError;
  1858. });
  1859. }
  1860. CHAKRA_API JsConstructObject(_In_ JsValueRef function, _In_reads_(cargs) JsValueRef *args, _In_ ushort cargs, _Out_ JsValueRef *result)
  1861. {
  1862. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1863. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTConstructCall, function, cargs, args);
  1864. VALIDATE_INCOMING_FUNCTION(function, scriptContext);
  1865. PARAM_NOT_NULL(result);
  1866. *result = nullptr;
  1867. if (cargs == 0 || args == nullptr)
  1868. {
  1869. return JsErrorInvalidArgument;
  1870. }
  1871. for (int index = 0; index < cargs; index++)
  1872. {
  1873. VALIDATE_INCOMING_REFERENCE(args[index], scriptContext);
  1874. }
  1875. Js::JavascriptFunction *jsFunction = Js::JavascriptFunction::FromVar(function);
  1876. Js::CallInfo callInfo(Js::CallFlags::CallFlags_New, cargs);
  1877. Js::Arguments jsArgs(callInfo, reinterpret_cast<Js::Var *>(args));
  1878. //
  1879. //TODO: we will want to look at this at some point -- either treat as "top-level" call or maybe constructors are fast so we can just jump back to previous "real" code
  1880. //TTDAssert(!Js::ScriptFunction::Is(jsFunction) || execContext->GetThreadContext()->TTDRootNestingCount != 0, "This will cause user code to execute and we need to add support for that as a top-level call source!!!!");
  1881. //
  1882. *result = Js::JavascriptFunction::CallAsConstructor(jsFunction, /* overridingNewTarget = */nullptr, jsArgs, scriptContext);
  1883. Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
  1884. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1885. return JsNoError;
  1886. });
  1887. }
  1888. CHAKRA_API JsCreateFunction(_In_ JsNativeFunction nativeFunction, _In_opt_ void *callbackState, _Out_ JsValueRef *function)
  1889. {
  1890. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1891. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateFunction, false, nullptr);
  1892. PARAM_NOT_NULL(nativeFunction);
  1893. PARAM_NOT_NULL(function);
  1894. *function = nullptr;
  1895. Js::JavascriptExternalFunction *externalFunction = scriptContext->GetLibrary()->CreateStdCallExternalFunction((Js::StdCallJavascriptMethod)nativeFunction, 0, callbackState);
  1896. *function = (JsValueRef)externalFunction;
  1897. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, function);
  1898. return JsNoError;
  1899. });
  1900. }
  1901. CHAKRA_API JsCreateNamedFunction(_In_ JsValueRef name, _In_ JsNativeFunction nativeFunction, _In_opt_ void *callbackState, _Out_ JsValueRef *function)
  1902. {
  1903. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1904. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateFunction, true, name);
  1905. VALIDATE_INCOMING_REFERENCE(name, scriptContext);
  1906. PARAM_NOT_NULL(nativeFunction);
  1907. PARAM_NOT_NULL(function);
  1908. *function = nullptr;
  1909. if (name != JS_INVALID_REFERENCE)
  1910. {
  1911. name = Js::JavascriptConversion::ToString(name, scriptContext);
  1912. }
  1913. else
  1914. {
  1915. name = scriptContext->GetLibrary()->GetEmptyString();
  1916. }
  1917. Js::JavascriptExternalFunction *externalFunction = scriptContext->GetLibrary()->CreateStdCallExternalFunction((Js::StdCallJavascriptMethod)nativeFunction, Js::JavascriptString::FromVar(name), callbackState);
  1918. *function = (JsValueRef)externalFunction;
  1919. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, function);
  1920. return JsNoError;
  1921. });
  1922. }
  1923. void SetErrorMessage(Js::ScriptContext *scriptContext, JsValueRef newError, JsValueRef message)
  1924. {
  1925. Js::JavascriptOperators::OP_SetProperty(newError, Js::PropertyIds::message, message, scriptContext);
  1926. }
  1927. CHAKRA_API JsCreateError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  1928. {
  1929. return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1930. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateError, message);
  1931. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  1932. PARAM_NOT_NULL(error);
  1933. *error = nullptr;
  1934. JsValueRef newError = scriptContext->GetLibrary()->CreateError();
  1935. SetErrorMessage(scriptContext, newError, message);
  1936. *error = newError;
  1937. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  1938. return JsNoError;
  1939. });
  1940. }
  1941. CHAKRA_API JsCreateRangeError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  1942. {
  1943. return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1944. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateRangeError, message);
  1945. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  1946. PARAM_NOT_NULL(error);
  1947. *error = nullptr;
  1948. JsValueRef newError = scriptContext->GetLibrary()->CreateRangeError();
  1949. SetErrorMessage(scriptContext, newError, message);
  1950. *error = newError;
  1951. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  1952. return JsNoError;
  1953. });
  1954. }
  1955. CHAKRA_API JsCreateReferenceError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  1956. {
  1957. return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1958. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateReferenceError, message);
  1959. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  1960. PARAM_NOT_NULL(error);
  1961. *error = nullptr;
  1962. JsValueRef newError = scriptContext->GetLibrary()->CreateReferenceError();
  1963. SetErrorMessage(scriptContext, newError, message);
  1964. *error = newError;
  1965. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  1966. return JsNoError;
  1967. });
  1968. }
  1969. CHAKRA_API JsCreateSyntaxError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  1970. {
  1971. return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1972. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateSyntaxError, message);
  1973. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  1974. PARAM_NOT_NULL(error);
  1975. *error = nullptr;
  1976. JsValueRef newError = scriptContext->GetLibrary()->CreateSyntaxError();
  1977. SetErrorMessage(scriptContext, newError, message);
  1978. *error = newError;
  1979. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  1980. return JsNoError;
  1981. });
  1982. }
  1983. CHAKRA_API JsCreateTypeError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  1984. {
  1985. return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1986. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateTypeError, message);
  1987. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  1988. PARAM_NOT_NULL(error);
  1989. *error = nullptr;
  1990. JsValueRef newError = scriptContext->GetLibrary()->CreateTypeError();
  1991. SetErrorMessage(scriptContext, newError, message);
  1992. *error = newError;
  1993. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  1994. return JsNoError;
  1995. });
  1996. }
  1997. CHAKRA_API JsCreateURIError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  1998. {
  1999. return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2000. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateURIError, message);
  2001. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  2002. PARAM_NOT_NULL(error);
  2003. *error = nullptr;
  2004. JsValueRef newError = scriptContext->GetLibrary()->CreateURIError();
  2005. SetErrorMessage(scriptContext, newError, message);
  2006. *error = newError;
  2007. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  2008. return JsNoError;
  2009. });
  2010. }
  2011. CHAKRA_API JsHasException(_Out_ bool *hasException)
  2012. {
  2013. PARAM_NOT_NULL(hasException);
  2014. *hasException = false;
  2015. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2016. if (currentContext == nullptr)
  2017. {
  2018. return JsErrorNoCurrentContext;
  2019. }
  2020. Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
  2021. Assert(scriptContext != nullptr);
  2022. if (scriptContext->GetRecycler() && scriptContext->GetRecycler()->IsHeapEnumInProgress())
  2023. {
  2024. return JsErrorHeapEnumInProgress;
  2025. }
  2026. else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
  2027. {
  2028. return JsErrorInThreadServiceCallback;
  2029. }
  2030. if (scriptContext->GetThreadContext()->IsExecutionDisabled())
  2031. {
  2032. return JsErrorInDisabledState;
  2033. }
  2034. *hasException = scriptContext->HasRecordedException();
  2035. return JsNoError;
  2036. }
  2037. CHAKRA_API JsGetAndClearException(_Out_ JsValueRef *exception)
  2038. {
  2039. PARAM_NOT_NULL(exception);
  2040. *exception = nullptr;
  2041. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2042. if (currentContext == nullptr)
  2043. {
  2044. return JsErrorNoCurrentContext;
  2045. }
  2046. Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
  2047. Assert(scriptContext != nullptr);
  2048. if (scriptContext->GetRecycler() && scriptContext->GetRecycler()->IsHeapEnumInProgress())
  2049. {
  2050. return JsErrorHeapEnumInProgress;
  2051. }
  2052. else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
  2053. {
  2054. return JsErrorInThreadServiceCallback;
  2055. }
  2056. if (scriptContext->GetThreadContext()->IsExecutionDisabled())
  2057. {
  2058. return JsErrorInDisabledState;
  2059. }
  2060. HRESULT hr = S_OK;
  2061. Js::JavascriptExceptionObject *recordedException = nullptr;
  2062. BEGIN_TRANSLATE_OOM_TO_HRESULT
  2063. recordedException = scriptContext->GetAndClearRecordedException();
  2064. END_TRANSLATE_OOM_TO_HRESULT(hr)
  2065. if (hr == E_OUTOFMEMORY)
  2066. {
  2067. recordedException = scriptContext->GetThreadContext()->GetRecordedException();
  2068. }
  2069. if (recordedException == nullptr)
  2070. {
  2071. return JsErrorInvalidArgument;
  2072. }
  2073. *exception = recordedException->GetThrownObject(nullptr);
  2074. #if ENABLE_TTD
  2075. if(hr != E_OUTOFMEMORY)
  2076. {
  2077. TTD::TTDJsRTActionResultAutoRecorder _actionEntryPopper;
  2078. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetAndClearException);
  2079. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, exception);
  2080. }
  2081. #endif
  2082. if (*exception == nullptr)
  2083. {
  2084. return JsErrorInvalidArgument;
  2085. }
  2086. return JsNoError;
  2087. }
  2088. CHAKRA_API JsSetException(_In_ JsValueRef exception)
  2089. {
  2090. return ContextAPINoScriptWrapper([&](Js::ScriptContext* scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2091. JsrtContext * context = JsrtContext::GetCurrent();
  2092. JsrtRuntime * runtime = context->GetRuntime();
  2093. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetException, exception, runtime->DispatchExceptions());
  2094. VALIDATE_INCOMING_REFERENCE(exception, scriptContext);
  2095. Js::JavascriptExceptionObject *exceptionObject;
  2096. exceptionObject = RecyclerNew(scriptContext->GetRecycler(), Js::JavascriptExceptionObject, exception, scriptContext, nullptr);
  2097. scriptContext->RecordException(exceptionObject, runtime->DispatchExceptions());
  2098. return JsNoError;
  2099. });
  2100. }
  2101. CHAKRA_API JsGetRuntimeMemoryUsage(_In_ JsRuntimeHandle runtimeHandle, _Out_ size_t * memoryUsage)
  2102. {
  2103. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2104. PARAM_NOT_NULL(memoryUsage);
  2105. *memoryUsage = 0;
  2106. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2107. AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
  2108. *memoryUsage = allocPolicyManager->GetUsage();
  2109. return JsNoError;
  2110. }
  2111. CHAKRA_API JsSetRuntimeMemoryLimit(_In_ JsRuntimeHandle runtimeHandle, _In_ size_t memoryLimit)
  2112. {
  2113. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2114. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2115. AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
  2116. allocPolicyManager->SetLimit(memoryLimit);
  2117. return JsNoError;
  2118. }
  2119. CHAKRA_API JsGetRuntimeMemoryLimit(_In_ JsRuntimeHandle runtimeHandle, _Out_ size_t * memoryLimit)
  2120. {
  2121. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2122. PARAM_NOT_NULL(memoryLimit);
  2123. *memoryLimit = 0;
  2124. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2125. AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
  2126. *memoryLimit = allocPolicyManager->GetLimit();
  2127. return JsNoError;
  2128. }
  2129. C_ASSERT(JsMemoryAllocate == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryAllocate);
  2130. C_ASSERT(JsMemoryFree == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryFree);
  2131. C_ASSERT(JsMemoryFailure == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryFailure);
  2132. C_ASSERT(JsMemoryFailure == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryMax);
  2133. CHAKRA_API JsSetRuntimeMemoryAllocationCallback(_In_ JsRuntimeHandle runtime, _In_opt_ void *callbackState, _In_ JsMemoryAllocationCallback allocationCallback)
  2134. {
  2135. VALIDATE_INCOMING_RUNTIME_HANDLE(runtime);
  2136. ThreadContext* threadContext = JsrtRuntime::FromHandle(runtime)->GetThreadContext();
  2137. AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
  2138. allocPolicyManager->SetMemoryAllocationCallback(callbackState, (AllocationPolicyManager::PageAllocatorMemoryAllocationCallback)allocationCallback);
  2139. return JsNoError;
  2140. }
  2141. CHAKRA_API JsSetRuntimeBeforeCollectCallback(_In_ JsRuntimeHandle runtime, _In_opt_ void *callbackState, _In_ JsBeforeCollectCallback beforeCollectCallback)
  2142. {
  2143. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  2144. VALIDATE_INCOMING_RUNTIME_HANDLE(runtime);
  2145. JsrtRuntime::FromHandle(runtime)->SetBeforeCollectCallback(beforeCollectCallback, callbackState);
  2146. return JsNoError;
  2147. });
  2148. }
  2149. CHAKRA_API JsDisableRuntimeExecution(_In_ JsRuntimeHandle runtimeHandle)
  2150. {
  2151. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2152. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2153. if (!threadContext->TestThreadContextFlag(ThreadContextFlagCanDisableExecution))
  2154. {
  2155. return JsErrorCannotDisableExecution;
  2156. }
  2157. if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
  2158. {
  2159. return JsErrorHeapEnumInProgress;
  2160. }
  2161. else if (threadContext->IsInThreadServiceCallback())
  2162. {
  2163. return JsErrorInThreadServiceCallback;
  2164. }
  2165. threadContext->DisableExecution();
  2166. return JsNoError;
  2167. }
  2168. CHAKRA_API JsEnableRuntimeExecution(_In_ JsRuntimeHandle runtimeHandle)
  2169. {
  2170. return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode {
  2171. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2172. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2173. if (!threadContext->TestThreadContextFlag(ThreadContextFlagCanDisableExecution))
  2174. {
  2175. return JsNoError;
  2176. }
  2177. if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
  2178. {
  2179. return JsErrorHeapEnumInProgress;
  2180. }
  2181. else if (threadContext->IsInThreadServiceCallback())
  2182. {
  2183. return JsErrorInThreadServiceCallback;
  2184. }
  2185. ThreadContextScope scope(threadContext);
  2186. if (!scope.IsValid())
  2187. {
  2188. return JsErrorWrongThread;
  2189. }
  2190. threadContext->EnableExecution();
  2191. return JsNoError;
  2192. });
  2193. }
  2194. CHAKRA_API JsIsRuntimeExecutionDisabled(_In_ JsRuntimeHandle runtimeHandle, _Out_ bool *isDisabled)
  2195. {
  2196. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2197. PARAM_NOT_NULL(isDisabled);
  2198. *isDisabled = false;
  2199. ThreadContext* threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2200. *isDisabled = threadContext->IsExecutionDisabled();
  2201. return JsNoError;
  2202. }
  2203. CHAKRA_API JsGetPropertyIdFromName(_In_z_ const WCHAR *name, _Out_ JsPropertyIdRef *propertyId)
  2204. {
  2205. return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext * scriptContext) -> JsErrorCode {
  2206. PARAM_NOT_NULL(name);
  2207. PARAM_NOT_NULL(propertyId);
  2208. *propertyId = nullptr;
  2209. size_t cPropertyNameLength = wcslen(name);
  2210. if (cPropertyNameLength <= INT_MAX)
  2211. {
  2212. scriptContext->GetOrAddPropertyRecord(name, static_cast<int>(cPropertyNameLength), (Js::PropertyRecord const **)propertyId);
  2213. return JsNoError;
  2214. }
  2215. else
  2216. {
  2217. return JsErrorOutOfMemory;
  2218. }
  2219. });
  2220. }
  2221. CHAKRA_API JsGetPropertyIdFromSymbol(_In_ JsValueRef symbol, _Out_ JsPropertyIdRef *propertyId)
  2222. {
  2223. return ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2224. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetPropertyIdFromSymbol, symbol);
  2225. VALIDATE_INCOMING_REFERENCE(symbol, scriptContext);
  2226. PARAM_NOT_NULL(propertyId);
  2227. *propertyId = nullptr;
  2228. if (!Js::JavascriptSymbol::Is(symbol))
  2229. {
  2230. return JsErrorPropertyNotSymbol;
  2231. }
  2232. *propertyId = (JsPropertyIdRef)Js::JavascriptSymbol::FromVar(symbol)->GetValue();
  2233. return JsNoError;
  2234. },
  2235. /*allowInObjectBeforeCollectCallback*/true);
  2236. }
  2237. CHAKRA_API JsGetSymbolFromPropertyId(_In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *symbol)
  2238. {
  2239. return ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2240. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  2241. VALIDATE_INCOMING_PROPERTYID(propertyId);
  2242. PARAM_NOT_NULL(symbol);
  2243. *symbol = nullptr;
  2244. Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
  2245. if (!propertyRecord->IsSymbol())
  2246. {
  2247. return JsErrorPropertyNotSymbol;
  2248. }
  2249. *symbol = scriptContext->GetLibrary()->CreateSymbol(propertyRecord);
  2250. return JsNoError;
  2251. });
  2252. }
  2253. #pragma prefast(suppress:6101, "Prefast doesn't see through the lambda")
  2254. CHAKRA_API JsGetPropertyNameFromId(_In_ JsPropertyIdRef propertyId, _Outptr_result_z_ const WCHAR **name)
  2255. {
  2256. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  2257. VALIDATE_INCOMING_PROPERTYID(propertyId);
  2258. PARAM_NOT_NULL(name);
  2259. *name = nullptr;
  2260. Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
  2261. if (propertyRecord->IsSymbol())
  2262. {
  2263. return JsErrorPropertyNotString;
  2264. }
  2265. *name = propertyRecord->GetBuffer();
  2266. return JsNoError;
  2267. });
  2268. }
  2269. CHAKRA_API JsGetPropertyIdType(_In_ JsPropertyIdRef propertyId, _Out_ JsPropertyIdType* propertyIdType)
  2270. {
  2271. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  2272. VALIDATE_INCOMING_PROPERTYID(propertyId);
  2273. Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
  2274. if (propertyRecord->IsSymbol())
  2275. {
  2276. *propertyIdType = JsPropertyIdTypeSymbol;
  2277. }
  2278. else
  2279. {
  2280. *propertyIdType = JsPropertyIdTypeString;
  2281. }
  2282. return JsNoError;
  2283. });
  2284. }
  2285. CHAKRA_API JsGetRuntime(_In_ JsContextRef context, _Out_ JsRuntimeHandle *runtime)
  2286. {
  2287. VALIDATE_JSREF(context);
  2288. PARAM_NOT_NULL(runtime);
  2289. *runtime = nullptr;
  2290. if (!JsrtContext::Is(context))
  2291. {
  2292. return JsErrorInvalidArgument;
  2293. }
  2294. *runtime = static_cast<JsrtContext *>(context)->GetRuntime();
  2295. return JsNoError;
  2296. }
  2297. CHAKRA_API JsIdle(_Out_opt_ unsigned int *nextIdleTick)
  2298. {
  2299. PARAM_NOT_NULL(nextIdleTick);
  2300. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext * scriptContext) -> JsErrorCode {
  2301. *nextIdleTick = 0;
  2302. if (scriptContext->GetThreadContext()->GetRecycler() && scriptContext->GetThreadContext()->GetRecycler()->IsHeapEnumInProgress())
  2303. {
  2304. return JsErrorHeapEnumInProgress;
  2305. }
  2306. else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
  2307. {
  2308. return JsErrorInThreadServiceCallback;
  2309. }
  2310. JsrtContext * context = JsrtContext::GetCurrent();
  2311. JsrtRuntime * runtime = context->GetRuntime();
  2312. if (!runtime->UseIdle())
  2313. {
  2314. return JsErrorIdleNotEnabled;
  2315. }
  2316. unsigned int ticks = runtime->Idle();
  2317. *nextIdleTick = ticks;
  2318. return JsNoError;
  2319. });
  2320. }
  2321. CHAKRA_API JsSetPromiseContinuationCallback(_In_ JsPromiseContinuationCallback promiseContinuationCallback, _In_opt_ void *callbackState)
  2322. {
  2323. return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext * scriptContext) -> JsErrorCode {
  2324. PARAM_NOT_NULL(promiseContinuationCallback);
  2325. scriptContext->GetLibrary()->SetNativeHostPromiseContinuationFunction((Js::JavascriptLibrary::PromiseContinuationCallback)promiseContinuationCallback, callbackState);
  2326. return JsNoError;
  2327. },
  2328. /*allowInObjectBeforeCollectCallback*/true);
  2329. }
  2330. JsErrorCode RunScriptCore(JsValueRef scriptSource, const byte *script, size_t cb,
  2331. LoadScriptFlag loadScriptFlag, JsSourceContext sourceContext,
  2332. const WCHAR *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
  2333. bool isSourceModule, JsValueRef *result)
  2334. {
  2335. Js::JavascriptFunction *scriptFunction;
  2336. CompileScriptException se;
  2337. JsErrorCode errorCode = ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2338. PARAM_NOT_NULL(script);
  2339. PARAM_NOT_NULL(sourceUrl);
  2340. SourceContextInfo * sourceContextInfo = scriptContext->GetSourceContextInfo(sourceContext, nullptr);
  2341. if (sourceContextInfo == nullptr)
  2342. {
  2343. sourceContextInfo = scriptContext->CreateSourceContextInfo(sourceContext, sourceUrl, wcslen(sourceUrl), nullptr);
  2344. }
  2345. const int chsize = (loadScriptFlag & LoadScriptFlag_Utf8Source) ?
  2346. sizeof(utf8char_t) : sizeof(WCHAR);
  2347. SRCINFO si = {
  2348. /* sourceContextInfo */ sourceContextInfo,
  2349. /* dlnHost */ 0,
  2350. /* ulColumnHost */ 0,
  2351. /* lnMinHost */ 0,
  2352. /* ichMinHost */ 0,
  2353. /* ichLimHost */ static_cast<ULONG>(cb / chsize), // OK to truncate since this is used to limit sourceText in debugDocument/compilation errors.
  2354. /* ulCharOffset */ 0,
  2355. /* mod */ kmodGlobal,
  2356. /* grfsi */ 0
  2357. };
  2358. Js::Utf8SourceInfo* utf8SourceInfo = nullptr;
  2359. if (result != nullptr)
  2360. {
  2361. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Expression);
  2362. }
  2363. bool isLibraryCode = (parseAttributes & JsParseScriptAttributeLibraryCode) == JsParseScriptAttributeLibraryCode;
  2364. if (isLibraryCode)
  2365. {
  2366. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_LibraryCode);
  2367. }
  2368. if (isSourceModule)
  2369. {
  2370. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Module);
  2371. }
  2372. #if ENABLE_TTD
  2373. TTD::NSLogEvents::EventLogEntry* parseEvent = nullptr;
  2374. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2375. {
  2376. parseEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCodeParse(_actionEntryPopper,
  2377. loadScriptFlag, ((loadScriptFlag & LoadScriptFlag_Utf8Source) == LoadScriptFlag_Utf8Source),
  2378. script, (uint32)cb, sourceContext, sourceUrl);
  2379. }
  2380. #endif
  2381. scriptFunction = scriptContext->LoadScript(script, cb,
  2382. &si, &se, &utf8SourceInfo,
  2383. Js::Constants::GlobalCode, loadScriptFlag, scriptSource);
  2384. #if ENABLE_TTD
  2385. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2386. {
  2387. _actionEntryPopper.SetResult((Js::Var*)&scriptFunction);
  2388. }
  2389. //
  2390. //TODO: We may (probably?) want to use the debugger source rundown functionality here instead
  2391. //
  2392. if (scriptContext->IsTTDRecordModeEnabled())
  2393. {
  2394. //Make sure we have the body and text information available
  2395. Js::FunctionBody* globalBody = TTD::JsSupport::ForceAndGetFunctionBody(scriptFunction->GetParseableFunctionInfo());
  2396. const TTD::NSSnapValues::TopLevelScriptLoadFunctionBodyResolveInfo* tbfi = scriptContext->GetThreadContext()->TTDLog->AddScriptLoad(globalBody, kmodGlobal, globalBody->GetUtf8SourceInfo()->GetSourceInfoId(), script, (uint32)cb, loadScriptFlag);
  2397. if(parseEvent != nullptr)
  2398. {
  2399. TTD::NSLogEvents::JsRTCodeParseAction_SetBodyCtrId(parseEvent, tbfi->TopLevelBase.TopLevelBodyCtr);
  2400. }
  2401. //walk global body to (1) add functions to pin set (2) build parent map
  2402. BEGIN_JS_RUNTIME_CALL(scriptContext);
  2403. {
  2404. scriptContext->TTDContextInfo->ProcessFunctionBodyOnLoad(globalBody, nullptr);
  2405. scriptContext->TTDContextInfo->RegisterLoadedScript(globalBody, tbfi->TopLevelBase.TopLevelBodyCtr);
  2406. }
  2407. END_JS_RUNTIME_CALL(scriptContext);
  2408. }
  2409. #endif
  2410. JsrtContext * context = JsrtContext::GetCurrent();
  2411. context->OnScriptLoad(scriptFunction, utf8SourceInfo, &se);
  2412. return JsNoError;
  2413. });
  2414. if (errorCode != JsNoError)
  2415. {
  2416. return errorCode;
  2417. }
  2418. return ContextAPIWrapper<false>([&](Js::ScriptContext* scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2419. if (scriptFunction == nullptr)
  2420. {
  2421. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  2422. HandleScriptCompileError(scriptContext, &se);
  2423. return JsErrorScriptCompile;
  2424. }
  2425. if (parseOnly)
  2426. {
  2427. PARAM_NOT_NULL(result);
  2428. *result = scriptFunction;
  2429. }
  2430. else
  2431. {
  2432. Js::Arguments args(0, nullptr);
  2433. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2434. Js::Var varThis;
  2435. if (PHASE_FORCE1(Js::EvalCompilePhase))
  2436. {
  2437. varThis = Js::JavascriptOperators::OP_GetThis(scriptContext->GetLibrary()->GetUndefined(), kmodGlobal, scriptContext);
  2438. args.Info.Flags = (Js::CallFlags)Js::CallFlags::CallFlags_Eval;
  2439. args.Info.Count = 1;
  2440. args.Values = &varThis;
  2441. }
  2442. #endif
  2443. #if ENABLE_TTD
  2444. TTD::TTDJsRTFunctionCallActionPopperRecorder callInfoPopper;
  2445. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2446. {
  2447. TTD::NSLogEvents::EventLogEntry* callEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCallFunction(_actionEntryPopper, scriptContext->GetThreadContext()->TTDRootNestingCount, scriptFunction, args.Info.Count, args.Values);
  2448. callInfoPopper.InitializeForRecording(scriptContext, callEvent);
  2449. if(scriptContext->GetThreadContext()->TTDRootNestingCount == 0)
  2450. {
  2451. TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
  2452. elog->ResetCallStackForTopLevelCall(elog->GetLastEventTime());
  2453. }
  2454. }
  2455. #endif
  2456. Js::Var varResult = scriptFunction->CallRootFunction(args, scriptContext, true);
  2457. if (result != nullptr)
  2458. {
  2459. *result = varResult;
  2460. }
  2461. #if ENABLE_TTD
  2462. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2463. {
  2464. _actionEntryPopper.SetResult(result);
  2465. }
  2466. #endif
  2467. }
  2468. return JsNoError;
  2469. });
  2470. }
  2471. JsErrorCode RunScriptCore(const char *script, JsSourceContext sourceContext,
  2472. const char *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
  2473. bool isSourceModule, JsValueRef *result)
  2474. {
  2475. utf8::NarrowToWide url((LPCSTR)sourceUrl);
  2476. if (!url)
  2477. {
  2478. return JsErrorOutOfMemory;
  2479. }
  2480. return RunScriptCore(nullptr, reinterpret_cast<const byte*>(script), strlen(script),
  2481. LoadScriptFlag_Utf8Source, sourceContext, url, parseOnly, parseAttributes,
  2482. isSourceModule, result);
  2483. }
  2484. JsErrorCode RunScriptCore(const WCHAR *script, JsSourceContext sourceContext,
  2485. const WCHAR *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
  2486. bool isSourceModule, JsValueRef *result)
  2487. {
  2488. return RunScriptCore(nullptr, reinterpret_cast<const byte*>(script),
  2489. wcslen(script) * sizeof(WCHAR),
  2490. LoadScriptFlag_None, sourceContext, sourceUrl, parseOnly,
  2491. parseAttributes, isSourceModule, result);
  2492. }
  2493. #ifdef _WIN32
  2494. CHAKRA_API JsParseScript(_In_z_ const WCHAR * script, _In_ JsSourceContext sourceContext,
  2495. _In_z_ const WCHAR *sourceUrl, _Out_ JsValueRef * result)
  2496. {
  2497. return RunScriptCore(script, sourceContext, sourceUrl, true,
  2498. JsParseScriptAttributeNone, false /*isModule*/, result);
  2499. }
  2500. CHAKRA_API JsParseScriptWithAttributes(
  2501. _In_z_ const WCHAR *script,
  2502. _In_ JsSourceContext sourceContext,
  2503. _In_z_ const WCHAR *sourceUrl,
  2504. _In_ JsParseScriptAttributes parseAttributes,
  2505. _Out_ JsValueRef *result)
  2506. {
  2507. return RunScriptCore(script, sourceContext, sourceUrl, true,
  2508. parseAttributes, false /*isModule*/, result);
  2509. }
  2510. CHAKRA_API JsRunScript(_In_z_ const WCHAR * script, _In_ JsSourceContext sourceContext,
  2511. _In_z_ const WCHAR *sourceUrl, _Out_ JsValueRef * result)
  2512. {
  2513. return RunScriptCore(script, sourceContext, sourceUrl, false,
  2514. JsParseScriptAttributeNone, false /*isModule*/, result);
  2515. }
  2516. CHAKRA_API JsExperimentalApiRunModule(_In_z_ const WCHAR * script,
  2517. _In_ JsSourceContext sourceContext, _In_z_ const WCHAR *sourceUrl,
  2518. _Out_ JsValueRef * result)
  2519. {
  2520. return RunScriptCore(script, sourceContext, sourceUrl, false,
  2521. JsParseScriptAttributeNone, true, result);
  2522. }
  2523. #endif
  2524. JsErrorCode JsSerializeScriptCore(const byte *script, size_t cb,
  2525. LoadScriptFlag loadScriptFlag, BYTE *functionTable, int functionTableSize,
  2526. unsigned char *buffer, unsigned int *bufferSize, JsValueRef scriptSource)
  2527. {
  2528. Js::JavascriptFunction *function;
  2529. CompileScriptException se;
  2530. JsErrorCode errorCode = ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
  2531. PARAM_NOT_NULL(script);
  2532. PARAM_NOT_NULL(bufferSize);
  2533. if (*bufferSize > 0)
  2534. {
  2535. PARAM_NOT_NULL(buffer);
  2536. ZeroMemory(buffer, *bufferSize);
  2537. }
  2538. if (scriptContext->IsScriptContextInDebugMode())
  2539. {
  2540. return JsErrorCannotSerializeDebugScript;
  2541. }
  2542. SourceContextInfo * sourceContextInfo = scriptContext->GetSourceContextInfo(JS_SOURCE_CONTEXT_NONE, nullptr);
  2543. Assert(sourceContextInfo != nullptr);
  2544. const int chsize = (loadScriptFlag & LoadScriptFlag_Utf8Source) ? sizeof(utf8char_t) : sizeof(WCHAR);
  2545. SRCINFO si = {
  2546. /* sourceContextInfo */ sourceContextInfo,
  2547. /* dlnHost */ 0,
  2548. /* ulColumnHost */ 0,
  2549. /* lnMinHost */ 0,
  2550. /* ichMinHost */ 0,
  2551. /* ichLimHost */ static_cast<ULONG>(cb / chsize), // OK to truncate since this is used to limit sourceText in debugDocument/compilation errors.
  2552. /* ulCharOffset */ 0,
  2553. /* mod */ kmodGlobal,
  2554. /* grfsi */ 0
  2555. };
  2556. bool isSerializeByteCodeForLibrary = false;
  2557. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2558. isSerializeByteCodeForLibrary = JsrtContext::GetCurrent()->GetRuntime()->IsSerializeByteCodeForLibrary();
  2559. #endif
  2560. Js::Utf8SourceInfo* sourceInfo = nullptr;
  2561. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_disableDeferredParse);
  2562. if (isSerializeByteCodeForLibrary)
  2563. {
  2564. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_isByteCodeBufferForLibrary);
  2565. }
  2566. else
  2567. {
  2568. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Expression);
  2569. }
  2570. function = scriptContext->LoadScript(script, cb, &si, &se, &sourceInfo,
  2571. Js::Constants::GlobalCode, loadScriptFlag, scriptSource);
  2572. return JsNoError;
  2573. });
  2574. if (errorCode != JsNoError)
  2575. {
  2576. return errorCode;
  2577. }
  2578. return ContextAPIWrapper_NoRecord<false>([&](Js::ScriptContext* scriptContext) -> JsErrorCode {
  2579. if (function == nullptr)
  2580. {
  2581. HandleScriptCompileError(scriptContext, &se);
  2582. return JsErrorScriptCompile;
  2583. }
  2584. // Could we have a deserialized function in this case?
  2585. // If we are going to serialize it, a check isn't to expensive
  2586. if (CONFIG_FLAG(ForceSerialized) && function->GetFunctionProxy() != nullptr) {
  2587. function->GetFunctionProxy()->EnsureDeserialized();
  2588. }
  2589. Js::FunctionBody *functionBody = function->GetFunctionBody();
  2590. const Js::Utf8SourceInfo *sourceInfo = functionBody->GetUtf8SourceInfo();
  2591. size_t cSourceCodeLength = sourceInfo->GetCbLength(_u("JsSerializeScript"));
  2592. // truncation of code length can lead to accessing random memory. Reject the call.
  2593. if (cSourceCodeLength > DWORD_MAX)
  2594. {
  2595. return JsErrorOutOfMemory;
  2596. }
  2597. LPCUTF8 utf8Code = sourceInfo->GetSource(_u("JsSerializeScript"));
  2598. DWORD dwFlags = 0;
  2599. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2600. dwFlags = JsrtContext::GetCurrent()->GetRuntime()->IsSerializeByteCodeForLibrary() ? GENERATE_BYTE_CODE_BUFFER_LIBRARY : 0;
  2601. #endif
  2602. BEGIN_TEMP_ALLOCATOR(tempAllocator, scriptContext, _u("ByteCodeSerializer"));
  2603. // We cast buffer size to DWORD* because on Windows, DWORD = unsigned long = unsigned int
  2604. // On 64-bit clang on linux, this is not true, unsigned long is larger than unsigned int
  2605. // However, the PAL defines DWORD for us on linux as unsigned int so the cast is safe here.
  2606. HRESULT hr = Js::ByteCodeSerializer::SerializeToBuffer(scriptContext,
  2607. tempAllocator, static_cast<DWORD>(cSourceCodeLength), utf8Code,
  2608. functionBody, functionBody->GetHostSrcInfo(), false, &buffer,
  2609. (DWORD*) bufferSize, dwFlags);
  2610. END_TEMP_ALLOCATOR(tempAllocator, scriptContext);
  2611. if (SUCCEEDED(hr))
  2612. {
  2613. return JsNoError;
  2614. }
  2615. else
  2616. {
  2617. return JsErrorScriptCompile;
  2618. }
  2619. });
  2620. }
  2621. CHAKRA_API JsSerializeScript(_In_z_ const WCHAR *script, _Out_writes_to_opt_(*bufferSize,
  2622. *bufferSize) unsigned char *buffer,
  2623. _Inout_ unsigned int *bufferSize)
  2624. {
  2625. return JsSerializeScriptCore((const byte*)script, wcslen(script) * sizeof(WCHAR),
  2626. LoadScriptFlag_None, nullptr, 0, buffer, bufferSize, nullptr);
  2627. }
  2628. template <typename TLoadCallback, typename TUnloadCallback>
  2629. JsErrorCode RunSerializedScriptCore(
  2630. TLoadCallback scriptLoadCallback, TUnloadCallback scriptUnloadCallback,
  2631. JsSourceContext scriptLoadSourceContext, // only used by scriptLoadCallback
  2632. unsigned char *buffer, JsValueRef bufferVal,
  2633. JsSourceContext sourceContext, const WCHAR *sourceUrl,
  2634. bool parseOnly, JsValueRef *result)
  2635. {
  2636. Js::JavascriptFunction *function;
  2637. JsErrorCode errorCode = ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
  2638. if (result != nullptr)
  2639. {
  2640. *result = nullptr;
  2641. }
  2642. PARAM_NOT_NULL(buffer);
  2643. PARAM_NOT_NULL(sourceUrl);
  2644. Js::ISourceHolder *sourceHolder = nullptr;
  2645. PARAM_NOT_NULL(scriptLoadCallback);
  2646. PARAM_NOT_NULL(scriptUnloadCallback);
  2647. typedef Js::JsrtSourceHolder<TLoadCallback, TUnloadCallback> TSourceHolder;
  2648. sourceHolder = RecyclerNewFinalized(scriptContext->GetRecycler(), TSourceHolder,
  2649. scriptLoadCallback, scriptUnloadCallback, scriptLoadSourceContext, bufferVal);
  2650. SourceContextInfo *sourceContextInfo;
  2651. SRCINFO *hsi;
  2652. Js::FunctionBody *functionBody = nullptr;
  2653. HRESULT hr;
  2654. sourceContextInfo = scriptContext->GetSourceContextInfo(sourceContext, nullptr);
  2655. if (sourceContextInfo == nullptr)
  2656. {
  2657. sourceContextInfo = scriptContext->CreateSourceContextInfo(sourceContext, sourceUrl,
  2658. wcslen(sourceUrl), nullptr);
  2659. }
  2660. SRCINFO si = {
  2661. /* sourceContextInfo */ sourceContextInfo,
  2662. /* dlnHost */ 0,
  2663. /* ulColumnHost */ 0,
  2664. /* lnMinHost */ 0,
  2665. /* ichMinHost */ 0,
  2666. /* ichLimHost */ 0, // xplat-todo: need to compute this?
  2667. /* ulCharOffset */ 0,
  2668. /* mod */ kmodGlobal,
  2669. /* grfsi */ 0
  2670. };
  2671. uint32 flags = 0;
  2672. if (CONFIG_FLAG(CreateFunctionProxy) && !scriptContext->IsProfiling())
  2673. {
  2674. flags = fscrAllowFunctionProxy;
  2675. }
  2676. hsi = scriptContext->AddHostSrcInfo(&si);
  2677. hr = Js::ByteCodeSerializer::DeserializeFromBuffer(scriptContext, flags, sourceHolder,
  2678. hsi, buffer, nullptr, &functionBody);
  2679. if (FAILED(hr))
  2680. {
  2681. return JsErrorBadSerializedScript;
  2682. }
  2683. function = scriptContext->GetLibrary()->CreateScriptFunction(functionBody);
  2684. JsrtContext * context = JsrtContext::GetCurrent();
  2685. context->OnScriptLoad(function, functionBody->GetUtf8SourceInfo(), nullptr);
  2686. return JsNoError;
  2687. });
  2688. if (errorCode != JsNoError)
  2689. {
  2690. return errorCode;
  2691. }
  2692. return ContextAPIWrapper_NoRecord<false>([&](Js::ScriptContext* scriptContext) -> JsErrorCode {
  2693. if (parseOnly)
  2694. {
  2695. PARAM_NOT_NULL(result);
  2696. *result = function;
  2697. }
  2698. else
  2699. {
  2700. Js::Var varResult = function->CallRootFunction(Js::Arguments(0, nullptr), scriptContext, true);
  2701. if (result != nullptr)
  2702. {
  2703. *result = varResult;
  2704. }
  2705. }
  2706. return JsNoError;
  2707. });
  2708. }
  2709. static void CHAKRA_CALLBACK DummyScriptUnloadCallback(_In_ JsSourceContext sourceContext)
  2710. {
  2711. // Do nothing
  2712. }
  2713. #ifdef _WIN32
  2714. static bool CHAKRA_CALLBACK DummyScriptLoadSourceCallback(_In_ JsSourceContext sourceContext, _Outptr_result_z_ const WCHAR** scriptBuffer)
  2715. {
  2716. // sourceContext is actually the script source pointer
  2717. *scriptBuffer = reinterpret_cast<const WCHAR*>(sourceContext);
  2718. return true;
  2719. }
  2720. CHAKRA_API JsParseSerializedScript(_In_z_ const WCHAR * script, _In_ unsigned char *buffer,
  2721. _In_ JsSourceContext sourceContext,
  2722. _In_z_ const WCHAR *sourceUrl,
  2723. _Out_ JsValueRef * result)
  2724. {
  2725. return RunSerializedScriptCore(
  2726. DummyScriptLoadSourceCallback, DummyScriptUnloadCallback,
  2727. reinterpret_cast<JsSourceContext>(script), // use script source pointer as scriptLoadSourceContext
  2728. buffer, nullptr, sourceContext, sourceUrl, true, result);
  2729. }
  2730. CHAKRA_API JsRunSerializedScript(_In_z_ const WCHAR * script, _In_ unsigned char *buffer,
  2731. _In_ JsSourceContext sourceContext,
  2732. _In_z_ const WCHAR *sourceUrl,
  2733. _Out_ JsValueRef * result)
  2734. {
  2735. return RunSerializedScriptCore(
  2736. DummyScriptLoadSourceCallback, DummyScriptUnloadCallback,
  2737. reinterpret_cast<JsSourceContext>(script), // use script source pointer as scriptLoadSourceContext
  2738. buffer, nullptr, sourceContext, sourceUrl, false, result);
  2739. }
  2740. CHAKRA_API JsParseSerializedScriptWithCallback(_In_ JsSerializedScriptLoadSourceCallback scriptLoadCallback,
  2741. _In_ JsSerializedScriptUnloadCallback scriptUnloadCallback,
  2742. _In_ unsigned char *buffer, _In_ JsSourceContext sourceContext,
  2743. _In_z_ const WCHAR *sourceUrl, _Out_ JsValueRef * result)
  2744. {
  2745. return RunSerializedScriptCore(
  2746. scriptLoadCallback, scriptUnloadCallback,
  2747. sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
  2748. buffer, nullptr, sourceContext, sourceUrl, true, result);
  2749. }
  2750. CHAKRA_API JsRunSerializedScriptWithCallback(_In_ JsSerializedScriptLoadSourceCallback scriptLoadCallback,
  2751. _In_ JsSerializedScriptUnloadCallback scriptUnloadCallback,
  2752. _In_ unsigned char *buffer, _In_ JsSourceContext sourceContext,
  2753. _In_z_ const WCHAR *sourceUrl, _Out_opt_ JsValueRef * result)
  2754. {
  2755. return RunSerializedScriptCore(
  2756. scriptLoadCallback, scriptUnloadCallback,
  2757. sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
  2758. buffer, nullptr, sourceContext, sourceUrl, false, result);
  2759. }
  2760. #endif // _WIN32
  2761. /////////////////////
  2762. CHAKRA_API JsTTDCreateRecordRuntime(_In_ JsRuntimeAttributes attributes, _In_reads_(infoUriCount) const byte* infoUri, _In_ size_t infoUriCount, _In_ size_t snapInterval, _In_ size_t snapHistoryLength,
  2763. _In_ JsTTDInitializeForWriteLogStreamCallback writeInitializeFunction, _In_ TTDOpenResourceStreamCallback openResourceStream,
  2764. _In_ JsTTDReadBytesFromStreamCallback readBytesFromStream, _In_ JsTTDWriteBytesToStreamCallback writeBytesToStream, _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
  2765. _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtime)
  2766. {
  2767. #if !ENABLE_TTD
  2768. return JsErrorCategoryUsage;
  2769. #else
  2770. if(snapInterval > UINT32_MAX || snapHistoryLength > UINT32_MAX)
  2771. {
  2772. return JsErrorInvalidArgument;
  2773. }
  2774. return CreateRuntimeCore(attributes, infoUri, infoUriCount, true, false, false, (uint32)snapInterval, (uint32)snapHistoryLength,
  2775. writeInitializeFunction, openResourceStream, readBytesFromStream, writeBytesToStream, flushAndCloseStream,
  2776. threadService, runtime);
  2777. #endif
  2778. }
  2779. CHAKRA_API JsTTDCreateReplayRuntime(_In_ JsRuntimeAttributes attributes, _In_reads_(infoUriCount) const byte* infoUri, _In_ size_t infoUriCount, _In_ bool enableDebugging,
  2780. _In_ JsTTDInitializeForWriteLogStreamCallback writeInitializeFunction, _In_ TTDOpenResourceStreamCallback openResourceStream,
  2781. _In_ JsTTDReadBytesFromStreamCallback readBytesFromStream, _In_ JsTTDWriteBytesToStreamCallback writeBytesToStream, _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
  2782. _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtime)
  2783. {
  2784. #if !ENABLE_TTD
  2785. return JsErrorCategoryUsage;
  2786. #else
  2787. return CreateRuntimeCore(attributes, infoUri, infoUriCount, false, true, enableDebugging, UINT_MAX, UINT_MAX,
  2788. writeInitializeFunction, openResourceStream, readBytesFromStream, writeBytesToStream, flushAndCloseStream,
  2789. threadService, runtime);
  2790. #endif
  2791. }
  2792. CHAKRA_API JsTTDCreateContext(_In_ JsRuntimeHandle runtimeHandle, _In_ bool useRuntimeTTDMode, _Out_ JsContextRef *newContext)
  2793. {
  2794. #if !ENABLE_TTD
  2795. return JsErrorCategoryUsage;
  2796. #else
  2797. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  2798. PARAM_NOT_NULL(newContext);
  2799. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2800. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  2801. ThreadContext * threadContext = runtime->GetThreadContext();
  2802. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Need to create in TTD Mode.");
  2803. bool inRecord = false;
  2804. bool activelyRecording = false;
  2805. bool inReplay = false;
  2806. TTDRecorder dummyActionEntryPopper;
  2807. if(useRuntimeTTDMode)
  2808. {
  2809. threadContext->TTDLog->GetModesForExplicitContextCreate(inRecord, activelyRecording, inReplay);
  2810. }
  2811. return CreateContextCore(runtimeHandle, dummyActionEntryPopper, inRecord, activelyRecording, inReplay, newContext);
  2812. });
  2813. #endif
  2814. }
  2815. CHAKRA_API JsTTDNotifyContextDestroy(_In_ JsContextRef context)
  2816. {
  2817. #if !ENABLE_TTD
  2818. return JsErrorCategoryUsage;
  2819. #else
  2820. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  2821. if(threadContext->IsRuntimeInTTDMode())
  2822. {
  2823. Js::ScriptContext* ctx = static_cast<JsrtContext*>(context)->GetScriptContext();
  2824. threadContext->TTDContext->NotifyCtxDestroyInRecord(ctx);
  2825. }
  2826. return JsNoError;
  2827. #endif
  2828. }
  2829. CHAKRA_API JsTTDStart()
  2830. {
  2831. #if !ENABLE_TTD
  2832. return JsErrorCategoryUsage;
  2833. #else
  2834. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2835. JsErrorCode cCheck = CheckContext(currentContext, true);
  2836. TTDAssert(cCheck == JsNoError, "Must have valid context when starting TTD.");
  2837. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  2838. TTDAssert(scriptContext->IsTTDRecordOrReplayModeEnabled(), "Need to create in TTD Record Mode.");
  2839. #if ENABLE_NATIVE_CODEGEN
  2840. TTDAssert(JITManager::GetJITManager() == nullptr || !JITManager::GetJITManager()->IsOOPJITEnabled(), "TTD cannot run with OOP JIT yet!!!");
  2841. #endif
  2842. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  2843. {
  2844. if(scriptContext->IsTTDRecordModeEnabled())
  2845. {
  2846. scriptContext->GetThreadContext()->TTDLog->DoSnapshotExtract();
  2847. }
  2848. //Want to verify that we are at top-level of dispatch
  2849. scriptContext->GetThreadContext()->TTDLog->PushMode(TTD::TTDMode::CurrentlyEnabled);
  2850. return JsNoError;
  2851. });
  2852. #endif
  2853. }
  2854. CHAKRA_API JsTTDStop()
  2855. {
  2856. #if !ENABLE_TTD
  2857. return JsErrorCategoryUsage;
  2858. #else
  2859. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2860. JsErrorCode cCheck = CheckContext(currentContext, true);
  2861. TTDAssert(cCheck == JsNoError, "Must have valid context when starting TTD.");
  2862. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  2863. TTDAssert(scriptContext->IsTTDRecordOrReplayModeEnabled(), "Need to create in TTD mode.");
  2864. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  2865. {
  2866. scriptContext->GetThreadContext()->TTDLog->PopMode(TTD::TTDMode::CurrentlyEnabled);
  2867. if(scriptContext->IsTTDRecordModeEnabled())
  2868. {
  2869. scriptContext->GetThreadContext()->TTDLog->UnloadAllLogData();
  2870. }
  2871. return JsNoError;
  2872. });
  2873. #endif
  2874. }
  2875. CHAKRA_API JsTTDEmitRecording()
  2876. {
  2877. #if !ENABLE_TTD
  2878. return JsErrorCategoryUsage;
  2879. #else
  2880. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2881. JsErrorCode cCheck = CheckContext(currentContext, true);
  2882. TTDAssert(cCheck == JsNoError, "Must have valid context when starting TTD.");
  2883. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  2884. TTDAssert(scriptContext->ShouldPerformRecordAction(), "Need to be running in TTD mode.");
  2885. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  2886. {
  2887. scriptContext->GetThreadContext()->TTDLog->EmitLog();
  2888. return JsNoError;
  2889. });
  2890. #endif
  2891. }
  2892. CHAKRA_API JsTTDPauseTimeTravelBeforeRuntimeOperation()
  2893. {
  2894. #if !ENABLE_TTD
  2895. return JsErrorCategoryUsage;
  2896. #else
  2897. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2898. JsErrorCode cCheck = CheckContext(currentContext, true);
  2899. TTDAssert(cCheck == JsNoError, "Must have valid context when changing debugger mode.");
  2900. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  2901. ThreadContext* threadContext = scriptContext->GetThreadContext();
  2902. if(threadContext->IsRuntimeInTTDMode())
  2903. {
  2904. threadContext->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionDebuggerAction);
  2905. }
  2906. return JsNoError;
  2907. #endif
  2908. }
  2909. CHAKRA_API JsTTDReStartTimeTravelAfterRuntimeOperation()
  2910. {
  2911. #if !ENABLE_TTD
  2912. return JsErrorCategoryUsage;
  2913. #else
  2914. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2915. JsErrorCode cCheck = CheckContext(currentContext, true);
  2916. TTDAssert(cCheck == JsNoError, "Must have valid context when changing debugger mode.");
  2917. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  2918. ThreadContext* threadContext = scriptContext->GetThreadContext();
  2919. if(threadContext->IsRuntimeInTTDMode())
  2920. {
  2921. threadContext->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionDebuggerAction);
  2922. }
  2923. return JsNoError;
  2924. #endif
  2925. }
  2926. CHAKRA_API JsTTDNotifyYield()
  2927. {
  2928. #if !ENABLE_TTD
  2929. return JsErrorCategoryUsage;
  2930. #else
  2931. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2932. JsErrorCode cCheck = CheckContext(currentContext, true);
  2933. if(cCheck != JsNoError)
  2934. {
  2935. return JsNoError; //we are ok just aren't going to do any TTD related work
  2936. }
  2937. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  2938. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  2939. {
  2940. if(scriptContext->IsTTDRecordModeEnabled())
  2941. {
  2942. JsUtil::List<TTD::DeadScriptLogTagInfo, HeapAllocator>& deadScripts = scriptContext->GetThreadContext()->TTDContext->GetTTDDeadContextsForRecord();
  2943. if(scriptContext->ShouldPerformRecordAction())
  2944. {
  2945. for(int32 i = 0; i < deadScripts.Count(); ++i)
  2946. {
  2947. const TTD::DeadScriptLogTagInfo& deadCtx = deadScripts.Item(i);
  2948. scriptContext->GetThreadContext()->TTDLog->RecordJsRTDeadScriptEvent(deadCtx);
  2949. }
  2950. }
  2951. deadScripts.Clear();
  2952. }
  2953. if(scriptContext->IsTTDRecordModeEnabled())
  2954. {
  2955. scriptContext->GetThreadContext()->TTDLog->RecordJsRTEventLoopYieldPoint();
  2956. }
  2957. return JsNoError;
  2958. });
  2959. #endif
  2960. }
  2961. CHAKRA_API JsTTDHostExit(_In_ int statusCode)
  2962. {
  2963. #if !ENABLE_TTD
  2964. return JsErrorCategoryUsage;
  2965. #else
  2966. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2967. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTHostExitProcess, statusCode);
  2968. return JsNoError;
  2969. });
  2970. #endif
  2971. }
  2972. CHAKRA_API JsTTDRawBufferCopySyncIndirect(_In_ JsValueRef dst, _In_ size_t dstIndex, _In_ JsValueRef src, _In_ size_t srcIndex, _In_ size_t count)
  2973. {
  2974. #if !ENABLE_TTD
  2975. return JsErrorCategoryUsage;
  2976. #else
  2977. if(dstIndex > UINT32_MAX || srcIndex > UINT32_MAX || count > UINT32_MAX)
  2978. {
  2979. return JsErrorInvalidArgument;
  2980. }
  2981. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2982. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferCopySync, dst, (uint32)dstIndex, src, (uint32)srcIndex, (uint32)count);
  2983. return JsNoError;
  2984. });
  2985. #endif
  2986. }
  2987. CHAKRA_API JsTTDRawBufferModifySyncIndirect(_In_ JsValueRef buffer, _In_ size_t index, _In_ size_t count)
  2988. {
  2989. #if !ENABLE_TTD
  2990. return JsErrorCategoryUsage;
  2991. #else
  2992. if(index > UINT32_MAX || count > UINT32_MAX)
  2993. {
  2994. return JsErrorInvalidArgument;
  2995. }
  2996. return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2997. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferModifySync, buffer, (uint32)index, (uint32)count);
  2998. return JsNoError;
  2999. });
  3000. #endif
  3001. }
  3002. CHAKRA_API JsTTDRawBufferAsyncModificationRegister(_In_ JsValueRef instance, _In_ byte* initialModPos)
  3003. {
  3004. #if !ENABLE_TTD
  3005. return JsErrorCategoryUsage;
  3006. #else
  3007. JsValueRef addRefObj = nullptr;
  3008. JsErrorCode addRefResult = ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3009. if (scriptContext->IsTTDRecordModeEnabled())
  3010. {
  3011. TTDAssert(Js::ArrayBuffer::Is(instance), "Not array buffer object!!!");
  3012. Js::ArrayBuffer* dstBuff = Js::ArrayBuffer::FromVar(instance);
  3013. addRefObj = dstBuff;
  3014. TTDAssert(dstBuff->GetBuffer() <= initialModPos && initialModPos < dstBuff->GetBuffer() + dstBuff->GetByteLength(), "Not array buffer object!!!");
  3015. TTDAssert(initialModPos - dstBuff->GetBuffer() < UINT32_MAX, "This is really big!!!");
  3016. ptrdiff_t index = initialModPos - Js::ArrayBuffer::FromVar(instance)->GetBuffer();
  3017. scriptContext->TTDContextInfo->AddToAsyncPendingList(dstBuff, (uint32)index);
  3018. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferAsyncModificationRegister, instance, (uint32)index);
  3019. }
  3020. return JsNoError;
  3021. });
  3022. if(addRefResult != JsNoError)
  3023. {
  3024. return addRefResult;
  3025. }
  3026. //We need to root add ref so we can find this during replay!!!
  3027. if(addRefObj == nullptr)
  3028. {
  3029. return JsNoError;
  3030. }
  3031. else
  3032. {
  3033. return JsAddRef(addRefObj, nullptr);
  3034. }
  3035. #endif
  3036. }
  3037. CHAKRA_API JsTTDRawBufferAsyncModifyComplete(_In_ byte* finalModPos)
  3038. {
  3039. #if !ENABLE_TTD
  3040. return JsErrorCategoryUsage;
  3041. #else
  3042. JsValueRef releaseObj = nullptr;
  3043. JsErrorCode releaseStatus = ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3044. if (scriptContext->IsTTDRecordModeEnabled())
  3045. {
  3046. TTD::TTDPendingAsyncBufferModification pendingAsyncInfo = { 0 };
  3047. scriptContext->TTDContextInfo->GetFromAsyncPendingList(&pendingAsyncInfo, finalModPos);
  3048. Js::ArrayBuffer* dstBuff = Js::ArrayBuffer::FromVar(pendingAsyncInfo.ArrayBufferVar);
  3049. releaseObj = dstBuff;
  3050. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferAsyncModifyComplete, pendingAsyncInfo, finalModPos);
  3051. }
  3052. return JsNoError;
  3053. });
  3054. if(releaseStatus != JsNoError)
  3055. {
  3056. return releaseStatus;
  3057. }
  3058. //We need to root release ref so we can free this in replay if needed!!!
  3059. if(releaseObj == nullptr)
  3060. {
  3061. return JsNoError;
  3062. }
  3063. else
  3064. {
  3065. return JsRelease(releaseObj, nullptr);
  3066. }
  3067. #endif
  3068. }
  3069. CHAKRA_API JsTTDCheckAndAssertIfTTDRunning(_In_ const char* msg)
  3070. {
  3071. #if ENABLE_TTD
  3072. JsrtContext* context = JsrtContext::GetCurrent();
  3073. TTDAssert(context == nullptr || !context->GetScriptContext()->ShouldPerformRecordAction(), msg);
  3074. #endif
  3075. return JsNoError;
  3076. }
  3077. CHAKRA_API JsTTDGetSnapTimeTopLevelEventMove(_In_ JsRuntimeHandle runtimeHandle,
  3078. _In_ JsTTDMoveMode moveMode, _In_opt_ uint32_t kthEvent,
  3079. _Inout_ int64_t* targetEventTime, _Out_ int64_t* targetStartSnapTime,
  3080. _Out_opt_ int64_t* targetEndSnapTime)
  3081. {
  3082. #if !ENABLE_TTD
  3083. return JsErrorCategoryUsage;
  3084. #else
  3085. JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3086. ThreadContext* threadContext = runtime->GetThreadContext();
  3087. *targetStartSnapTime = -1;
  3088. if(targetEndSnapTime != nullptr)
  3089. {
  3090. *targetEndSnapTime = -1;
  3091. }
  3092. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3093. //If we requested a move to a specific event then extract the event count and try to find it
  3094. if((moveMode & JsTTDMoveMode::JsTTDMoveFirstEvent) == JsTTDMoveMode::JsTTDMoveFirstEvent)
  3095. {
  3096. *targetEventTime = threadContext->TTDLog->GetFirstEventTimeInLog();
  3097. if(*targetEventTime == -1)
  3098. {
  3099. return JsErrorCategoryUsage;
  3100. }
  3101. }
  3102. else if((moveMode & JsTTDMoveMode::JsTTDMoveLastEvent) == JsTTDMoveMode::JsTTDMoveLastEvent)
  3103. {
  3104. *targetEventTime = threadContext->TTDLog->GetLastEventTimeInLog();
  3105. if(*targetEventTime == -1)
  3106. {
  3107. return JsErrorCategoryUsage;
  3108. }
  3109. }
  3110. else if((moveMode & JsTTDMoveMode::JsTTDMoveKthEvent) == JsTTDMoveMode::JsTTDMoveKthEvent)
  3111. {
  3112. *targetEventTime = threadContext->TTDLog->GetKthEventTimeInLog(kthEvent);
  3113. if(*targetEventTime == -1)
  3114. {
  3115. return JsErrorCategoryUsage;
  3116. }
  3117. }
  3118. else
  3119. {
  3120. ;
  3121. }
  3122. #ifdef __APPLE__
  3123. //TODO: Explicit cast of ptr since compiler gets confused -- resolve in PAL later
  3124. static_assert(sizeof(int64_t) == sizeof(int64));
  3125. *targetStartSnapTime = threadContext->TTDLog->FindSnapTimeForEventTime(*targetEventTime, (int64*)targetEndSnapTime);
  3126. #else
  3127. *targetStartSnapTime = threadContext->TTDLog->FindSnapTimeForEventTime(*targetEventTime, targetEndSnapTime);
  3128. #endif
  3129. return JsNoError;
  3130. #endif
  3131. }
  3132. CHAKRA_API JsTTDGetSnapShotBoundInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t targetEventTime, _Out_ int64_t* startSnapTime, _Out_ int64_t* endSnapTime)
  3133. {
  3134. #if !ENABLE_TTD
  3135. return JsErrorCategoryUsage;
  3136. #else
  3137. JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3138. ThreadContext* threadContext = runtime->GetThreadContext();
  3139. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3140. #ifdef __APPLE__
  3141. //TODO: Explicit cast of ptr since compiler gets confused -- resolve in PAL later
  3142. static_assert(sizeof(int64_t) == sizeof(int64));
  3143. threadContext->TTDLog->GetSnapShotBoundInterval(targetEventTime, (int64*)startSnapTime, (int64*)endSnapTime);
  3144. #else
  3145. threadContext->TTDLog->GetSnapShotBoundInterval(targetEventTime, startSnapTime, endSnapTime);
  3146. #endif
  3147. return JsNoError;
  3148. #endif
  3149. }
  3150. CHAKRA_API JsTTDGetPreviousSnapshotInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t currentSnapStartTime, _Out_ int64_t* previousSnapTime)
  3151. {
  3152. #if !ENABLE_TTD
  3153. return JsErrorCategoryUsage;
  3154. #else
  3155. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3156. ThreadContext * threadContext = runtime->GetThreadContext();
  3157. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3158. *previousSnapTime = threadContext->TTDLog->GetPreviousSnapshotInterval(currentSnapStartTime);
  3159. return JsNoError;
  3160. #endif
  3161. }
  3162. #if ENABLE_TTD
  3163. //Helper method for resetting breakpoint info around snapshot inflate
  3164. JsErrorCode TTDHandleBreakpointInfoAndInflate(TTD::EventLog* elog, int64_t snapTime, JsrtRuntime* runtime, ThreadContext* threadContext)
  3165. {
  3166. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  3167. {
  3168. elog->LoadPreservedBPInfo();
  3169. elog->DoSnapshotInflate(snapTime);
  3170. if(elog->GetPerservedBPInfoCount() != 0)
  3171. {
  3172. JsrtDebugManager* jsrtDebugManager = runtime->GetJsrtDebugManager();
  3173. TTD_LOG_PTR_ID* ctxIdList = elog->GetPerservedBPInfoScriptArray();
  3174. TTD::TTDebuggerSourceLocation** locationList = elog->GetPerservedBPInfoLocationArray();
  3175. for(uint32 i = 0; i < elog->GetPerservedBPInfoCount(); ++i)
  3176. {
  3177. const TTD::TTDebuggerSourceLocation* bpLocation = locationList[i];
  3178. Js::ScriptContext* bpContext = threadContext->TTDContext->LookupContextForScriptId(ctxIdList[i]);
  3179. if(bpContext != nullptr)
  3180. {
  3181. Js::FunctionBody* body = bpLocation->ResolveAssociatedSourceInfo(bpContext);
  3182. Js::Utf8SourceInfo* utf8SourceInfo = body->GetUtf8SourceInfo();
  3183. bool isNewBP = false;
  3184. jsrtDebugManager->SetBreakpointHelper_TTD(bpContext, utf8SourceInfo, bpLocation->GetLine(), bpLocation->GetColumn(), &isNewBP);
  3185. }
  3186. }
  3187. }
  3188. elog->UnLoadPreservedBPInfo();
  3189. return JsNoError;
  3190. });
  3191. }
  3192. #endif
  3193. CHAKRA_API JsTTDPreExecuteSnapShotInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t startSnapTime, _In_ int64_t endSnapTime, _In_ JsTTDMoveMode moveMode, _Out_ int64_t* newTargetEventTime)
  3194. {
  3195. #if !ENABLE_TTD
  3196. return JsErrorCategoryUsage;
  3197. #else
  3198. *newTargetEventTime = -1;
  3199. JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3200. ThreadContext* threadContext = runtime->GetThreadContext();
  3201. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3202. TTD::EventLog* elog = threadContext->TTDLog;
  3203. JsErrorCode res = JsNoError;
  3204. JsErrorCode inflateStatus = TTDHandleBreakpointInfoAndInflate(elog, startSnapTime, runtime, threadContext);
  3205. if(inflateStatus != JsNoError)
  3206. {
  3207. return inflateStatus;
  3208. }
  3209. elog->ClearBPScanInfo();
  3210. elog->PushMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
  3211. elog->PushMode(TTD::TTDMode::DebuggerLogBreakpoints);
  3212. try
  3213. {
  3214. if(endSnapTime == -1)
  3215. {
  3216. elog->ReplayRootEventsToTime(TTD_EVENT_MAXTIME);
  3217. }
  3218. else
  3219. {
  3220. elog->ReplayRootEventsToTime(endSnapTime);
  3221. }
  3222. }
  3223. catch(TTD::TTDebuggerAbortException abortException)
  3224. {
  3225. //If we hit the end of the log or we hit a terminal exception that is fine -- anything else is a problem
  3226. if(!abortException.IsEndOfLog() && !abortException.IsTopLevelException())
  3227. {
  3228. res = JsErrorFatal;
  3229. }
  3230. }
  3231. catch(...) //we are replaying something that should be known to execute successfully so encountering any error is very bad
  3232. {
  3233. res = JsErrorFatal;
  3234. TTDAssert(false, "Unexpected fatal Error");
  3235. }
  3236. elog->PopMode(TTD::TTDMode::DebuggerLogBreakpoints);
  3237. elog->PopMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
  3238. if((moveMode & JsTTDMoveMode::JsTTDMoveScanIntervalForContinue) == JsTTDMoveMode::JsTTDMoveScanIntervalForContinue)
  3239. {
  3240. bool bpFound = elog->TryFindAndSetPreviousBP();
  3241. if(bpFound)
  3242. {
  3243. *newTargetEventTime = elog->GetPendingTTDBPTargetEventTime();
  3244. }
  3245. }
  3246. elog->ClearBPScanInfo();
  3247. return res;
  3248. #endif
  3249. }
  3250. CHAKRA_API JsTTDMoveToTopLevelEvent(_In_ JsRuntimeHandle runtimeHandle, _In_ JsTTDMoveMode moveMode, _In_ int64_t snapshotTime, _In_ int64_t eventTime)
  3251. {
  3252. #if !ENABLE_TTD
  3253. return JsErrorCategoryUsage;
  3254. #else
  3255. JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3256. ThreadContext* threadContext = runtime->GetThreadContext();
  3257. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3258. TTD::EventLog* elog = threadContext->TTDLog;
  3259. JsErrorCode res = JsNoError;
  3260. JsErrorCode inflateStatus = TTDHandleBreakpointInfoAndInflate(elog, snapshotTime, runtime, threadContext);
  3261. if(inflateStatus != JsNoError)
  3262. {
  3263. return inflateStatus;
  3264. }
  3265. elog->PushMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
  3266. try
  3267. {
  3268. elog->ReplayRootEventsToTime(eventTime);
  3269. elog->DoRtrSnapIfNeeded();
  3270. }
  3271. catch(...) //we are replaying something that should be known to execute successfully so encountering any error is very bad
  3272. {
  3273. res = JsErrorFatal;
  3274. TTDAssert(false, "Unexpected fatal Error");
  3275. }
  3276. elog->PopMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
  3277. return res;
  3278. #endif
  3279. }
  3280. CHAKRA_API JsTTDReplayExecution(_Inout_ JsTTDMoveMode* moveMode, _Out_ int64_t* rootEventTime)
  3281. {
  3282. #if !ENABLE_TTD
  3283. return JsErrorCategoryUsage;
  3284. #else
  3285. JsrtContext *currentContext = JsrtContext::GetCurrent();
  3286. JsErrorCode cCheck = CheckContext(currentContext, true);
  3287. TTDAssert(cCheck == JsNoError, "This shouldn't happen!!!");
  3288. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  3289. ThreadContext* threadContext = scriptContext->GetThreadContext();
  3290. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3291. TTD::EventLog* elog = threadContext->TTDLog;
  3292. if((*moveMode & JsTTDMoveMode::JsTTDMoveBreakOnEntry) == JsTTDMoveMode::JsTTDMoveBreakOnEntry)
  3293. {
  3294. elog->SetBreakOnFirstUserCode();
  3295. }
  3296. //reset any breakpoints that we preserved accross a TTD move
  3297. if(elog->HasPendingTTDBP())
  3298. {
  3299. GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  3300. JsrtDebugManager* jsrtDebugManager = currentContext->GetRuntime()->GetJsrtDebugManager();
  3301. //If the log has a BP requested then we should set the actual bp here
  3302. if(elog->HasPendingTTDBP())
  3303. {
  3304. TTD::TTDebuggerSourceLocation bpLocation;
  3305. elog->GetPendingTTDBPInfo(bpLocation);
  3306. Js::FunctionBody* body = bpLocation.ResolveAssociatedSourceInfo(scriptContext);
  3307. Js::Utf8SourceInfo* utf8SourceInfo = body->GetUtf8SourceInfo();
  3308. bool isNewBP = false;
  3309. Js::BreakpointProbe* probe = jsrtDebugManager->SetBreakpointHelper_TTD(scriptContext, utf8SourceInfo, bpLocation.GetLine(), bpLocation.GetColumn(), &isNewBP);
  3310. if(probe != nullptr)
  3311. {
  3312. elog->SetActiveBP(probe->GetId(), isNewBP, bpLocation);
  3313. }
  3314. //Finally clear the pending BP info so we don't get confused later
  3315. elog->ClearPendingTTDBPInfo();
  3316. }
  3317. return JsNoError;
  3318. });
  3319. }
  3320. *moveMode = JsTTDMoveMode::JsTTDMoveNone;
  3321. *rootEventTime = -1;
  3322. JsErrorCode res = JsNoError;
  3323. try
  3324. {
  3325. elog->ReplayRootEventsToTime(TTD_EVENT_MAXTIME);
  3326. }
  3327. catch(TTD::TTDebuggerAbortException abortException)
  3328. {
  3329. //if the debugger bails out with a move time request set info on the requested event time here
  3330. //rest of breakpoint info should have been set by the debugger callback before aborting
  3331. if (abortException.IsEventTimeMove() || abortException.IsTopLevelException())
  3332. {
  3333. *moveMode = (JsTTDMoveMode)abortException.GetMoveMode();
  3334. *rootEventTime = abortException.GetTargetEventTime();
  3335. if(abortException.IsTopLevelException())
  3336. {
  3337. TTD::TTDebuggerSourceLocation throwLocation;
  3338. elog->GetLastExecutedTimeAndPositionForDebugger(throwLocation);
  3339. elog->SetPendingTTDBPInfo(throwLocation);
  3340. }
  3341. }
  3342. res = abortException.IsTopLevelException() ? JsErrorCategoryScript : JsNoError;
  3343. }
  3344. catch(...)
  3345. {
  3346. res = JsErrorFatal;
  3347. TTDAssert(false, "Unexpected fatal Error");
  3348. }
  3349. return res;
  3350. #endif
  3351. }
  3352. #ifdef CHAKRACOREBUILD_
  3353. template <class SrcChar, class DstChar>
  3354. static void CastCopy(const SrcChar* src, DstChar* dst, size_t count)
  3355. {
  3356. const SrcChar* end = src + count;
  3357. while (src < end)
  3358. {
  3359. *dst++ = static_cast<DstChar>(*src++);
  3360. }
  3361. }
  3362. CHAKRA_API JsCreateString(
  3363. _In_ const char *content,
  3364. _In_ size_t length,
  3365. _Out_ JsValueRef *value)
  3366. {
  3367. PARAM_NOT_NULL(content);
  3368. utf8::NarrowToWide wstr(content, length);
  3369. if (!wstr)
  3370. {
  3371. return JsErrorOutOfMemory;
  3372. }
  3373. return JsPointerToString(wstr, wstr.Length(), value);
  3374. }
  3375. CHAKRA_API JsCreateStringUtf16(
  3376. _In_ const uint16_t *content,
  3377. _In_ size_t length,
  3378. _Out_ JsValueRef *value)
  3379. {
  3380. PARAM_NOT_NULL(content);
  3381. return JsPointerToString(
  3382. reinterpret_cast<const char16*>(content), length, value);
  3383. }
  3384. template <class CopyFunc>
  3385. JsErrorCode WriteStringCopy(
  3386. JsValueRef value,
  3387. int start,
  3388. int length,
  3389. _Out_opt_ size_t* written,
  3390. const CopyFunc& copyFunc)
  3391. {
  3392. if (written)
  3393. {
  3394. *written = 0; // init to 0 for default
  3395. }
  3396. const char16* str = nullptr;
  3397. size_t strLength = 0;
  3398. JsErrorCode errorCode = JsStringToPointer(value, &str, &strLength);
  3399. if (errorCode != JsNoError)
  3400. {
  3401. return errorCode;
  3402. }
  3403. if (start < 0 || (size_t)start > strLength)
  3404. {
  3405. return JsErrorInvalidArgument; // start out of range, no chars written
  3406. }
  3407. size_t count = min(static_cast<size_t>(length), strLength - start);
  3408. if (count == 0)
  3409. {
  3410. return JsNoError; // no chars written
  3411. }
  3412. errorCode = copyFunc(str + start, count, written);
  3413. if (errorCode != JsNoError)
  3414. {
  3415. return errorCode;
  3416. }
  3417. if (written)
  3418. {
  3419. *written = count;
  3420. }
  3421. return JsNoError;
  3422. }
  3423. CHAKRA_API JsCopyStringUtf16(
  3424. _In_ JsValueRef value,
  3425. _In_ int start,
  3426. _In_ int length,
  3427. _Out_opt_ uint16_t* buffer,
  3428. _Out_opt_ size_t* written)
  3429. {
  3430. PARAM_NOT_NULL(value);
  3431. VALIDATE_JSREF(value);
  3432. return WriteStringCopy(value, start, length, written,
  3433. [buffer](const char16* src, size_t count, size_t *needed)
  3434. {
  3435. if (buffer)
  3436. {
  3437. memmove(buffer, src, sizeof(char16) * count);
  3438. }
  3439. else
  3440. {
  3441. *needed = count;
  3442. }
  3443. return JsNoError;
  3444. });
  3445. }
  3446. CHAKRA_API JsCopyString(
  3447. _In_ JsValueRef value,
  3448. _Out_opt_ char* buffer,
  3449. _In_ size_t bufferSize,
  3450. _Out_opt_ size_t* length)
  3451. {
  3452. PARAM_NOT_NULL(value);
  3453. VALIDATE_JSREF(value);
  3454. const char16* str = nullptr;
  3455. size_t strLength = 0;
  3456. JsErrorCode errorCode = JsStringToPointer(value, &str, &strLength);
  3457. if (errorCode != JsNoError)
  3458. {
  3459. return errorCode;
  3460. }
  3461. utf8::WideToNarrow utf8Str(str, strLength);
  3462. if (!buffer)
  3463. {
  3464. if (length)
  3465. {
  3466. *length = utf8Str.Length();
  3467. }
  3468. }
  3469. else
  3470. {
  3471. size_t count = min(bufferSize, utf8Str.Length());
  3472. // Try to copy whole characters if buffer size insufficient
  3473. auto maxFitChars = utf8::ByteIndexIntoCharacterIndex(
  3474. (LPCUTF8)(const char*)utf8Str, count,
  3475. utf8::DecodeOptions::doChunkedEncoding);
  3476. count = utf8::CharacterIndexToByteIndex(
  3477. (LPCUTF8)(const char*)utf8Str, utf8Str.Length(), maxFitChars);
  3478. memmove(buffer, utf8Str, sizeof(char) * count);
  3479. if (length)
  3480. {
  3481. *length = count;
  3482. }
  3483. }
  3484. return JsNoError;
  3485. }
  3486. _ALWAYSINLINE JsErrorCode CompileRun(
  3487. JsValueRef scriptVal,
  3488. JsSourceContext sourceContext,
  3489. JsValueRef sourceUrl,
  3490. JsParseScriptAttributes parseAttributes,
  3491. _Out_ JsValueRef *result,
  3492. bool parseOnly)
  3493. {
  3494. PARAM_NOT_NULL(scriptVal);
  3495. VALIDATE_JSREF(scriptVal);
  3496. PARAM_NOT_NULL(sourceUrl);
  3497. bool isExternalArray = Js::ExternalArrayBuffer::Is(scriptVal),
  3498. isString = false;
  3499. bool isUtf8 = !(parseAttributes & JsParseScriptAttributeArrayBufferIsUtf16Encoded);
  3500. LoadScriptFlag scriptFlag = LoadScriptFlag_None;
  3501. const byte* script;
  3502. size_t cb;
  3503. const WCHAR *url;
  3504. if (isExternalArray)
  3505. {
  3506. script = ((Js::ExternalArrayBuffer*)(scriptVal))->GetBuffer();
  3507. cb = ((Js::ExternalArrayBuffer*)(scriptVal))->GetByteLength();
  3508. scriptFlag = (LoadScriptFlag)(isUtf8 ?
  3509. LoadScriptFlag_ExternalArrayBuffer | LoadScriptFlag_Utf8Source :
  3510. LoadScriptFlag_ExternalArrayBuffer);
  3511. }
  3512. else
  3513. {
  3514. isString = Js::JavascriptString::Is(scriptVal);
  3515. if (!isString)
  3516. {
  3517. return JsErrorInvalidArgument;
  3518. }
  3519. }
  3520. JsErrorCode error = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  3521. if (isString)
  3522. {
  3523. Js::JavascriptString* jsString = Js::JavascriptString::FromVar(scriptVal);
  3524. script = (const byte*)jsString->GetSz();
  3525. // JavascriptString is 2 bytes (WCHAR/char16)
  3526. cb = jsString->GetLength() * sizeof(WCHAR);
  3527. }
  3528. if (!Js::JavascriptString::Is(sourceUrl))
  3529. {
  3530. return JsErrorInvalidArgument;
  3531. }
  3532. url = Js::JavascriptString::FromVar(sourceUrl)->GetSz();
  3533. return JsNoError;
  3534. });
  3535. if (error != JsNoError)
  3536. {
  3537. return error;
  3538. }
  3539. return RunScriptCore(scriptVal, script, cb, scriptFlag,
  3540. sourceContext, url, parseOnly, parseAttributes, false, result);
  3541. }
  3542. CHAKRA_API JsParse(
  3543. _In_ JsValueRef scriptVal,
  3544. _In_ JsSourceContext sourceContext,
  3545. _In_ JsValueRef sourceUrl,
  3546. _In_ JsParseScriptAttributes parseAttributes,
  3547. _Out_ JsValueRef *result)
  3548. {
  3549. return CompileRun(scriptVal, sourceContext, sourceUrl, parseAttributes,
  3550. result, true);
  3551. }
  3552. CHAKRA_API JsRun(
  3553. _In_ JsValueRef scriptVal,
  3554. _In_ JsSourceContext sourceContext,
  3555. _In_ JsValueRef sourceUrl,
  3556. _In_ JsParseScriptAttributes parseAttributes,
  3557. _Out_ JsValueRef *result)
  3558. {
  3559. return CompileRun(scriptVal, sourceContext, sourceUrl, parseAttributes,
  3560. result, false);
  3561. }
  3562. CHAKRA_API JsCreatePropertyId(
  3563. _In_z_ const char *name,
  3564. _In_ size_t length,
  3565. _Out_ JsPropertyIdRef *propertyId)
  3566. {
  3567. PARAM_NOT_NULL(name);
  3568. utf8::NarrowToWide wname(name, length);
  3569. if (!wname)
  3570. {
  3571. return JsErrorOutOfMemory;
  3572. }
  3573. return JsGetPropertyIdFromName(wname, propertyId);
  3574. }
  3575. CHAKRA_API JsCopyPropertyId(
  3576. _In_ JsPropertyIdRef propertyId,
  3577. _Out_ char* buffer,
  3578. _In_ size_t bufferSize,
  3579. _Out_ size_t* length)
  3580. {
  3581. PARAM_NOT_NULL(propertyId);
  3582. const char16* str = nullptr;
  3583. JsErrorCode errorCode = JsGetPropertyNameFromId(propertyId, &str);
  3584. if (errorCode != JsNoError)
  3585. {
  3586. return errorCode;
  3587. }
  3588. utf8::WideToNarrow utf8Str(str);
  3589. if (!buffer)
  3590. {
  3591. if (length)
  3592. {
  3593. *length = utf8Str.Length();
  3594. }
  3595. }
  3596. else
  3597. {
  3598. size_t count = min(bufferSize, utf8Str.Length());
  3599. // Try to copy whole characters if buffer size insufficient
  3600. auto maxFitChars = utf8::ByteIndexIntoCharacterIndex(
  3601. (LPCUTF8)(const char*)utf8Str, count,
  3602. utf8::DecodeOptions::doChunkedEncoding);
  3603. count = utf8::CharacterIndexToByteIndex(
  3604. (LPCUTF8)(const char*)utf8Str, utf8Str.Length(), maxFitChars);
  3605. memmove(buffer, utf8Str, sizeof(char) * count);
  3606. if (length)
  3607. {
  3608. *length = count;
  3609. }
  3610. }
  3611. return JsNoError;
  3612. }
  3613. CHAKRA_API JsSerialize(
  3614. _In_ JsValueRef scriptVal,
  3615. _Out_ JsValueRef *bufferVal,
  3616. _In_ JsParseScriptAttributes parseAttributes)
  3617. {
  3618. PARAM_NOT_NULL(scriptVal);
  3619. PARAM_NOT_NULL(bufferVal);
  3620. VALIDATE_JSREF(scriptVal);
  3621. *bufferVal = nullptr;
  3622. bool isExternalArray = Js::ExternalArrayBuffer::Is(scriptVal),
  3623. isString = false;
  3624. bool isUtf8 = !(parseAttributes & JsParseScriptAttributeArrayBufferIsUtf16Encoded);
  3625. if (!isExternalArray)
  3626. {
  3627. isString = Js::JavascriptString::Is(scriptVal);
  3628. if (!isString)
  3629. {
  3630. return JsErrorInvalidArgument;
  3631. }
  3632. }
  3633. LoadScriptFlag scriptFlag;
  3634. const byte* script = isExternalArray ?
  3635. ((Js::ExternalArrayBuffer*)(scriptVal))->GetBuffer() :
  3636. (const byte*)((Js::JavascriptString*)(scriptVal))->GetSz();
  3637. const size_t cb = isExternalArray ?
  3638. ((Js::ExternalArrayBuffer*)(scriptVal))->GetByteLength() :
  3639. ((Js::JavascriptString*)(scriptVal))->GetLength();
  3640. if (isExternalArray && isUtf8)
  3641. {
  3642. scriptFlag = (LoadScriptFlag) (LoadScriptFlag_ExternalArrayBuffer | LoadScriptFlag_Utf8Source);
  3643. }
  3644. else if (isUtf8)
  3645. {
  3646. scriptFlag = (LoadScriptFlag) (LoadScriptFlag_Utf8Source);
  3647. }
  3648. else
  3649. {
  3650. scriptFlag = LoadScriptFlag_None;
  3651. }
  3652. unsigned int bufferSize = 0;
  3653. JsErrorCode errorCode = JsSerializeScriptCore(script, cb, scriptFlag, nullptr,
  3654. 0, nullptr, &bufferSize, scriptVal);
  3655. if (errorCode != JsNoError)
  3656. {
  3657. return errorCode;
  3658. }
  3659. if (bufferSize == 0)
  3660. {
  3661. return JsErrorScriptCompile;
  3662. }
  3663. if ((errorCode = JsCreateArrayBuffer(bufferSize, bufferVal)) == JsNoError)
  3664. {
  3665. byte* buffer = ((Js::ArrayBuffer*)(*bufferVal))->GetBuffer();
  3666. errorCode = JsSerializeScriptCore(script, cb, scriptFlag, nullptr,
  3667. 0, buffer, &bufferSize, scriptVal);
  3668. }
  3669. return errorCode;
  3670. }
  3671. CHAKRA_API JsParseSerialized(
  3672. _In_ JsValueRef bufferVal,
  3673. _In_ JsSerializedLoadScriptCallback scriptLoadCallback,
  3674. _In_ JsSourceContext sourceContext,
  3675. _In_ JsValueRef sourceUrl,
  3676. _Out_ JsValueRef *result)
  3677. {
  3678. PARAM_NOT_NULL(bufferVal);
  3679. PARAM_NOT_NULL(sourceUrl);
  3680. const WCHAR *url;
  3681. if (Js::JavascriptString::Is(sourceUrl))
  3682. {
  3683. url = ((Js::JavascriptString*)(sourceUrl))->GetSz();
  3684. }
  3685. else
  3686. {
  3687. return JsErrorInvalidArgument;
  3688. }
  3689. // JsParseSerialized only accepts ArrayBuffer (incl. ExternalArrayBuffer)
  3690. if (!Js::ExternalArrayBuffer::Is(bufferVal))
  3691. {
  3692. return JsErrorInvalidArgument;
  3693. }
  3694. byte* buffer = Js::ArrayBuffer::FromVar(bufferVal)->GetBuffer();
  3695. return RunSerializedScriptCore(
  3696. scriptLoadCallback, DummyScriptUnloadCallback,
  3697. sourceContext,// use the same user provided sourceContext as scriptLoadSourceContext
  3698. buffer, bufferVal, sourceContext, url, true, result);
  3699. }
  3700. CHAKRA_API JsRunSerialized(
  3701. _In_ JsValueRef bufferVal,
  3702. _In_ JsSerializedLoadScriptCallback scriptLoadCallback,
  3703. _In_ JsSourceContext sourceContext,
  3704. _In_ JsValueRef sourceUrl,
  3705. _Out_ JsValueRef *result)
  3706. {
  3707. PARAM_NOT_NULL(bufferVal);
  3708. const WCHAR *url;
  3709. if (sourceUrl && Js::JavascriptString::Is(sourceUrl))
  3710. {
  3711. url = ((Js::JavascriptString*)(sourceUrl))->GetSz();
  3712. }
  3713. else
  3714. {
  3715. return JsErrorInvalidArgument;
  3716. }
  3717. // JsParseSerialized only accepts ArrayBuffer (incl. ExternalArrayBuffer)
  3718. if (!Js::ExternalArrayBuffer::Is(bufferVal))
  3719. {
  3720. return JsErrorInvalidArgument;
  3721. }
  3722. byte* buffer = Js::ArrayBuffer::FromVar(bufferVal)->GetBuffer();
  3723. return RunSerializedScriptCore(
  3724. scriptLoadCallback, DummyScriptUnloadCallback,
  3725. sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
  3726. buffer, bufferVal, sourceContext, url, false, result);
  3727. }
  3728. #endif // CHAKRACOREBUILD_