Jsrt.cpp 162 KB

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