Jsrt.cpp 166 KB

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