Jsrt.cpp 162 KB

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