| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556 |
- //-------------------------------------------------------------------------------------------------------
- // Copyright (C) Microsoft. All rights reserved.
- // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
- //-------------------------------------------------------------------------------------------------------
- #include "JsrtPch.h"
- #include "JsrtInternal.h"
- #include "JsrtExternalObject.h"
- #include "JsrtExternalArrayBuffer.h"
- #include "jsrtHelper.h"
- #include "JsrtSourceHolder.h"
- #include "ByteCode/ByteCodeSerializer.h"
- #include "Common/ByteSwap.h"
- #include "Library/DataView.h"
- #include "Library/JavascriptSymbol.h"
- #include "Base/ThreadContextTlsEntry.h"
- #include "Codex/Utf8Helper.h"
- // Parser Includes
- #include "cmperr.h" // For ERRnoMemory
- #include "screrror.h" // For CompileScriptException
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- #include "TestHooksRt.h"
- #endif
- struct CodexHeapAllocatorInterface
- {
- public:
- static void* allocate(size_t size)
- {
- return HeapNewArray(char, size);
- }
- static void free(void* ptr, size_t count)
- {
- HeapDeleteArray(count, (char*) ptr);
- }
- };
- typedef utf8::NarrowWideConverter<CodexHeapAllocatorInterface, LPCSTR, LPWSTR> NarrowToWideChakraHeap;
- typedef utf8::NarrowWideConverter<CodexHeapAllocatorInterface, LPCWSTR, LPSTR> WideToNarrowChakraHeap;
- JsErrorCode CheckContext(JsrtContext *currentContext, bool verifyRuntimeState, bool allowInObjectBeforeCollectCallback)
- {
- if (currentContext == nullptr)
- {
- return JsErrorNoCurrentContext;
- }
- Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
- Assert(scriptContext != nullptr);
- Recycler *recycler = scriptContext->GetRecycler();
- ThreadContext *threadContext = scriptContext->GetThreadContext();
- // We don't need parameter check if it's checked in previous wrapper.
- if (verifyRuntimeState)
- {
- if (recycler && recycler->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if (!allowInObjectBeforeCollectCallback && recycler && recycler->IsInObjectBeforeCollectCallback())
- {
- return JsErrorInObjectBeforeCollectCallback;
- }
- else if (threadContext->IsExecutionDisabled())
- {
- return JsErrorInDisabledState;
- }
- else if (scriptContext->IsInProfileCallback())
- {
- return JsErrorInProfileCallback;
- }
- else if (threadContext->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- // Make sure we don't have an outstanding exception.
- if (scriptContext->GetThreadContext()->GetRecordedException() != nullptr)
- {
- return JsErrorInExceptionState;
- }
- }
- return JsNoError;
- }
- /////////////////////
- //A create context function that we can funnel to for regular and record or debug aware creation
- JsErrorCode CreateContextCore(_In_ JsRuntimeHandle runtimeHandle, _In_ TTDRecorder& _actionEntryPopper, _In_ bool inRecordMode, _In_ bool activelyRecording, _In_ bool inReplayMode, _Out_ JsContextRef *newContext)
- {
- JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext * threadContext = runtime->GetThreadContext();
- if(threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if(threadContext->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- ThreadContextScope scope(threadContext);
- if(!scope.IsValid())
- {
- return JsErrorWrongThread;
- }
- #if ENABLE_TTD
- TTD::NSLogEvents::EventLogEntry* createEvent = nullptr;
- if(activelyRecording)
- {
- createEvent = threadContext->TTDLog->RecordJsRTCreateScriptContext(_actionEntryPopper);
- }
- #endif
- JsrtContext * context = JsrtContext::New(runtime);
- #if ENABLE_TTD
- if(inRecordMode | inReplayMode)
- {
- Js::ScriptContext* scriptContext = context->GetScriptContext();
- HostScriptContextCallbackFunctor callbackFunctor(context, &JsrtContext::OnScriptLoad_TTDCallback);
- #if ENABLE_TTD_DIAGNOSTICS_TRACING
- bool noNative = true;
- bool doDebug = true;
- #else
- bool noNative = TTD_FORCE_NOJIT_MODE || threadContext->TTDLog->IsDebugModeFlagSet();
- bool doDebug = TTD_FORCE_DEBUG_MODE || threadContext->TTDLog->IsDebugModeFlagSet();
- #endif
- threadContext->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionTTAction);
- if(inRecordMode)
- {
- threadContext->TTDContext->AddNewScriptContextRecord(context, scriptContext, callbackFunctor, noNative, doDebug);
- }
- else
- {
- threadContext->TTDContext->AddNewScriptContextReplay(context, scriptContext, callbackFunctor, noNative, doDebug);
- }
- threadContext->TTDLog->SetModeFlagsOnContext(scriptContext);
- threadContext->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionTTAction);
- }
- #endif
- JsrtDebugManager* jsrtDebugManager = runtime->GetJsrtDebugManager();
- if(jsrtDebugManager != nullptr)
- {
- Js::ScriptContext* scriptContext = context->GetScriptContext();
- scriptContext->InitializeDebugging();
- Js::DebugContext* debugContext = scriptContext->GetDebugContext();
- debugContext->SetHostDebugContext(jsrtDebugManager);
- Js::ProbeContainer* probeContainer = debugContext->GetProbeContainer();
- probeContainer->InitializeInlineBreakEngine(jsrtDebugManager);
- probeContainer->InitializeDebuggerScriptOptionCallback(jsrtDebugManager);
- threadContext->GetDebugManager()->SetLocalsDisplayFlags(Js::DebugManager::LocalsDisplayFlags::LocalsDisplayFlags_NoGroupMethods);
- }
- #if ENABLE_TTD
- if(activelyRecording)
- {
- threadContext->TTDLog->RecordJsRTCreateScriptContextResult(createEvent, context->GetScriptContext());
- }
- #endif
- *newContext = (JsContextRef)context;
- return JsNoError;
- }
- #if ENABLE_TTD
- void CALLBACK CreateExternalObject_TTDCallback(Js::ScriptContext* ctx, Js::Var* object)
- {
- TTDAssert(object != nullptr, "This should always be a valid location");
- *object = JsrtExternalObject::Create(nullptr, nullptr, ctx);
- }
- static void CALLBACK TTDDummyPromiseContinuationCallback(JsValueRef task, void *callbackState)
- {
- TTDAssert(false, "This should never actually be invoked!!!");
- }
- void CALLBACK CreateJsRTContext_TTDCallback(void* runtimeHandle, Js::ScriptContext** result)
- {
- JsContextRef newContext = nullptr;
- *result = nullptr;
- TTDRecorder dummyActionEntryPopper;
- JsErrorCode err = CreateContextCore(static_cast<JsRuntimeHandle>(runtimeHandle), dummyActionEntryPopper, false /*inRecordMode*/, false /*activelyRecording*/, true /*inReplayMode*/, &newContext);
- TTDAssert(err == JsNoError, "Shouldn't fail on us!!!");
- *result = static_cast<JsrtContext*>(newContext)->GetScriptContext();
- (*result)->GetLibrary()->SetNativeHostPromiseContinuationFunction((Js::JavascriptLibrary::PromiseContinuationCallback)TTDDummyPromiseContinuationCallback, nullptr);
- //To ensure we have a valid context active (when we next try and inflate into this context) set this as active by convention
- JsrtContext::TrySetCurrent(static_cast<JsrtContext*>(newContext));
- }
- void CALLBACK ReleaseJsRTContext_TTDCallback(FinalizableObject* jsrtCtx)
- {
- static_cast<JsrtContext*>(jsrtCtx)->GetScriptContext()->GetThreadContext()->GetRecycler()->RootRelease(jsrtCtx);
- JsrtContext::OnReplayDisposeContext_TTDCallback(jsrtCtx);
- }
- void CALLBACK SetActiveJsRTContext_TTDCallback(void* runtimeHandle, Js::ScriptContext* ctx)
- {
- JsrtRuntime * runtime = JsrtRuntime::FromHandle(static_cast<JsRuntimeHandle>(runtimeHandle));
- ThreadContext * threadContext = runtime->GetThreadContext();
- threadContext->TTDContext->SetActiveScriptContext(ctx);
- JsrtContext* runtimeCtx = (JsrtContext*)threadContext->TTDContext->GetRuntimeContextForScriptContext(ctx);
- JsrtContext::TrySetCurrent(runtimeCtx);
- }
- #endif
- //A create runtime function that we can funnel to for regular and record or debug aware creation
- JsErrorCode CreateRuntimeCore(_In_ JsRuntimeAttributes attributes,
- _In_opt_ const byte* optTTUri, size_t optTTUriCount, bool isRecord, bool isReplay, bool isDebug,
- _In_ UINT32 snapInterval, _In_ UINT32 snapHistoryLength,
- _In_opt_ JsTTDInitializeForWriteLogStreamCallback writeInitializeFunction,
- _In_opt_ TTDOpenResourceStreamCallback openResourceStream, _In_opt_ JsTTDReadBytesFromStreamCallback readBytesFromStream,
- _In_opt_ JsTTDWriteBytesToStreamCallback writeBytesToStream, _In_opt_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
- _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtimeHandle)
- {
- VALIDATE_ENTER_CURRENT_THREAD();
- PARAM_NOT_NULL(runtimeHandle);
- *runtimeHandle = nullptr;
- JsErrorCode runtimeResult = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- const JsRuntimeAttributes JsRuntimeAttributesAll =
- (JsRuntimeAttributes)(
- JsRuntimeAttributeDisableBackgroundWork |
- JsRuntimeAttributeAllowScriptInterrupt |
- JsRuntimeAttributeEnableIdleProcessing |
- JsRuntimeAttributeDisableEval |
- JsRuntimeAttributeDisableNativeCodeGeneration |
- JsRuntimeAttributeEnableExperimentalFeatures |
- JsRuntimeAttributeDispatchSetExceptionsToDebugger
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- | JsRuntimeAttributeSerializeLibraryByteCode
- #endif
- );
- Assert((attributes & ~JsRuntimeAttributesAll) == 0);
- if ((attributes & ~JsRuntimeAttributesAll) != 0)
- {
- return JsErrorInvalidArgument;
- }
- CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 0, nullptr);
- AllocationPolicyManager * policyManager = HeapNew(AllocationPolicyManager, (attributes & JsRuntimeAttributeDisableBackgroundWork) == 0);
- bool enableExperimentalFeatures = (attributes & JsRuntimeAttributeEnableExperimentalFeatures) != 0;
- ThreadContext * threadContext = HeapNew(ThreadContext, policyManager, threadService, enableExperimentalFeatures);
- if (((attributes & JsRuntimeAttributeDisableBackgroundWork) != 0)
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- && !Js::Configuration::Global.flags.ConcurrentRuntime
- #endif
- )
- {
- threadContext->OptimizeForManyInstances(true);
- #if ENABLE_NATIVE_CODEGEN
- threadContext->EnableBgJit(false);
- #endif
- }
- if (!threadContext->IsRentalThreadingEnabledInJSRT()
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- || Js::Configuration::Global.flags.DisableRentalThreading
- #endif
- )
- {
- threadContext->SetIsThreadBound();
- }
- if (attributes & JsRuntimeAttributeAllowScriptInterrupt)
- {
- threadContext->SetThreadContextFlag(ThreadContextFlagCanDisableExecution);
- }
- if (attributes & JsRuntimeAttributeDisableEval)
- {
- threadContext->SetThreadContextFlag(ThreadContextFlagEvalDisabled);
- }
- if (attributes & JsRuntimeAttributeDisableNativeCodeGeneration)
- {
- threadContext->SetThreadContextFlag(ThreadContextFlagNoJIT);
- }
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- if (Js::Configuration::Global.flags.PrimeRecycler)
- {
- threadContext->EnsureRecycler()->Prime();
- }
- #endif
- bool enableIdle = (attributes & JsRuntimeAttributeEnableIdleProcessing) == JsRuntimeAttributeEnableIdleProcessing;
- bool dispatchExceptions = (attributes & JsRuntimeAttributeDispatchSetExceptionsToDebugger) == JsRuntimeAttributeDispatchSetExceptionsToDebugger;
- JsrtRuntime * runtime = HeapNew(JsrtRuntime, threadContext, enableIdle, dispatchExceptions);
- threadContext->SetCurrentThreadId(ThreadContext::NoThread);
- *runtimeHandle = runtime->ToHandle();
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- runtime->SetSerializeByteCodeForLibrary((attributes & JsRuntimeAttributeSerializeLibraryByteCode) != 0);
- #endif
- return JsNoError;
- });
- #if ENABLE_TTD
- if(runtimeResult != JsNoError)
- {
- return runtimeResult;
- }
- if(isRecord | isReplay | isDebug)
- {
- ThreadContext* threadContext = JsrtRuntime::FromHandle(*runtimeHandle)->GetThreadContext();
- if(isRecord && isReplay)
- {
- return JsErrorInvalidArgument; //A runtime can only be in 1 mode
- }
- if(isDebug && !isReplay)
- {
- return JsErrorInvalidArgument; //A debug runtime also needs to be in runtime mode (and we are going to be strict about it)
- }
- if(optTTUri == nullptr)
- {
- return JsErrorInvalidArgument; //We must have a location to store data into
- }
- runtimeResult = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- //Make sure the thread context recycler is allocated before we do anything else
- ThreadContextScope scope(threadContext);
- threadContext->EnsureRecycler();
- threadContext->InitTimeTravel(threadContext, *runtimeHandle, optTTUriCount, optTTUri, snapInterval, max<uint32>(2, snapHistoryLength));
- threadContext->InitHostFunctionsAndTTData(isRecord, isReplay, isDebug,
- writeInitializeFunction, openResourceStream, readBytesFromStream, writeBytesToStream, flushAndCloseStream,
- &CreateExternalObject_TTDCallback, &CreateJsRTContext_TTDCallback, &ReleaseJsRTContext_TTDCallback, &SetActiveJsRTContext_TTDCallback);
- return JsNoError;
- });
- }
- #endif
- return runtimeResult;
- }
- /////////////////////
- CHAKRA_API JsCreateRuntime(_In_ JsRuntimeAttributes attributes, _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtimeHandle)
- {
- return CreateRuntimeCore(attributes,
- nullptr /*optRecordUri*/, 0 /*optRecordUriCount */, false /*isRecord*/, false /*isReplay*/, false /*isDebug*/,
- UINT_MAX /*optSnapInterval*/, UINT_MAX /*optLogLength*/,
- nullptr, nullptr, nullptr, nullptr, nullptr, /*TTD IO handlers*/
- threadService, runtimeHandle);
- }
- template <CollectionFlags flags>
- JsErrorCode JsCollectGarbageCommon(JsRuntimeHandle runtimeHandle)
- {
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
- if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if (threadContext->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- ThreadContextScope scope(threadContext);
- if (!scope.IsValid())
- {
- return JsErrorWrongThread;
- }
- Recycler* recycler = threadContext->EnsureRecycler();
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- if (flags & CollectOverride_SkipStack)
- {
- Recycler::AutoEnterExternalStackSkippingGCMode autoGC(recycler);
- recycler->CollectNow<flags>();
- }
- else
- #endif
- {
- recycler->CollectNow<flags>();
- }
- return JsNoError;
- });
- }
- CHAKRA_API JsCollectGarbage(_In_ JsRuntimeHandle runtimeHandle)
- {
- return JsCollectGarbageCommon<CollectNowExhaustive>(runtimeHandle);
- }
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- CHAKRA_API JsPrivateCollectGarbageSkipStack(_In_ JsRuntimeHandle runtimeHandle)
- {
- return JsCollectGarbageCommon<CollectNowExhaustiveSkipStack>(runtimeHandle);
- }
- #endif
- CHAKRA_API JsDisposeRuntime(_In_ JsRuntimeHandle runtimeHandle)
- {
- return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext * threadContext = runtime->GetThreadContext();
- ThreadContextScope scope(threadContext);
- // We should not dispose if the runtime is being used.
- if (!scope.IsValid() ||
- scope.WasInUse() ||
- (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress()))
- {
- return JsErrorRuntimeInUse;
- }
- else if (threadContext->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- // Invoke and clear the callbacks while the contexts and runtime are still available
- {
- Recycler* recycler = threadContext->GetRecycler();
- if (recycler != nullptr)
- {
- recycler->ClearObjectBeforeCollectCallbacks();
- }
- }
- if (runtime->GetJsrtDebugManager() != nullptr)
- {
- runtime->GetJsrtDebugManager()->ClearDebuggerObjects();
- }
- // Close any open Contexts.
- // We need to do this before recycler shutdown, because ScriptEngine->Close won't work then.
- runtime->CloseContexts();
- runtime->DeleteJsrtDebugManager();
- #if defined(CHECK_MEMORY_LEAK) || defined(LEAK_REPORT)
- bool doFinalGC = false;
- #if defined(LEAK_REPORT)
- if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
- {
- doFinalGC = true;
- }
- #endif
- #if defined(CHECK_MEMORY_LEAK)
- if (Js::Configuration::Global.flags.CheckMemoryLeak)
- {
- doFinalGC = true;
- }
- #endif
- if (doFinalGC)
- {
- Recycler *recycler = threadContext->GetRecycler();
- if (recycler)
- {
- recycler->EnsureNotCollecting();
- recycler->CollectNow<CollectNowFinalGC>();
- Assert(!recycler->CollectionInProgress());
- }
- }
- #endif
- runtime->SetBeforeCollectCallback(nullptr, nullptr);
- threadContext->CloseForJSRT();
- HeapDelete(threadContext);
- HeapDelete(runtime);
- scope.Invalidate();
- return JsNoError;
- });
- }
- CHAKRA_API JsAddRef(_In_ JsRef ref, _Out_opt_ unsigned int *count)
- {
- VALIDATE_JSREF(ref);
- if (count != nullptr)
- {
- *count = 0;
- }
- if (Js::TaggedNumber::Is(ref))
- {
- // The count is always one because these are never collected
- if (count)
- {
- *count = 1;
- }
- return JsNoError;
- }
- if (JsrtContext::Is(ref))
- {
- return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode
- {
- Recycler * recycler = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext()->GetRecycler();
- recycler->RootAddRef(ref, count);
- return JsNoError;
- });
- }
- else
- {
- ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
- if (threadContext == nullptr)
- {
- return JsErrorNoCurrentContext;
- }
- Recycler * recycler = threadContext->GetRecycler();
- return GlobalAPIWrapper([&] (TTDRecorder& _actionEntryPopper) -> JsErrorCode
- {
- // Note, some references may live in arena-allocated memory, so we need to do this check
- if (!recycler->IsValidObject(ref))
- {
- return JsNoError;
- }
- #if ENABLE_TTD
- unsigned int lCount = 0;
- recycler->RootAddRef(ref, &lCount);
- if (count != nullptr)
- {
- *count = lCount;
- }
- if((lCount == 1) && (threadContext->IsRuntimeInTTDMode()) && (!threadContext->TTDLog->IsPropertyRecordRef(ref)))
- {
- Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(ref);
- if(obj->GetScriptContext()->IsTTDRecordModeEnabled() && !TTD::ThreadContextTTD::IsSpecialRootObject(obj))
- {
- if(obj->GetScriptContext()->ShouldPerformRecordAction())
- {
- threadContext->TTDLog->RecordJsRTAddRootRef(_actionEntryPopper, (Js::Var)ref);
- }
- threadContext->TTDContext->AddTrackedRootGeneral(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(obj), obj);
- }
- }
- #else
- recycler->RootAddRef(ref, count);
- #endif
- return JsNoError;
- });
- }
- }
- CHAKRA_API JsRelease(_In_ JsRef ref, _Out_opt_ unsigned int *count)
- {
- VALIDATE_JSREF(ref);
- if (count != nullptr)
- {
- *count = 0;
- }
- if (Js::TaggedNumber::Is(ref))
- {
- // The count is always one because these are never collected
- if (count)
- {
- *count = 1;
- }
- return JsNoError;
- }
- if (JsrtContext::Is(ref))
- {
- return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode
- {
- Recycler * recycler = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext()->GetRecycler();
- recycler->RootRelease(ref, count);
- return JsNoError;
- });
- }
- else
- {
- ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
- if (threadContext == nullptr)
- {
- return JsErrorNoCurrentContext;
- }
- Recycler * recycler = threadContext->GetRecycler();
- return GlobalAPIWrapper([&](TTDRecorder& _actionEntryPopper) -> JsErrorCode
- {
- // Note, some references may live in arena-allocated memory, so we need to do this check
- if (!recycler->IsValidObject(ref))
- {
- return JsNoError;
- }
- #if ENABLE_TTD
- unsigned int lCount = 0;
- recycler->RootRelease(ref, &lCount);
- if (count != nullptr)
- {
- *count = lCount;
- }
- if((lCount == 0) && (threadContext->IsRuntimeInTTDMode()) && (!threadContext->TTDLog->IsPropertyRecordRef(ref)))
- {
- Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(ref);
- if(obj->GetScriptContext()->IsTTDRecordModeEnabled() && !TTD::ThreadContextTTD::IsSpecialRootObject(obj))
- {
- if(obj->GetScriptContext()->ShouldPerformRecordAction())
- {
- threadContext->TTDLog->RecordJsRTRemoveRootRef(_actionEntryPopper, (Js::Var)ref);
- }
- threadContext->TTDContext->RemoveTrackedRootGeneral(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(obj), obj);
- }
- }
- #else
- recycler->RootRelease(ref, count);
- #endif
- return JsNoError;
- });
- }
- }
- CHAKRA_API JsSetObjectBeforeCollectCallback(_In_ JsRef ref, _In_opt_ void *callbackState, _In_ JsObjectBeforeCollectCallback objectBeforeCollectCallback)
- {
- VALIDATE_JSREF(ref);
- if (Js::TaggedNumber::Is(ref))
- {
- return JsErrorInvalidArgument;
- }
- if (JsrtContext::Is(ref))
- {
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
- {
- ThreadContext* threadContext = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext();
- Recycler * recycler = threadContext->GetRecycler();
- recycler->SetObjectBeforeCollectCallback(ref, reinterpret_cast<Recycler::ObjectBeforeCollectCallback>(objectBeforeCollectCallback), callbackState,
- reinterpret_cast<Recycler::ObjectBeforeCollectCallbackWrapper>(JsrtCallbackState::ObjectBeforeCallectCallbackWrapper), threadContext);
- return JsNoError;
- });
- }
- else
- {
- ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
- if (threadContext == nullptr)
- {
- return JsErrorNoCurrentContext;
- }
- Recycler * recycler = threadContext->GetRecycler();
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
- {
- if (!recycler->IsValidObject(ref))
- {
- return JsErrorInvalidArgument;
- }
- recycler->SetObjectBeforeCollectCallback(ref, reinterpret_cast<Recycler::ObjectBeforeCollectCallback>(objectBeforeCollectCallback), callbackState,
- reinterpret_cast<Recycler::ObjectBeforeCollectCallbackWrapper>(JsrtCallbackState::ObjectBeforeCallectCallbackWrapper), threadContext);
- return JsNoError;
- });
- }
- }
- CHAKRA_API JsCreateContext(_In_ JsRuntimeHandle runtimeHandle, _Out_ JsContextRef *newContext)
- {
- return GlobalAPIWrapper([&](TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PARAM_NOT_NULL(newContext);
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- bool inRecord = false;
- bool activelyRecording = false;
- bool inReplay = false;
- #if ENABLE_TTD
- JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext * threadContext = runtime->GetThreadContext();
- if(threadContext->IsRuntimeInTTDMode() && threadContext->TTDContext->GetActiveScriptContext() != nullptr)
- {
- Js::ScriptContext* currentCtx = threadContext->TTDContext->GetActiveScriptContext();
- inRecord = currentCtx->IsTTDRecordModeEnabled();
- activelyRecording = currentCtx->ShouldPerformRecordAction();
- inReplay = currentCtx->IsTTDReplayModeEnabled();
- }
- #endif
- return CreateContextCore(runtimeHandle, _actionEntryPopper, inRecord, activelyRecording, inReplay, newContext);
- });
- }
- CHAKRA_API JsGetCurrentContext(_Out_ JsContextRef *currentContext)
- {
- PARAM_NOT_NULL(currentContext);
- BEGIN_JSRT_NO_EXCEPTION
- {
- *currentContext = (JsContextRef)JsrtContext::GetCurrent();
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsSetCurrentContext(_In_ JsContextRef newContext)
- {
- VALIDATE_ENTER_CURRENT_THREAD();
- return GlobalAPIWrapper([&] (TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- Recycler* recycler = currentContext != nullptr ? currentContext->GetScriptContext()->GetRecycler() : nullptr;
- #if ENABLE_TTD
- Js::ScriptContext* newScriptContext = newContext != nullptr ? static_cast<JsrtContext*>(newContext)->GetScriptContext() : nullptr;
- if(newScriptContext == nullptr)
- {
- Js::ScriptContext* oldScriptContext = currentContext != nullptr ? static_cast<JsrtContext*>(currentContext)->GetScriptContext() : nullptr;
- if(currentContext != nullptr && oldScriptContext->IsTTDRecordModeEnabled())
- {
- if(oldScriptContext->ShouldPerformRecordAction())
- {
- oldScriptContext->GetThreadContext()->TTDLog->RecordJsRTSetCurrentContext(_actionEntryPopper, nullptr);
- }
- oldScriptContext->GetThreadContext()->TTDContext->SetActiveScriptContext(nullptr);
- }
- }
- else
- {
- if(newScriptContext->IsTTDRecordModeEnabled())
- {
- if(newScriptContext->ShouldPerformRecordAction())
- {
- newScriptContext->GetThreadContext()->TTDLog->RecordJsRTSetCurrentContext(_actionEntryPopper, newScriptContext->GetGlobalObject());
- }
- newScriptContext->GetThreadContext()->TTDContext->SetActiveScriptContext(newScriptContext);
- }
- }
- #endif
- if (currentContext && recycler->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if (currentContext && currentContext->GetRuntime()->GetThreadContext()->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- if (!JsrtContext::TrySetCurrent((JsrtContext *)newContext))
- {
- return JsErrorWrongThread;
- }
- return JsNoError;
- });
- }
- CHAKRA_API JsGetContextOfObject(_In_ JsValueRef object, _Out_ JsContextRef *context)
- {
- VALIDATE_JSREF(object);
- PARAM_NOT_NULL(context);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (!Js::RecyclableObject::Is(object))
- {
- RETURN_NO_EXCEPTION(JsErrorArgumentNotObject);
- }
- Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(object);
- *context = (JsContextRef)obj->GetScriptContext()->GetLibrary()->GetPinnedJsrtContextObject();
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsGetContextData(_In_ JsContextRef context, _Out_ void **data)
- {
- VALIDATE_JSREF(context);
- PARAM_NOT_NULL(data);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (!JsrtContext::Is(context))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- *data = static_cast<JsrtContext *>(context)->GetExternalData();
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsSetContextData(_In_ JsContextRef context, _In_ void *data)
- {
- VALIDATE_JSREF(context);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (!JsrtContext::Is(context))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- static_cast<JsrtContext *>(context)->SetExternalData(data);
- }
- END_JSRT_NO_EXCEPTION
- }
- void HandleScriptCompileError(Js::ScriptContext * scriptContext, CompileScriptException * se)
- {
- HRESULT hr = se->ei.scode;
- if (hr == E_OUTOFMEMORY || hr == VBSERR_OutOfMemory || hr == VBSERR_OutOfStack || hr == ERRnoMemory)
- {
- Js::Throw::OutOfMemory();
- }
- Js::JavascriptError* error = Js::JavascriptError::CreateFromCompileScriptException(scriptContext, se);
- Js::JavascriptExceptionObject * exceptionObject = RecyclerNew(scriptContext->GetRecycler(),
- Js::JavascriptExceptionObject, error, scriptContext, nullptr);
- scriptContext->GetThreadContext()->SetRecordedException(exceptionObject);
- }
- CHAKRA_API JsGetUndefinedValue(_Out_ JsValueRef *undefinedValue)
- {
- return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
- PARAM_NOT_NULL(undefinedValue);
- *undefinedValue = scriptContext->GetLibrary()->GetUndefined();
- return JsNoError;
- },
- /*allowInObjectBeforeCollectCallback*/true);
- }
- CHAKRA_API JsGetNullValue(_Out_ JsValueRef *nullValue)
- {
- return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
- PARAM_NOT_NULL(nullValue);
- *nullValue = scriptContext->GetLibrary()->GetNull();
- return JsNoError;
- },
- /*allowInObjectBeforeCollectCallback*/true);
- }
- CHAKRA_API JsGetTrueValue(_Out_ JsValueRef *trueValue)
- {
- return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
- PARAM_NOT_NULL(trueValue);
- *trueValue = scriptContext->GetLibrary()->GetTrue();
- return JsNoError;
- },
- /*allowInObjectBeforeCollectCallback*/true);
- }
- CHAKRA_API JsGetFalseValue(_Out_ JsValueRef *falseValue)
- {
- return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
- PARAM_NOT_NULL(falseValue);
- *falseValue = scriptContext->GetLibrary()->GetFalse();
- return JsNoError;
- },
- /*allowInObjectBeforeCollectCallback*/true);
- }
- CHAKRA_API JsBoolToBoolean(_In_ bool value, _Out_ JsValueRef *booleanValue)
- {
- return ContextAPINoScriptWrapper([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateBoolean, value);
- PARAM_NOT_NULL(booleanValue);
- *booleanValue = value ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse();
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, booleanValue);
- return JsNoError;
- },
- /*allowInObjectBeforeCollectCallback*/true);
- }
- CHAKRA_API JsBooleanToBool(_In_ JsValueRef value, _Out_ bool *boolValue)
- {
- VALIDATE_JSREF(value);
- PARAM_NOT_NULL(boolValue);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (!Js::JavascriptBoolean::Is(value))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- *boolValue = Js::JavascriptBoolean::FromVar(value)->GetValue() ? true : false;
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsConvertValueToBoolean(_In_ JsValueRef value, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToBooleanConversion, (Js::Var)value);
- VALIDATE_INCOMING_REFERENCE(value, scriptContext);
- PARAM_NOT_NULL(result);
- if (Js::JavascriptConversion::ToBool((Js::Var)value, scriptContext))
- {
- *result = scriptContext->GetLibrary()->GetTrue();
- }
- else
- {
- *result = scriptContext->GetLibrary()->GetFalse();
- }
- //It is either true or false which we always track so no need to store result identity
- return JsNoError;
- });
- }
- CHAKRA_API JsGetValueType(_In_ JsValueRef value, _Out_ JsValueType *type)
- {
- VALIDATE_JSREF(value);
- PARAM_NOT_NULL(type);
- BEGIN_JSRT_NO_EXCEPTION
- {
- Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(value);
- switch (typeId)
- {
- case Js::TypeIds_Undefined:
- *type = JsUndefined;
- break;
- case Js::TypeIds_Null:
- *type = JsNull;
- break;
- case Js::TypeIds_Boolean:
- *type = JsBoolean;
- break;
- case Js::TypeIds_Integer:
- case Js::TypeIds_Number:
- case Js::TypeIds_Int64Number:
- case Js::TypeIds_UInt64Number:
- *type = JsNumber;
- break;
- case Js::TypeIds_String:
- *type = JsString;
- break;
- case Js::TypeIds_Function:
- *type = JsFunction;
- break;
- case Js::TypeIds_Error:
- *type = JsError;
- break;
- case Js::TypeIds_Array:
- case Js::TypeIds_NativeIntArray:
- #if ENABLE_COPYONACCESS_ARRAY
- case Js::TypeIds_CopyOnAccessNativeIntArray:
- #endif
- case Js::TypeIds_NativeFloatArray:
- case Js::TypeIds_ES5Array:
- *type = JsArray;
- break;
- case Js::TypeIds_Symbol:
- *type = JsSymbol;
- break;
- case Js::TypeIds_ArrayBuffer:
- *type = JsArrayBuffer;
- break;
- case Js::TypeIds_DataView:
- *type = JsDataView;
- break;
- default:
- if (Js::TypedArrayBase::Is(typeId))
- {
- *type = JsTypedArray;
- }
- else
- {
- *type = JsObject;
- }
- break;
- }
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsDoubleToNumber(_In_ double dbl, _Out_ JsValueRef *asValue)
- {
- PARAM_NOT_NULL(asValue);
- //If number is not heap allocated then we don't need to record/track the creation for time-travel
- if (Js::JavascriptNumber::TryToVarFastWithCheck(dbl, asValue))
- {
- return JsNoError;
- }
- return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateNumber, dbl);
- *asValue = Js::JavascriptNumber::ToVarNoCheck(dbl, scriptContext);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, asValue);
- return JsNoError;
- });
- }
- CHAKRA_API JsIntToNumber(_In_ int intValue, _Out_ JsValueRef *asValue)
- {
- PARAM_NOT_NULL(asValue);
- //If number is not heap allocated then we don't need to record/track the creation for time-travel
- if (Js::JavascriptNumber::TryToVarFast(intValue, asValue))
- {
- return JsNoError;
- }
- return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- #if !INT32VAR
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateInteger, intValue);
- #endif
- *asValue = Js::JavascriptNumber::ToVar(intValue, scriptContext);
- #if !INT32VAR
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, asValue);
- #endif
- return JsNoError;
- });
- }
- CHAKRA_API JsNumberToDouble(_In_ JsValueRef value, _Out_ double *asDouble)
- {
- VALIDATE_JSREF(value);
- PARAM_NOT_NULL(asDouble);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (Js::TaggedInt::Is(value))
- {
- *asDouble = Js::TaggedInt::ToDouble(value);
- }
- else if (Js::JavascriptNumber::Is_NoTaggedIntCheck(value))
- {
- *asDouble = Js::JavascriptNumber::GetValue(value);
- }
- else
- {
- *asDouble = 0;
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsNumberToInt(_In_ JsValueRef value, _Out_ int *asInt)
- {
- VALIDATE_JSREF(value);
- PARAM_NOT_NULL(asInt);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (Js::TaggedInt::Is(value))
- {
- *asInt = Js::TaggedInt::ToInt32(value);
- }
- else if (Js::JavascriptNumber::Is_NoTaggedIntCheck(value))
- {
- *asInt = Js::JavascriptConversion::ToInt32(Js::JavascriptNumber::GetValue(value));
- }
- else
- {
- *asInt = 0;
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsConvertValueToNumber(_In_ JsValueRef value, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToNumberConversion, (Js::Var)value);
- VALIDATE_INCOMING_REFERENCE(value, scriptContext);
- PARAM_NOT_NULL(result);
- *result = (JsValueRef)Js::JavascriptOperators::ToNumber((Js::Var)value, scriptContext);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- return JsNoError;
- });
- }
- CHAKRA_API JsGetStringLength(_In_ JsValueRef value, _Out_ int *length)
- {
- VALIDATE_JSREF(value);
- PARAM_NOT_NULL(length);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (!Js::JavascriptString::Is(value))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- *length = Js::JavascriptString::FromVar(value)->GetLengthAsSignedInt();
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsPointerToString(_In_reads_(stringLength) const wchar_t *stringValue, _In_ size_t stringLength, _Out_ JsValueRef *string)
- {
- return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateString, stringValue, stringLength);
- PARAM_NOT_NULL(stringValue);
- PARAM_NOT_NULL(string);
- if (!Js::IsValidCharCount(stringLength))
- {
- Js::JavascriptError::ThrowOutOfMemoryError(scriptContext);
- }
- *string = Js::JavascriptString::NewCopyBuffer(stringValue, static_cast<charcount_t>(stringLength), scriptContext);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, string);
- return JsNoError;
- });
- }
- // TODO: The annotation of stringPtr is wrong. Need to fix definition in chakrart.h
- // The warning is '*stringPtr' could be '0' : this does not adhere to the specification for the function 'JsStringToPointer'.
- #pragma warning(suppress:6387)
- CHAKRA_API JsStringToPointer(_In_ JsValueRef stringValue, _Outptr_result_buffer_(*stringLength) const wchar_t **stringPtr, _Out_ size_t *stringLength)
- {
- VALIDATE_JSREF(stringValue);
- PARAM_NOT_NULL(stringPtr);
- *stringPtr = nullptr;
- PARAM_NOT_NULL(stringLength);
- *stringLength = 0;
- if (!Js::JavascriptString::Is(stringValue))
- {
- return JsErrorInvalidArgument;
- }
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- Js::JavascriptString *jsString = Js::JavascriptString::FromVar(stringValue);
- *stringPtr = jsString->GetSz();
- *stringLength = jsString->GetLength();
- return JsNoError;
- });
- }
- CHAKRA_API JsConvertValueToString(_In_ JsValueRef value, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToStringConversion, (Js::Var)value);
- VALIDATE_INCOMING_REFERENCE(value, scriptContext);
- PARAM_NOT_NULL(result);
- *result = nullptr;
- *result = (JsValueRef) Js::JavascriptConversion::ToString((Js::Var)value, scriptContext);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- return JsNoError;
- });
- }
- CHAKRA_API JsGetGlobalObject(_Out_ JsValueRef *globalObject)
- {
- return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
- PARAM_NOT_NULL(globalObject);
- *globalObject = (JsValueRef)scriptContext->GetGlobalObject();
- return JsNoError;
- },
- /*allowInObjectBeforeCollectCallback*/true);
- }
- CHAKRA_API JsCreateObject(_Out_ JsValueRef *object)
- {
- return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateBasicObject);
- PARAM_NOT_NULL(object);
- *object = scriptContext->GetLibrary()->CreateObject();
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, object);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateExternalObject(_In_opt_ void *data, _In_opt_ JsFinalizeCallback finalizeCallback, _Out_ JsValueRef *object)
- {
- return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateExternalObject);
- PARAM_NOT_NULL(object);
- *object = JsrtExternalObject::Create(data, finalizeCallback, scriptContext);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, object);
- return JsNoError;
- });
- }
- CHAKRA_API JsConvertValueToObject(_In_ JsValueRef value, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToObjectConversion, (Js::Var)value);
- VALIDATE_INCOMING_REFERENCE(value, scriptContext);
- PARAM_NOT_NULL(result);
- *result = (JsValueRef)Js::JavascriptOperators::ToObject((Js::Var)value, scriptContext);
- Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- return JsNoError;
- });
- }
- CHAKRA_API JsGetPrototype(_In_ JsValueRef object, _Out_ JsValueRef *prototypeObject)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetPrototype, object);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- PARAM_NOT_NULL(prototypeObject);
- *prototypeObject = (JsValueRef)Js::JavascriptOperators::OP_GetPrototype(object, scriptContext);
- Assert(*prototypeObject == nullptr || !Js::CrossSite::NeedMarshalVar(*prototypeObject, scriptContext));
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, prototypeObject);
- return JsNoError;
- });
- }
- CHAKRA_API JsSetPrototype(_In_ JsValueRef object, _In_ JsValueRef prototypeObject)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetPrototype, object, prototypeObject);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_OBJECT_OR_NULL(prototypeObject, scriptContext);
- // We're not allowed to set this.
- if (object == scriptContext->GetLibrary()->GetObjectPrototype())
- {
- return JsErrorInvalidArgument;
- }
- Js::JavascriptObject::ChangePrototype(Js::RecyclableObject::FromVar(object), Js::RecyclableObject::FromVar(prototypeObject), true, scriptContext);
- return JsNoError;
- });
- }
- CHAKRA_API JsInstanceOf(_In_ JsValueRef object, _In_ JsValueRef constructor, _Out_ bool *result) {
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTInstanceOf, object, constructor);
- VALIDATE_INCOMING_REFERENCE(object, scriptContext);
- VALIDATE_INCOMING_REFERENCE(constructor, scriptContext);
- PARAM_NOT_NULL(result);
- *result = Js::RecyclableObject::FromVar(constructor)->HasInstance(object, scriptContext) ? true : false;
- return JsNoError;
- });
- }
- CHAKRA_API JsGetExtensionAllowed(_In_ JsValueRef object, _Out_ bool *value)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- PARAM_NOT_NULL(value);
- *value = nullptr;
- *value = Js::RecyclableObject::FromVar(object)->IsExtensible() != 0;
- return JsNoError;
- });
- }
- CHAKRA_API JsPreventExtension(_In_ JsValueRef object)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- Js::RecyclableObject::FromVar(object)->PreventExtensions();
- return JsNoError;
- });
- }
- CHAKRA_API JsGetProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *value)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetProperty, (Js::PropertyRecord *)propertyId, object);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- PARAM_NOT_NULL(value);
- *value = nullptr;
- *value = Js::JavascriptOperators::OP_GetProperty((Js::Var)object, ((Js::PropertyRecord *)propertyId)->GetPropertyId(), scriptContext);
- Assert(*value == nullptr || !Js::CrossSite::NeedMarshalVar(*value, scriptContext));
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, value);
- return JsNoError;
- });
- }
- CHAKRA_API JsGetOwnPropertyDescriptor(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *propertyDescriptor)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertyInfo, (Js::PropertyRecord *)propertyId, object);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- PARAM_NOT_NULL(propertyDescriptor);
- *propertyDescriptor = nullptr;
- Js::PropertyDescriptor propertyDescriptorValue;
- if (Js::JavascriptOperators::GetOwnPropertyDescriptor(Js::RecyclableObject::FromVar(object), ((Js::PropertyRecord *)propertyId)->GetPropertyId(), scriptContext, &propertyDescriptorValue))
- {
- *propertyDescriptor = Js::JavascriptOperators::FromPropertyDescriptor(propertyDescriptorValue, scriptContext);
- }
- else
- {
- *propertyDescriptor = scriptContext->GetLibrary()->GetUndefined();
- }
- Assert(*propertyDescriptor == nullptr || !Js::CrossSite::NeedMarshalVar(*propertyDescriptor, scriptContext));
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertyDescriptor);
- return JsNoError;
- });
- }
- CHAKRA_API JsGetOwnPropertyNames(_In_ JsValueRef object, _Out_ JsValueRef *propertyNames)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertyNamesInfo, object);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- PARAM_NOT_NULL(propertyNames);
- *propertyNames = nullptr;
- *propertyNames = Js::JavascriptOperators::GetOwnPropertyNames(object, scriptContext);
- Assert(*propertyNames == nullptr || !Js::CrossSite::NeedMarshalVar(*propertyNames, scriptContext));
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertyNames);
- return JsNoError;
- });
- }
- CHAKRA_API JsGetOwnPropertySymbols(_In_ JsValueRef object, _Out_ JsValueRef *propertySymbols)
- {
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertySymbolsInfo, object);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- PARAM_NOT_NULL(propertySymbols);
- *propertySymbols = Js::JavascriptOperators::GetOwnPropertySymbols(object, scriptContext);
- Assert(*propertySymbols == nullptr || !Js::CrossSite::NeedMarshalVar(*propertySymbols, scriptContext));
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertySymbols);
- return JsNoError;
- });
- }
- CHAKRA_API JsSetProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _In_ JsValueRef value, _In_ bool useStrictRules)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetProperty, object, (Js::PropertyRecord *)propertyId, value, useStrictRules);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- VALIDATE_INCOMING_REFERENCE(value, scriptContext);
- Js::JavascriptOperators::OP_SetProperty(object, ((Js::PropertyRecord *)propertyId)->GetPropertyId(), value, scriptContext,
- nullptr, useStrictRules ? Js::PropertyOperation_StrictMode : Js::PropertyOperation_None);
- return JsNoError;
- });
- }
- CHAKRA_API JsHasProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ bool *hasProperty)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTHasProperty, (Js::PropertyRecord *)propertyId, object);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- PARAM_NOT_NULL(hasProperty);
- *hasProperty = nullptr;
- *hasProperty = Js::JavascriptOperators::OP_HasProperty(object, ((Js::PropertyRecord *)propertyId)->GetPropertyId(), scriptContext) != 0;
- return JsNoError;
- });
- }
- CHAKRA_API JsDeleteProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _In_ bool useStrictRules, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTDeleteProperty, object, (Js::PropertyRecord *)propertyId, useStrictRules);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- PARAM_NOT_NULL(result);
- *result = nullptr;
- *result = Js::JavascriptOperators::OP_DeleteProperty((Js::Var)object, ((Js::PropertyRecord *)propertyId)->GetPropertyId(),
- scriptContext, useStrictRules ? Js::PropertyOperation_StrictMode : Js::PropertyOperation_None);
- Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- return JsNoError;
- });
- }
- CHAKRA_API JsDefineProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _In_ JsValueRef propertyDescriptor, _Out_ bool *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTDefineProperty, object, (Js::PropertyRecord *)propertyId, propertyDescriptor);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- VALIDATE_INCOMING_OBJECT(propertyDescriptor, scriptContext);
- PARAM_NOT_NULL(result);
- *result = nullptr;
- Js::PropertyDescriptor propertyDescriptorValue;
- if (!Js::JavascriptOperators::ToPropertyDescriptor(propertyDescriptor, &propertyDescriptorValue, scriptContext))
- {
- return JsErrorInvalidArgument;
- }
- *result = Js::JavascriptOperators::DefineOwnPropertyDescriptor(
- Js::RecyclableObject::FromVar(object), ((Js::PropertyRecord *)propertyId)->GetPropertyId(), propertyDescriptorValue,
- true, scriptContext) != 0;
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateArray(_In_ unsigned int length, _Out_ JsValueRef *result)
- {
- return ContextAPINoScriptWrapper([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateBasicArray, length);
- PARAM_NOT_NULL(result);
- *result = nullptr;
- *result = scriptContext->GetLibrary()->CreateArray(length);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateArrayBuffer(_In_ unsigned int byteLength, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateArrayBuffer, byteLength);
- PARAM_NOT_NULL(result);
- Js::JavascriptLibrary* library = scriptContext->GetLibrary();
- *result = library->CreateArrayBuffer(byteLength);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateExternalArrayBuffer(_Pre_maybenull_ _Pre_writable_byte_size_(byteLength) void *data, _In_ unsigned int byteLength,
- _In_opt_ JsFinalizeCallback finalizeCallback, _In_opt_ void *callbackState, _Out_ JsValueRef *result)
- {
- return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateExternalArrayBuffer, reinterpret_cast<BYTE*>(data), byteLength);
- PARAM_NOT_NULL(result);
- if (data == nullptr && byteLength > 0)
- {
- return JsErrorInvalidArgument;
- }
- Js::JavascriptLibrary* library = scriptContext->GetLibrary();
- *result = Js::JsrtExternalArrayBuffer::New(
- reinterpret_cast<BYTE*>(data),
- byteLength,
- finalizeCallback,
- callbackState,
- library->GetArrayBufferType());
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateTypedArray(_In_ JsTypedArrayType arrayType, _In_ JsValueRef baseArray, _In_ unsigned int byteOffset,
- _In_ unsigned int elementLength, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- if (baseArray != JS_INVALID_REFERENCE)
- {
- VALIDATE_INCOMING_REFERENCE(baseArray, scriptContext);
- }
- PARAM_NOT_NULL(result);
- Js::JavascriptLibrary* library = scriptContext->GetLibrary();
- const bool fromArrayBuffer = (baseArray != JS_INVALID_REFERENCE && Js::ArrayBuffer::Is(baseArray));
- if (byteOffset != 0 && !fromArrayBuffer)
- {
- return JsErrorInvalidArgument;
- }
- if (elementLength != 0 && !(baseArray == JS_INVALID_REFERENCE || fromArrayBuffer))
- {
- return JsErrorInvalidArgument;
- }
- Js::JavascriptFunction* constructorFunc = nullptr;
- Js::Var values[4] =
- {
- library->GetUndefined(),
- baseArray != nullptr ? baseArray : Js::JavascriptNumber::ToVar(elementLength, scriptContext)
- };
- if (fromArrayBuffer)
- {
- values[2] = Js::JavascriptNumber::ToVar(byteOffset, scriptContext);
- values[3] = Js::JavascriptNumber::ToVar(elementLength, scriptContext);
- }
- Js::CallInfo info(Js::CallFlags_New, fromArrayBuffer ? 4 : 2);
- Js::Arguments args(info, values);
- switch (arrayType)
- {
- case JsArrayTypeInt8:
- constructorFunc = library->GetInt8ArrayConstructor();
- break;
- case JsArrayTypeUint8:
- constructorFunc = library->GetUint8ArrayConstructor();
- break;
- case JsArrayTypeUint8Clamped:
- constructorFunc = library->GetUint8ClampedArrayConstructor();
- break;
- case JsArrayTypeInt16:
- constructorFunc = library->GetInt16ArrayConstructor();
- break;
- case JsArrayTypeUint16:
- constructorFunc = library->GetUint16ArrayConstructor();
- break;
- case JsArrayTypeInt32:
- constructorFunc = library->GetInt32ArrayConstructor();
- break;
- case JsArrayTypeUint32:
- constructorFunc = library->GetUint32ArrayConstructor();
- break;
- case JsArrayTypeFloat32:
- constructorFunc = library->GetFloat32ArrayConstructor();
- break;
- case JsArrayTypeFloat64:
- constructorFunc = library->GetFloat64ArrayConstructor();
- break;
- default:
- return JsErrorInvalidArgument;
- }
- *result = Js::JavascriptFunction::CallAsConstructor(constructorFunc, /* overridingNewTarget = */nullptr, args, scriptContext);
- JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateDataView(_In_ JsValueRef arrayBuffer, _In_ unsigned int byteOffset, _In_ unsigned int byteLength, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- VALIDATE_INCOMING_REFERENCE(arrayBuffer, scriptContext);
- PARAM_NOT_NULL(result);
- if (!Js::ArrayBuffer::Is(arrayBuffer))
- {
- return JsErrorInvalidArgument;
- }
- Js::JavascriptLibrary* library = scriptContext->GetLibrary();
- *result = library->CreateDataView(Js::ArrayBuffer::FromVar(arrayBuffer), byteOffset, byteLength);
- JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
- return JsNoError;
- });
- }
- C_ASSERT(JsArrayTypeUint8 - Js::TypeIds_Uint8Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
- C_ASSERT(JsArrayTypeUint8Clamped - Js::TypeIds_Uint8ClampedArray == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
- C_ASSERT(JsArrayTypeInt16 - Js::TypeIds_Int16Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
- C_ASSERT(JsArrayTypeUint16 - Js::TypeIds_Uint16Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
- C_ASSERT(JsArrayTypeInt32 - Js::TypeIds_Int32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
- C_ASSERT(JsArrayTypeUint32 - Js::TypeIds_Uint32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
- C_ASSERT(JsArrayTypeFloat32 - Js::TypeIds_Float32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
- C_ASSERT(JsArrayTypeFloat64 - Js::TypeIds_Float64Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
- inline JsTypedArrayType GetTypedArrayType(Js::TypeId typeId)
- {
- Assert(Js::TypedArrayBase::Is(typeId));
- return static_cast<JsTypedArrayType>(typeId + (JsArrayTypeInt8 - Js::TypeIds_Int8Array));
- }
- CHAKRA_API JsGetTypedArrayInfo(_In_ JsValueRef typedArray, _Out_opt_ JsTypedArrayType *arrayType, _Out_opt_ JsValueRef *arrayBuffer,
- _Out_opt_ unsigned int *byteOffset, _Out_opt_ unsigned int *byteLength)
- {
- VALIDATE_JSREF(typedArray);
- BEGIN_JSRT_NO_EXCEPTION
- {
- const Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(typedArray);
- if (!Js::TypedArrayBase::Is(typeId))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- if (arrayType != nullptr) {
- *arrayType = GetTypedArrayType(typeId);
- }
- Js::TypedArrayBase* typedArrayBase = Js::TypedArrayBase::FromVar(typedArray);
- if (arrayBuffer != nullptr) {
- *arrayBuffer = typedArrayBase->GetArrayBuffer();
- }
- if (byteOffset != nullptr) {
- *byteOffset = typedArrayBase->GetByteOffset();
- }
- if (byteLength != nullptr) {
- *byteLength = typedArrayBase->GetByteLength();
- }
- }
- #if ENABLE_TTD
- Js::ScriptContext* scriptContext = Js::RecyclableObject::FromVar(typedArray)->GetScriptContext();
- if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext) && arrayBuffer != nullptr)
- {
- scriptContext->GetThreadContext()->TTDLog->RecordJsRTGetTypedArrayInfo(typedArray, *arrayBuffer);
- }
- #endif
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsGetArrayBufferStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer,
- _Out_ unsigned int *bufferLength)
- {
- VALIDATE_JSREF(instance);
- PARAM_NOT_NULL(buffer);
- PARAM_NOT_NULL(bufferLength);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (!Js::ArrayBuffer::Is(instance))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- Js::ArrayBuffer* arrayBuffer = Js::ArrayBuffer::FromVar(instance);
- *buffer = arrayBuffer->GetBuffer();
- *bufferLength = arrayBuffer->GetByteLength();
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsGetTypedArrayStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer,
- _Out_ unsigned int *bufferLength, _Out_opt_ JsTypedArrayType *typedArrayType, _Out_opt_ int *elementSize)
- {
- VALIDATE_JSREF(instance);
- PARAM_NOT_NULL(buffer);
- PARAM_NOT_NULL(bufferLength);
- BEGIN_JSRT_NO_EXCEPTION
- {
- const Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(instance);
- if (!Js::TypedArrayBase::Is(typeId))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- Js::TypedArrayBase* typedArrayBase = Js::TypedArrayBase::FromVar(instance);
- *buffer = typedArrayBase->GetByteBuffer();
- *bufferLength = typedArrayBase->GetByteLength();
- if (typedArrayType)
- {
- *typedArrayType = GetTypedArrayType(typeId);
- }
- if (elementSize)
- {
- switch (typeId)
- {
- case Js::TypeIds_Int8Array:
- *elementSize = sizeof(int8);
- break;
- case Js::TypeIds_Uint8Array:
- *elementSize = sizeof(uint8);
- break;
- case Js::TypeIds_Uint8ClampedArray:
- *elementSize = sizeof(uint8);
- break;
- case Js::TypeIds_Int16Array:
- *elementSize = sizeof(int16);
- break;
- case Js::TypeIds_Uint16Array:
- *elementSize = sizeof(uint16);
- break;
- case Js::TypeIds_Int32Array:
- *elementSize = sizeof(int32);
- break;
- case Js::TypeIds_Uint32Array:
- *elementSize = sizeof(uint32);
- break;
- case Js::TypeIds_Float32Array:
- *elementSize = sizeof(float);
- break;
- case Js::TypeIds_Float64Array:
- *elementSize = sizeof(double);
- break;
- default:
- AssertMsg(FALSE, "invalid typed array type");
- *elementSize = 1;
- RETURN_NO_EXCEPTION(JsErrorFatal);
- }
- }
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsGetDataViewStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer, _Out_ unsigned int *bufferLength)
- {
- VALIDATE_JSREF(instance);
- PARAM_NOT_NULL(buffer);
- PARAM_NOT_NULL(bufferLength);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (!Js::DataView::Is(instance))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- Js::DataView* dataView = Js::DataView::FromVar(instance);
- *buffer = dataView->GetArrayBuffer()->GetBuffer() + dataView->GetByteOffset();
- *bufferLength = dataView->GetLength();
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsCreateSymbol(_In_ JsValueRef description, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateSymbol, description);
- PARAM_NOT_NULL(result);
- *result = nullptr;
- Js::JavascriptString* descriptionString;
- if (description != JS_INVALID_REFERENCE)
- {
- VALIDATE_INCOMING_REFERENCE(description, scriptContext);
- descriptionString = Js::JavascriptConversion::ToString(description, scriptContext);
- }
- else
- {
- descriptionString = scriptContext->GetLibrary()->GetEmptyString();
- }
- *result = scriptContext->GetLibrary()->CreateSymbol(descriptionString);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- return JsNoError;
- });
- }
- CHAKRA_API JsHasIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _Out_ bool *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_REFERENCE(index, scriptContext);
- PARAM_NOT_NULL(result);
- *result = false;
- *result = Js::JavascriptOperators::OP_HasItem((Js::Var)object, (Js::Var)index, scriptContext) != 0;
- return JsNoError;
- });
- }
- CHAKRA_API JsGetIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetIndex, index, object);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_REFERENCE(index, scriptContext);
- PARAM_NOT_NULL(result);
- *result = nullptr;
- *result = (JsValueRef)Js::JavascriptOperators::OP_GetElementI((Js::Var)object, (Js::Var)index, scriptContext);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- return JsNoError;
- });
- }
- CHAKRA_API JsSetIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _In_ JsValueRef value)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetIndex, object, index, value);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_REFERENCE(index, scriptContext);
- VALIDATE_INCOMING_REFERENCE(value, scriptContext);
- Js::JavascriptOperators::OP_SetElementI((Js::Var)object, (Js::Var)index, (Js::Var)value, scriptContext);
- return JsNoError;
- });
- }
- CHAKRA_API JsDeleteIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- VALIDATE_INCOMING_REFERENCE(index, scriptContext);
- Js::JavascriptOperators::OP_DeleteElementI((Js::Var)object, (Js::Var)index, scriptContext);
- return JsNoError;
- });
- }
- template <class T, bool clamped = false> struct TypedArrayTypeTraits { static const JsTypedArrayType cTypedArrayType; };
- template<> struct TypedArrayTypeTraits<int8> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt8; };
- template<> struct TypedArrayTypeTraits<uint8, false> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint8; };
- template<> struct TypedArrayTypeTraits<uint8, true> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint8Clamped; };
- template<> struct TypedArrayTypeTraits<int16> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt16; };
- template<> struct TypedArrayTypeTraits<uint16> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint16; };
- template<> struct TypedArrayTypeTraits<int32> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt32; };
- template<> struct TypedArrayTypeTraits<uint32> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint32; };
- template<> struct TypedArrayTypeTraits<float> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeFloat32; };
- template<> struct TypedArrayTypeTraits<double> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeFloat64; };
- template <class T, bool clamped = false>
- Js::ArrayObject* CreateTypedArray(Js::ScriptContext *scriptContext, void* data, unsigned int length)
- {
- Js::JavascriptLibrary* library = scriptContext->GetLibrary();
- Js::ArrayBufferBase* arrayBuffer = RecyclerNew(
- scriptContext->GetRecycler(),
- Js::ExternalArrayBuffer,
- reinterpret_cast<BYTE*>(data),
- length * sizeof(T),
- library->GetArrayBufferType());
- return static_cast<Js::ArrayObject*>(Js::TypedArray<T, clamped>::Create(arrayBuffer, 0, length, library));
- }
- template <class T, bool clamped = false>
- void GetObjectArrayData(Js::ArrayObject* objectArray, void** data, JsTypedArrayType* arrayType, uint* length)
- {
- Js::TypedArray<T, clamped>* typedArray = Js::TypedArray<T, clamped>::FromVar(objectArray);
- *data = typedArray->GetArrayBuffer()->GetBuffer();
- *arrayType = TypedArrayTypeTraits<T, clamped>::cTypedArrayType;
- *length = typedArray->GetLength();
- }
- CHAKRA_API JsSetIndexedPropertiesToExternalData(
- _In_ JsValueRef object,
- _In_ void* data,
- _In_ JsTypedArrayType arrayType,
- _In_ unsigned int elementLength)
- {
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- VALIDATE_INCOMING_OBJECT(object, scriptContext);
- // Don't support doing this on array or array-like object
- Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(object);
- if (!Js::DynamicType::Is(typeId)
- || Js::DynamicObject::IsAnyArrayTypeId(typeId)
- || (typeId >= Js::TypeIds_TypedArrayMin && typeId <= Js::TypeIds_TypedArrayMax)
- || typeId == Js::TypeIds_ArrayBuffer
- || typeId == Js::TypeIds_DataView
- || Js::RecyclableObject::FromVar(object)->IsExternal()
- )
- {
- return JsErrorInvalidArgument;
- }
- if (data == nullptr && elementLength > 0)
- {
- return JsErrorInvalidArgument;
- }
- Js::ArrayObject* newTypedArray = nullptr;
- switch (arrayType)
- {
- case JsArrayTypeInt8:
- newTypedArray = CreateTypedArray<int8>(scriptContext, data, elementLength);
- break;
- case JsArrayTypeUint8:
- newTypedArray = CreateTypedArray<uint8>(scriptContext, data, elementLength);
- break;
- case JsArrayTypeUint8Clamped:
- newTypedArray = CreateTypedArray<uint8, true>(scriptContext, data, elementLength);
- break;
- case JsArrayTypeInt16:
- newTypedArray = CreateTypedArray<int16>(scriptContext, data, elementLength);
- break;
- case JsArrayTypeUint16:
- newTypedArray = CreateTypedArray<uint16>(scriptContext, data, elementLength);
- break;
- case JsArrayTypeInt32:
- newTypedArray = CreateTypedArray<int32>(scriptContext, data, elementLength);
- break;
- case JsArrayTypeUint32:
- newTypedArray = CreateTypedArray<uint32>(scriptContext, data, elementLength);
- break;
- case JsArrayTypeFloat32:
- newTypedArray = CreateTypedArray<float>(scriptContext, data, elementLength);
- break;
- case JsArrayTypeFloat64:
- newTypedArray = CreateTypedArray<double>(scriptContext, data, elementLength);
- break;
- default:
- return JsErrorInvalidArgument;
- }
- Js::DynamicObject* dynamicObject = Js::DynamicObject::FromVar(object);
- dynamicObject->SetObjectArray(newTypedArray);
- return JsNoError;
- });
- }
- CHAKRA_API JsHasIndexedPropertiesExternalData(_In_ JsValueRef object, _Out_ bool *value)
- {
- VALIDATE_JSREF(object);
- PARAM_NOT_NULL(value);
- BEGIN_JSRT_NO_EXCEPTION
- {
- *value = false;
- if (Js::DynamicType::Is(Js::JavascriptOperators::GetTypeId(object)))
- {
- Js::DynamicObject* dynamicObject = Js::DynamicObject::FromVar(object);
- Js::ArrayObject* objectArray = dynamicObject->GetObjectArray();
- *value = (objectArray && !Js::DynamicObject::IsAnyArray(objectArray));
- }
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsGetIndexedPropertiesExternalData(
- _In_ JsValueRef object,
- _Out_ void** buffer,
- _Out_ JsTypedArrayType* arrayType,
- _Out_ unsigned int* elementLength)
- {
- VALIDATE_JSREF(object);
- PARAM_NOT_NULL(buffer);
- PARAM_NOT_NULL(arrayType);
- PARAM_NOT_NULL(elementLength);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (!Js::DynamicType::Is(Js::JavascriptOperators::GetTypeId(object)))
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- *buffer = nullptr;
- *arrayType = JsTypedArrayType();
- *elementLength = 0;
- Js::DynamicObject* dynamicObject = Js::DynamicObject::FromVar(object);
- Js::ArrayObject* objectArray = dynamicObject->GetObjectArray();
- if (!objectArray)
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- switch (Js::JavascriptOperators::GetTypeId(objectArray))
- {
- case Js::TypeIds_Int8Array:
- GetObjectArrayData<int8>(objectArray, buffer, arrayType, elementLength);
- break;
- case Js::TypeIds_Uint8Array:
- GetObjectArrayData<uint8>(objectArray, buffer, arrayType, elementLength);
- break;
- case Js::TypeIds_Uint8ClampedArray:
- GetObjectArrayData<uint8, true>(objectArray, buffer, arrayType, elementLength);
- break;
- case Js::TypeIds_Int16Array:
- GetObjectArrayData<int16>(objectArray, buffer, arrayType, elementLength);
- break;
- case Js::TypeIds_Uint16Array:
- GetObjectArrayData<uint16>(objectArray, buffer, arrayType, elementLength);
- break;
- case Js::TypeIds_Int32Array:
- GetObjectArrayData<int32>(objectArray, buffer, arrayType, elementLength);
- break;
- case Js::TypeIds_Uint32Array:
- GetObjectArrayData<uint32>(objectArray, buffer, arrayType, elementLength);
- break;
- case Js::TypeIds_Float32Array:
- GetObjectArrayData<float>(objectArray, buffer, arrayType, elementLength);
- break;
- case Js::TypeIds_Float64Array:
- GetObjectArrayData<double>(objectArray, buffer, arrayType, elementLength);
- break;
- default:
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsEquals(_In_ JsValueRef object1, _In_ JsValueRef object2, _Out_ bool *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTEquals, object1, object2, false);
- VALIDATE_INCOMING_REFERENCE(object1, scriptContext);
- VALIDATE_INCOMING_REFERENCE(object2, scriptContext);
- PARAM_NOT_NULL(result);
- *result = Js::JavascriptOperators::Equal((Js::Var)object1, (Js::Var)object2, scriptContext) != 0;
- return JsNoError;
- });
- }
- CHAKRA_API JsStrictEquals(_In_ JsValueRef object1, _In_ JsValueRef object2, _Out_ bool *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTEquals, object1, object2, true);
- VALIDATE_INCOMING_REFERENCE(object1, scriptContext);
- VALIDATE_INCOMING_REFERENCE(object2, scriptContext);
- PARAM_NOT_NULL(result);
- *result = Js::JavascriptOperators::StrictEqual((Js::Var)object1, (Js::Var)object2, scriptContext) != 0;
- return JsNoError;
- });
- }
- CHAKRA_API JsHasExternalData(_In_ JsValueRef object, _Out_ bool *value)
- {
- VALIDATE_JSREF(object);
- PARAM_NOT_NULL(value);
- BEGIN_JSRT_NO_EXCEPTION
- {
- *value = JsrtExternalObject::Is(object);
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsGetExternalData(_In_ JsValueRef object, _Out_ void **data)
- {
- VALIDATE_JSREF(object);
- PARAM_NOT_NULL(data);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (JsrtExternalObject::Is(object))
- {
- *data = JsrtExternalObject::FromVar(object)->GetSlotData();
- }
- else
- {
- *data = nullptr;
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsSetExternalData(_In_ JsValueRef object, _In_opt_ void *data)
- {
- VALIDATE_JSREF(object);
- BEGIN_JSRT_NO_EXCEPTION
- {
- if (JsrtExternalObject::Is(object))
- {
- JsrtExternalObject::FromVar(object)->SetSlotData(data);
- }
- else
- {
- RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
- }
- }
- END_JSRT_NO_EXCEPTION
- }
- CHAKRA_API JsCallFunction(_In_ JsValueRef function, _In_reads_(cargs) JsValueRef *args, _In_ ushort cargs, _Out_opt_ JsValueRef *result)
- {
- if(result != nullptr)
- {
- *result = nullptr;
- }
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- #if ENABLE_TTD
- TTD::TTDJsRTFunctionCallActionPopperRecorder callInfoPopper;
- if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
- {
- TTD::NSLogEvents::EventLogEntry* callEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCallFunction(_actionEntryPopper, scriptContext->GetThreadContext()->TTDRootNestingCount, function, cargs, args);
- callInfoPopper.InitializeForRecording(scriptContext, callEvent);
- if(scriptContext->GetThreadContext()->TTDRootNestingCount == 0)
- {
- TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
- elog->ResetCallStackForTopLevelCall(elog->GetLastEventTime());
- }
- }
- #endif
- VALIDATE_INCOMING_FUNCTION(function, scriptContext);
- if(cargs == 0 || args == nullptr)
- {
- return JsErrorInvalidArgument;
- }
- for(int index = 0; index < cargs; index++)
- {
- VALIDATE_INCOMING_REFERENCE(args[index], scriptContext);
- }
- Js::JavascriptFunction *jsFunction = Js::JavascriptFunction::FromVar(function);
- Js::CallInfo callInfo(cargs);
- Js::Arguments jsArgs(callInfo, reinterpret_cast<Js::Var *>(args));
- Js::Var varResult = jsFunction->CallRootFunction(jsArgs, scriptContext, true);
- if(result != nullptr)
- {
- *result = varResult;
- Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
- }
- #if ENABLE_TTD
- if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
- {
- _actionEntryPopper.SetResult(result);
- }
- #endif
- return JsNoError;
- });
- }
- CHAKRA_API JsConstructObject(_In_ JsValueRef function, _In_reads_(cargs) JsValueRef *args, _In_ ushort cargs, _Out_ JsValueRef *result)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTConstructCall, function, cargs, args);
- VALIDATE_INCOMING_FUNCTION(function, scriptContext);
- PARAM_NOT_NULL(result);
- *result = nullptr;
- if (cargs == 0 || args == nullptr)
- {
- return JsErrorInvalidArgument;
- }
- for (int index = 0; index < cargs; index++)
- {
- VALIDATE_INCOMING_REFERENCE(args[index], scriptContext);
- }
- Js::JavascriptFunction *jsFunction = Js::JavascriptFunction::FromVar(function);
- Js::CallInfo callInfo(Js::CallFlags::CallFlags_New, cargs);
- Js::Arguments jsArgs(callInfo, reinterpret_cast<Js::Var *>(args));
- //
- //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
- //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!!!!");
- //
- *result = Js::JavascriptFunction::CallAsConstructor(jsFunction, /* overridingNewTarget = */nullptr, jsArgs, scriptContext);
- Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateFunction(_In_ JsNativeFunction nativeFunction, _In_opt_ void *callbackState, _Out_ JsValueRef *function)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateFunction, false, nullptr);
- PARAM_NOT_NULL(nativeFunction);
- PARAM_NOT_NULL(function);
- *function = nullptr;
- Js::JavascriptExternalFunction *externalFunction = scriptContext->GetLibrary()->CreateStdCallExternalFunction((Js::StdCallJavascriptMethod)nativeFunction, 0, callbackState);
- *function = (JsValueRef)externalFunction;
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, function);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateNamedFunction(_In_ JsValueRef name, _In_ JsNativeFunction nativeFunction, _In_opt_ void *callbackState, _Out_ JsValueRef *function)
- {
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateFunction, true, name);
- VALIDATE_INCOMING_REFERENCE(name, scriptContext);
- PARAM_NOT_NULL(nativeFunction);
- PARAM_NOT_NULL(function);
- *function = nullptr;
- if (name != JS_INVALID_REFERENCE)
- {
- name = Js::JavascriptConversion::ToString(name, scriptContext);
- }
- else
- {
- name = scriptContext->GetLibrary()->GetEmptyString();
- }
- Js::JavascriptExternalFunction *externalFunction = scriptContext->GetLibrary()->CreateStdCallExternalFunction((Js::StdCallJavascriptMethod)nativeFunction, Js::JavascriptString::FromVar(name), callbackState);
- *function = (JsValueRef)externalFunction;
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, function);
- return JsNoError;
- });
- }
- void SetErrorMessage(Js::ScriptContext *scriptContext, JsValueRef newError, JsValueRef message)
- {
- Js::JavascriptOperators::OP_SetProperty(newError, Js::PropertyIds::message, message, scriptContext);
- }
- CHAKRA_API JsCreateError(_In_ JsValueRef message, _Out_ JsValueRef *error)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateError, message);
- VALIDATE_INCOMING_REFERENCE(message, scriptContext);
- PARAM_NOT_NULL(error);
- *error = nullptr;
- JsValueRef newError = scriptContext->GetLibrary()->CreateError();
- SetErrorMessage(scriptContext, newError, message);
- *error = newError;
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateRangeError(_In_ JsValueRef message, _Out_ JsValueRef *error)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateRangeError, message);
- VALIDATE_INCOMING_REFERENCE(message, scriptContext);
- PARAM_NOT_NULL(error);
- *error = nullptr;
- JsValueRef newError = scriptContext->GetLibrary()->CreateRangeError();
- SetErrorMessage(scriptContext, newError, message);
- *error = newError;
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateReferenceError(_In_ JsValueRef message, _Out_ JsValueRef *error)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateReferenceError, message);
- VALIDATE_INCOMING_REFERENCE(message, scriptContext);
- PARAM_NOT_NULL(error);
- *error = nullptr;
- JsValueRef newError = scriptContext->GetLibrary()->CreateReferenceError();
- SetErrorMessage(scriptContext, newError, message);
- *error = newError;
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateSyntaxError(_In_ JsValueRef message, _Out_ JsValueRef *error)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateSyntaxError, message);
- VALIDATE_INCOMING_REFERENCE(message, scriptContext);
- PARAM_NOT_NULL(error);
- *error = nullptr;
- JsValueRef newError = scriptContext->GetLibrary()->CreateSyntaxError();
- SetErrorMessage(scriptContext, newError, message);
- *error = newError;
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateTypeError(_In_ JsValueRef message, _Out_ JsValueRef *error)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateTypeError, message);
- VALIDATE_INCOMING_REFERENCE(message, scriptContext);
- PARAM_NOT_NULL(error);
- *error = nullptr;
- JsValueRef newError = scriptContext->GetLibrary()->CreateTypeError();
- SetErrorMessage(scriptContext, newError, message);
- *error = newError;
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
- return JsNoError;
- });
- }
- CHAKRA_API JsCreateURIError(_In_ JsValueRef message, _Out_ JsValueRef *error)
- {
- return ContextAPIWrapper<true>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateURIError, message);
- VALIDATE_INCOMING_REFERENCE(message, scriptContext);
- PARAM_NOT_NULL(error);
- *error = nullptr;
- JsValueRef newError = scriptContext->GetLibrary()->CreateURIError();
- SetErrorMessage(scriptContext, newError, message);
- *error = newError;
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
- return JsNoError;
- });
- }
- CHAKRA_API JsHasException(_Out_ bool *hasException)
- {
- PARAM_NOT_NULL(hasException);
- *hasException = false;
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- if (currentContext == nullptr)
- {
- return JsErrorNoCurrentContext;
- }
- Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
- Assert(scriptContext != nullptr);
- if (scriptContext->GetRecycler() && scriptContext->GetRecycler()->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- if (scriptContext->GetThreadContext()->IsExecutionDisabled())
- {
- return JsErrorInDisabledState;
- }
- *hasException = scriptContext->HasRecordedException();
- return JsNoError;
- }
- CHAKRA_API JsGetAndClearException(_Out_ JsValueRef *exception)
- {
- PARAM_NOT_NULL(exception);
- *exception = nullptr;
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- if (currentContext == nullptr)
- {
- return JsErrorNoCurrentContext;
- }
- Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
- Assert(scriptContext != nullptr);
- if (scriptContext->GetRecycler() && scriptContext->GetRecycler()->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- if (scriptContext->GetThreadContext()->IsExecutionDisabled())
- {
- return JsErrorInDisabledState;
- }
- HRESULT hr = S_OK;
- Js::JavascriptExceptionObject *recordedException = nullptr;
- BEGIN_TRANSLATE_OOM_TO_HRESULT
- recordedException = scriptContext->GetAndClearRecordedException();
- END_TRANSLATE_OOM_TO_HRESULT(hr)
- if (hr == E_OUTOFMEMORY)
- {
- recordedException = scriptContext->GetThreadContext()->GetRecordedException();
- }
- if (recordedException == nullptr)
- {
- return JsErrorInvalidArgument;
- }
- *exception = recordedException->GetThrownObject(nullptr);
- #if ENABLE_TTD
- if(hr != E_OUTOFMEMORY)
- {
- TTD::TTDJsRTActionResultAutoRecorder _actionEntryPopper;
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetAndClearException);
- PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, exception);
- }
- #endif
- if (*exception == nullptr)
- {
- return JsErrorInvalidArgument;
- }
- return JsNoError;
- }
- CHAKRA_API JsSetException(_In_ JsValueRef exception)
- {
- return ContextAPINoScriptWrapper([&](Js::ScriptContext* scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- JsrtContext * context = JsrtContext::GetCurrent();
- JsrtRuntime * runtime = context->GetRuntime();
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetException, exception, runtime->DispatchExceptions());
- VALIDATE_INCOMING_REFERENCE(exception, scriptContext);
- Js::JavascriptExceptionObject *exceptionObject;
- exceptionObject = RecyclerNew(scriptContext->GetRecycler(), Js::JavascriptExceptionObject, exception, scriptContext, nullptr);
- scriptContext->RecordException(exceptionObject, runtime->DispatchExceptions());
- return JsNoError;
- });
- }
- CHAKRA_API JsGetRuntimeMemoryUsage(_In_ JsRuntimeHandle runtimeHandle, _Out_ size_t * memoryUsage)
- {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- PARAM_NOT_NULL(memoryUsage);
- *memoryUsage = 0;
- ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
- AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
- *memoryUsage = allocPolicyManager->GetUsage();
- return JsNoError;
- }
- CHAKRA_API JsSetRuntimeMemoryLimit(_In_ JsRuntimeHandle runtimeHandle, _In_ size_t memoryLimit)
- {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
- AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
- allocPolicyManager->SetLimit(memoryLimit);
- return JsNoError;
- }
- CHAKRA_API JsGetRuntimeMemoryLimit(_In_ JsRuntimeHandle runtimeHandle, _Out_ size_t * memoryLimit)
- {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- PARAM_NOT_NULL(memoryLimit);
- *memoryLimit = 0;
- ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
- AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
- *memoryLimit = allocPolicyManager->GetLimit();
- return JsNoError;
- }
- C_ASSERT(JsMemoryAllocate == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryAllocate);
- C_ASSERT(JsMemoryFree == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryFree);
- C_ASSERT(JsMemoryFailure == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryFailure);
- C_ASSERT(JsMemoryFailure == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryMax);
- CHAKRA_API JsSetRuntimeMemoryAllocationCallback(_In_ JsRuntimeHandle runtime, _In_opt_ void *callbackState, _In_ JsMemoryAllocationCallback allocationCallback)
- {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtime);
- ThreadContext* threadContext = JsrtRuntime::FromHandle(runtime)->GetThreadContext();
- AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
- allocPolicyManager->SetMemoryAllocationCallback(callbackState, (AllocationPolicyManager::PageAllocatorMemoryAllocationCallback)allocationCallback);
- return JsNoError;
- }
- CHAKRA_API JsSetRuntimeBeforeCollectCallback(_In_ JsRuntimeHandle runtime, _In_opt_ void *callbackState, _In_ JsBeforeCollectCallback beforeCollectCallback)
- {
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtime);
- JsrtRuntime::FromHandle(runtime)->SetBeforeCollectCallback(beforeCollectCallback, callbackState);
- return JsNoError;
- });
- }
- CHAKRA_API JsDisableRuntimeExecution(_In_ JsRuntimeHandle runtimeHandle)
- {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
- if (!threadContext->TestThreadContextFlag(ThreadContextFlagCanDisableExecution))
- {
- return JsErrorCannotDisableExecution;
- }
- if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if (threadContext->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- threadContext->DisableExecution();
- return JsNoError;
- }
- CHAKRA_API JsEnableRuntimeExecution(_In_ JsRuntimeHandle runtimeHandle)
- {
- return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
- if (!threadContext->TestThreadContextFlag(ThreadContextFlagCanDisableExecution))
- {
- return JsNoError;
- }
- if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if (threadContext->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- ThreadContextScope scope(threadContext);
- if (!scope.IsValid())
- {
- return JsErrorWrongThread;
- }
- threadContext->EnableExecution();
- return JsNoError;
- });
- }
- CHAKRA_API JsIsRuntimeExecutionDisabled(_In_ JsRuntimeHandle runtimeHandle, _Out_ bool *isDisabled)
- {
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- PARAM_NOT_NULL(isDisabled);
- *isDisabled = false;
- ThreadContext* threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
- *isDisabled = threadContext->IsExecutionDisabled();
- return JsNoError;
- }
- CHAKRA_API JsGetPropertyIdFromName(_In_z_ const wchar_t *name, _Out_ JsPropertyIdRef *propertyId)
- {
- return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext * scriptContext) -> JsErrorCode {
- PARAM_NOT_NULL(name);
- PARAM_NOT_NULL(propertyId);
- *propertyId = nullptr;
- size_t cPropertyNameLength = wcslen(name);
- if (cPropertyNameLength <= INT_MAX)
- {
- scriptContext->GetOrAddPropertyRecord(name, static_cast<int>(cPropertyNameLength), (Js::PropertyRecord const **)propertyId);
- return JsNoError;
- }
- else
- {
- return JsErrorOutOfMemory;
- }
- });
- }
- CHAKRA_API JsGetPropertyIdFromSymbol(_In_ JsValueRef symbol, _Out_ JsPropertyIdRef *propertyId)
- {
- return ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetPropertyIdFromSymbol, symbol);
- VALIDATE_INCOMING_REFERENCE(symbol, scriptContext);
- PARAM_NOT_NULL(propertyId);
- *propertyId = nullptr;
- if (!Js::JavascriptSymbol::Is(symbol))
- {
- return JsErrorPropertyNotSymbol;
- }
- *propertyId = (JsPropertyIdRef)Js::JavascriptSymbol::FromVar(symbol)->GetValue();
- return JsNoError;
- },
- /*allowInObjectBeforeCollectCallback*/true);
- }
- CHAKRA_API JsGetSymbolFromPropertyId(_In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *symbol)
- {
- return ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- PARAM_NOT_NULL(symbol);
- *symbol = nullptr;
- Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
- if (!propertyRecord->IsSymbol())
- {
- return JsErrorPropertyNotSymbol;
- }
- *symbol = scriptContext->GetLibrary()->CreateSymbol(propertyRecord);
- return JsNoError;
- });
- }
- #pragma prefast(suppress:6101, "Prefast doesn't see through the lambda")
- CHAKRA_API JsGetPropertyNameFromId(_In_ JsPropertyIdRef propertyId, _Outptr_result_z_ const wchar_t **name)
- {
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- PARAM_NOT_NULL(name);
- *name = nullptr;
- Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
- if (propertyRecord->IsSymbol())
- {
- return JsErrorPropertyNotString;
- }
- *name = propertyRecord->GetBuffer();
- return JsNoError;
- });
- }
- CHAKRA_API JsGetPropertyIdType(_In_ JsPropertyIdRef propertyId, _Out_ JsPropertyIdType* propertyIdType)
- {
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- VALIDATE_INCOMING_PROPERTYID(propertyId);
- Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
- if (propertyRecord->IsSymbol())
- {
- *propertyIdType = JsPropertyIdTypeSymbol;
- }
- else
- {
- *propertyIdType = JsPropertyIdTypeString;
- }
- return JsNoError;
- });
- }
- CHAKRA_API JsGetRuntime(_In_ JsContextRef context, _Out_ JsRuntimeHandle *runtime)
- {
- VALIDATE_JSREF(context);
- PARAM_NOT_NULL(runtime);
- *runtime = nullptr;
- if (!JsrtContext::Is(context))
- {
- return JsErrorInvalidArgument;
- }
- *runtime = static_cast<JsrtContext *>(context)->GetRuntime();
- return JsNoError;
- }
- CHAKRA_API JsIdle(_Out_opt_ unsigned int *nextIdleTick)
- {
- PARAM_NOT_NULL(nextIdleTick);
- return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext * scriptContext) -> JsErrorCode {
- *nextIdleTick = 0;
- if (scriptContext->GetThreadContext()->GetRecycler() && scriptContext->GetThreadContext()->GetRecycler()->IsHeapEnumInProgress())
- {
- return JsErrorHeapEnumInProgress;
- }
- else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
- {
- return JsErrorInThreadServiceCallback;
- }
- JsrtContext * context = JsrtContext::GetCurrent();
- JsrtRuntime * runtime = context->GetRuntime();
- if (!runtime->UseIdle())
- {
- return JsErrorIdleNotEnabled;
- }
- unsigned int ticks = runtime->Idle();
- *nextIdleTick = ticks;
- return JsNoError;
- });
- }
- CHAKRA_API JsSetPromiseContinuationCallback(_In_ JsPromiseContinuationCallback promiseContinuationCallback, _In_opt_ void *callbackState)
- {
- return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext * scriptContext) -> JsErrorCode {
- PARAM_NOT_NULL(promiseContinuationCallback);
- scriptContext->GetLibrary()->SetNativeHostPromiseContinuationFunction((Js::JavascriptLibrary::PromiseContinuationCallback)promiseContinuationCallback, callbackState);
- return JsNoError;
- },
- /*allowInObjectBeforeCollectCallback*/true);
- }
- JsErrorCode RunScriptCore(JsValueRef scriptSource, const byte *script, size_t cb,
- LoadScriptFlag loadScriptFlag, JsSourceContext sourceContext,
- const wchar_t *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
- bool isSourceModule, JsValueRef *result)
- {
- Js::JavascriptFunction *scriptFunction;
- CompileScriptException se;
- JsErrorCode errorCode = ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PARAM_NOT_NULL(script);
- PARAM_NOT_NULL(sourceUrl);
- SourceContextInfo * sourceContextInfo = scriptContext->GetSourceContextInfo(sourceContext, nullptr);
- if (sourceContextInfo == nullptr)
- {
- sourceContextInfo = scriptContext->CreateSourceContextInfo(sourceContext, sourceUrl, wcslen(sourceUrl), nullptr);
- }
- const int chsize = (loadScriptFlag & LoadScriptFlag_Utf8Source) ?
- sizeof(utf8char_t) : sizeof(wchar_t);
- SRCINFO si = {
- /* sourceContextInfo */ sourceContextInfo,
- /* dlnHost */ 0,
- /* ulColumnHost */ 0,
- /* lnMinHost */ 0,
- /* ichMinHost */ 0,
- /* ichLimHost */ static_cast<ULONG>(cb / chsize), // OK to truncate since this is used to limit sourceText in debugDocument/compilation errors.
- /* ulCharOffset */ 0,
- /* mod */ kmodGlobal,
- /* grfsi */ 0
- };
- Js::Utf8SourceInfo* utf8SourceInfo = nullptr;
- if (result != nullptr)
- {
- loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Expression);
- }
- bool isLibraryCode = (parseAttributes & JsParseScriptAttributeLibraryCode) == JsParseScriptAttributeLibraryCode;
- if (isLibraryCode)
- {
- loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_LibraryCode);
- }
- if (isSourceModule)
- {
- loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Module);
- }
- #if ENABLE_TTD
- TTD::NSLogEvents::EventLogEntry* parseEvent = nullptr;
- if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
- {
- parseEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCodeParse(_actionEntryPopper,
- loadScriptFlag, ((loadScriptFlag & LoadScriptFlag_Utf8Source) == LoadScriptFlag_Utf8Source),
- script, (uint32)cb, sourceContext, sourceUrl);
- }
- #endif
- scriptFunction = scriptContext->LoadScript(script, cb,
- &si, &se, &utf8SourceInfo,
- Js::Constants::GlobalCode, loadScriptFlag, scriptSource);
- #if ENABLE_TTD
- if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
- {
- _actionEntryPopper.SetResult((Js::Var*)&scriptFunction);
- }
- //
- //TODO: We may (probably?) want to use the debugger source rundown functionality here instead
- //
- if (scriptContext->IsTTDRecordModeEnabled())
- {
- //Make sure we have the body and text information available
- Js::FunctionBody* globalBody = TTD::JsSupport::ForceAndGetFunctionBody(scriptFunction->GetParseableFunctionInfo());
- const TTD::NSSnapValues::TopLevelScriptLoadFunctionBodyResolveInfo* tbfi = scriptContext->GetThreadContext()->TTDLog->AddScriptLoad(globalBody, kmodGlobal, globalBody->GetUtf8SourceInfo()->GetSourceInfoId(), script, (uint32)cb, loadScriptFlag);
- if(parseEvent != nullptr)
- {
- TTD::NSLogEvents::JsRTCodeParseAction_SetBodyCtrId(parseEvent, tbfi->TopLevelBase.TopLevelBodyCtr);
- }
- //walk global body to (1) add functions to pin set (2) build parent map
- BEGIN_JS_RUNTIME_CALL(scriptContext);
- {
- scriptContext->TTDContextInfo->ProcessFunctionBodyOnLoad(globalBody, nullptr);
- scriptContext->TTDContextInfo->RegisterLoadedScript(globalBody, tbfi->TopLevelBase.TopLevelBodyCtr);
- }
- END_JS_RUNTIME_CALL(scriptContext);
- }
- #endif
- JsrtContext * context = JsrtContext::GetCurrent();
- context->OnScriptLoad(scriptFunction, utf8SourceInfo, &se);
- return JsNoError;
- });
- if (errorCode != JsNoError)
- {
- return errorCode;
- }
- return ContextAPIWrapper<false>([&](Js::ScriptContext* scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- if (scriptFunction == nullptr)
- {
- PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
- HandleScriptCompileError(scriptContext, &se);
- return JsErrorScriptCompile;
- }
- if (parseOnly)
- {
- PARAM_NOT_NULL(result);
- *result = scriptFunction;
- }
- else
- {
- Js::Arguments args(0, nullptr);
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- Js::Var varThis;
- if (PHASE_FORCE1(Js::EvalCompilePhase))
- {
- varThis = Js::JavascriptOperators::OP_GetThis(scriptContext->GetLibrary()->GetUndefined(), kmodGlobal, scriptContext);
- args.Info.Flags = (Js::CallFlags)Js::CallFlags::CallFlags_Eval;
- args.Info.Count = 1;
- args.Values = &varThis;
- }
- #endif
- #if ENABLE_TTD
- TTD::TTDJsRTFunctionCallActionPopperRecorder callInfoPopper;
- if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
- {
- TTD::NSLogEvents::EventLogEntry* callEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCallFunction(_actionEntryPopper, scriptContext->GetThreadContext()->TTDRootNestingCount, scriptFunction, args.Info.Count, args.Values);
- callInfoPopper.InitializeForRecording(scriptContext, callEvent);
- if(scriptContext->GetThreadContext()->TTDRootNestingCount == 0)
- {
- TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
- elog->ResetCallStackForTopLevelCall(elog->GetLastEventTime());
- }
- }
- #endif
- Js::Var varResult = scriptFunction->CallRootFunction(args, scriptContext, true);
- if (result != nullptr)
- {
- *result = varResult;
- }
- #if ENABLE_TTD
- if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
- {
- _actionEntryPopper.SetResult(result);
- }
- #endif
- }
- return JsNoError;
- });
- }
- JsErrorCode RunScriptCore(const char *script, JsSourceContext sourceContext,
- const char *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
- bool isSourceModule, JsValueRef *result)
- {
- utf8::NarrowToWide url((LPCSTR)sourceUrl);
- if (!url)
- {
- return JsErrorOutOfMemory;
- }
- return RunScriptCore(nullptr, reinterpret_cast<const byte*>(script), strlen(script),
- LoadScriptFlag_Utf8Source, sourceContext, url, parseOnly, parseAttributes,
- isSourceModule, result);
- }
- JsErrorCode RunScriptCore(const wchar_t *script, JsSourceContext sourceContext,
- const wchar_t *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
- bool isSourceModule, JsValueRef *result)
- {
- return RunScriptCore(nullptr, reinterpret_cast<const byte*>(script),
- wcslen(script) * sizeof(wchar_t),
- LoadScriptFlag_None, sourceContext, sourceUrl, parseOnly,
- parseAttributes, isSourceModule, result);
- }
- #ifdef _WIN32
- CHAKRA_API JsParseScript(_In_z_ const wchar_t * script, _In_ JsSourceContext sourceContext,
- _In_z_ const wchar_t *sourceUrl, _Out_ JsValueRef * result)
- {
- return RunScriptCore(script, sourceContext, sourceUrl, true,
- JsParseScriptAttributeNone, false /*isModule*/, result);
- }
- CHAKRA_API JsParseScriptWithAttributes(
- _In_z_ const wchar_t *script,
- _In_ JsSourceContext sourceContext,
- _In_z_ const wchar_t *sourceUrl,
- _In_ JsParseScriptAttributes parseAttributes,
- _Out_ JsValueRef *result)
- {
- return RunScriptCore(script, sourceContext, sourceUrl, true,
- parseAttributes, false /*isModule*/, result);
- }
- CHAKRA_API JsRunScript(_In_z_ const wchar_t * script, _In_ JsSourceContext sourceContext,
- _In_z_ const wchar_t *sourceUrl, _Out_ JsValueRef * result)
- {
- return RunScriptCore(script, sourceContext, sourceUrl, false,
- JsParseScriptAttributeNone, false /*isModule*/, result);
- }
- CHAKRA_API JsExperimentalApiRunModule(_In_z_ const wchar_t * script,
- _In_ JsSourceContext sourceContext, _In_z_ const wchar_t *sourceUrl,
- _Out_ JsValueRef * result)
- {
- return RunScriptCore(script, sourceContext, sourceUrl, false,
- JsParseScriptAttributeNone, true, result);
- }
- #endif
- JsErrorCode JsSerializeScriptCore(const byte *script, size_t cb,
- LoadScriptFlag loadScriptFlag, BYTE *functionTable, int functionTableSize,
- unsigned char *buffer, unsigned int *bufferSize, JsValueRef scriptSource)
- {
- Js::JavascriptFunction *function;
- CompileScriptException se;
- JsErrorCode errorCode = ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
- PARAM_NOT_NULL(script);
- PARAM_NOT_NULL(bufferSize);
- if (*bufferSize > 0)
- {
- PARAM_NOT_NULL(buffer);
- ZeroMemory(buffer, *bufferSize);
- }
- if (scriptContext->IsScriptContextInDebugMode())
- {
- return JsErrorCannotSerializeDebugScript;
- }
- SourceContextInfo * sourceContextInfo = scriptContext->GetSourceContextInfo(JS_SOURCE_CONTEXT_NONE, nullptr);
- Assert(sourceContextInfo != nullptr);
- const int chsize = (loadScriptFlag & LoadScriptFlag_Utf8Source) ? sizeof(utf8char_t) : sizeof(wchar_t);
- SRCINFO si = {
- /* sourceContextInfo */ sourceContextInfo,
- /* dlnHost */ 0,
- /* ulColumnHost */ 0,
- /* lnMinHost */ 0,
- /* ichMinHost */ 0,
- /* ichLimHost */ static_cast<ULONG>(cb / chsize), // OK to truncate since this is used to limit sourceText in debugDocument/compilation errors.
- /* ulCharOffset */ 0,
- /* mod */ kmodGlobal,
- /* grfsi */ 0
- };
- bool isSerializeByteCodeForLibrary = false;
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- isSerializeByteCodeForLibrary = JsrtContext::GetCurrent()->GetRuntime()->IsSerializeByteCodeForLibrary();
- #endif
- Js::Utf8SourceInfo* sourceInfo = nullptr;
- loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_disableDeferredParse);
- if (isSerializeByteCodeForLibrary)
- {
- loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_isByteCodeBufferForLibrary);
- }
- else
- {
- loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Expression);
- }
- function = scriptContext->LoadScript(script, cb, &si, &se, &sourceInfo,
- Js::Constants::GlobalCode, loadScriptFlag, scriptSource);
- return JsNoError;
- });
- if (errorCode != JsNoError)
- {
- return errorCode;
- }
- return ContextAPIWrapper_NoRecord<false>([&](Js::ScriptContext* scriptContext) -> JsErrorCode {
- if (function == nullptr)
- {
- HandleScriptCompileError(scriptContext, &se);
- return JsErrorScriptCompile;
- }
- // Could we have a deserialized function in this case?
- // If we are going to serialize it, a check isn't to expensive
- if (CONFIG_FLAG(ForceSerialized) && function->GetFunctionProxy() != nullptr) {
- function->GetFunctionProxy()->EnsureDeserialized();
- }
- Js::FunctionBody *functionBody = function->GetFunctionBody();
- const Js::Utf8SourceInfo *sourceInfo = functionBody->GetUtf8SourceInfo();
- size_t cSourceCodeLength = sourceInfo->GetCbLength(_u("JsSerializeScript"));
- // truncation of code length can lead to accessing random memory. Reject the call.
- if (cSourceCodeLength > DWORD_MAX)
- {
- return JsErrorOutOfMemory;
- }
- LPCUTF8 utf8Code = sourceInfo->GetSource(_u("JsSerializeScript"));
- DWORD dwFlags = 0;
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- dwFlags = JsrtContext::GetCurrent()->GetRuntime()->IsSerializeByteCodeForLibrary() ? GENERATE_BYTE_CODE_BUFFER_LIBRARY : 0;
- #endif
- BEGIN_TEMP_ALLOCATOR(tempAllocator, scriptContext, _u("ByteCodeSerializer"));
- // We cast buffer size to DWORD* because on Windows, DWORD = unsigned long = unsigned int
- // On 64-bit clang on linux, this is not true, unsigned long is larger than unsigned int
- // However, the PAL defines DWORD for us on linux as unsigned int so the cast is safe here.
- HRESULT hr = Js::ByteCodeSerializer::SerializeToBuffer(scriptContext,
- tempAllocator, static_cast<DWORD>(cSourceCodeLength), utf8Code,
- functionBody, functionBody->GetHostSrcInfo(), false, &buffer,
- (DWORD*) bufferSize, dwFlags);
- END_TEMP_ALLOCATOR(tempAllocator, scriptContext);
- if (SUCCEEDED(hr))
- {
- return JsNoError;
- }
- else
- {
- return JsErrorScriptCompile;
- }
- });
- }
- CHAKRA_API JsSerializeScript(_In_z_ const wchar_t *script, _Out_writes_to_opt_(*bufferSize,
- *bufferSize) unsigned char *buffer,
- _Inout_ unsigned int *bufferSize)
- {
- return JsSerializeScriptCore((const byte*)script, wcslen(script) * sizeof(wchar_t),
- LoadScriptFlag_None, nullptr, 0, buffer, bufferSize, nullptr);
- }
- template <typename TLoadCallback, typename TUnloadCallback>
- JsErrorCode RunSerializedScriptCore(
- TLoadCallback scriptLoadCallback, TUnloadCallback scriptUnloadCallback,
- JsSourceContext scriptLoadSourceContext, // only used by scriptLoadCallback
- unsigned char *buffer, JsValueRef bufferVal,
- JsSourceContext sourceContext, const wchar_t *sourceUrl,
- bool parseOnly, JsValueRef *result)
- {
- Js::JavascriptFunction *function;
- JsErrorCode errorCode = ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
- if (result != nullptr)
- {
- *result = nullptr;
- }
- PARAM_NOT_NULL(buffer);
- PARAM_NOT_NULL(sourceUrl);
- Js::ISourceHolder *sourceHolder = nullptr;
- PARAM_NOT_NULL(scriptLoadCallback);
- PARAM_NOT_NULL(scriptUnloadCallback);
- typedef Js::JsrtSourceHolder<TLoadCallback, TUnloadCallback> TSourceHolder;
- sourceHolder = RecyclerNewFinalized(scriptContext->GetRecycler(), TSourceHolder,
- scriptLoadCallback, scriptUnloadCallback, scriptLoadSourceContext, bufferVal);
- SourceContextInfo *sourceContextInfo;
- SRCINFO *hsi;
- Js::FunctionBody *functionBody = nullptr;
- HRESULT hr;
- sourceContextInfo = scriptContext->GetSourceContextInfo(sourceContext, nullptr);
- if (sourceContextInfo == nullptr)
- {
- sourceContextInfo = scriptContext->CreateSourceContextInfo(sourceContext, sourceUrl,
- wcslen(sourceUrl), nullptr);
- }
- SRCINFO si = {
- /* sourceContextInfo */ sourceContextInfo,
- /* dlnHost */ 0,
- /* ulColumnHost */ 0,
- /* lnMinHost */ 0,
- /* ichMinHost */ 0,
- /* ichLimHost */ 0, // xplat-todo: need to compute this?
- /* ulCharOffset */ 0,
- /* mod */ kmodGlobal,
- /* grfsi */ 0
- };
- uint32 flags = 0;
- if (CONFIG_FLAG(CreateFunctionProxy) && !scriptContext->IsProfiling())
- {
- flags = fscrAllowFunctionProxy;
- }
- hsi = scriptContext->AddHostSrcInfo(&si);
- hr = Js::ByteCodeSerializer::DeserializeFromBuffer(scriptContext, flags, sourceHolder,
- hsi, buffer, nullptr, &functionBody);
- if (FAILED(hr))
- {
- return JsErrorBadSerializedScript;
- }
- function = scriptContext->GetLibrary()->CreateScriptFunction(functionBody);
- JsrtContext * context = JsrtContext::GetCurrent();
- context->OnScriptLoad(function, functionBody->GetUtf8SourceInfo(), nullptr);
- return JsNoError;
- });
- if (errorCode != JsNoError)
- {
- return errorCode;
- }
- return ContextAPIWrapper_NoRecord<false>([&](Js::ScriptContext* scriptContext) -> JsErrorCode {
- if (parseOnly)
- {
- PARAM_NOT_NULL(result);
- *result = function;
- }
- else
- {
- Js::Var varResult = function->CallRootFunction(Js::Arguments(0, nullptr), scriptContext, true);
- if (result != nullptr)
- {
- *result = varResult;
- }
- }
- return JsNoError;
- });
- }
- static void CHAKRA_CALLBACK DummyScriptUnloadCallback(_In_ JsSourceContext sourceContext)
- {
- // Do nothing
- }
- #ifdef _WIN32
- static bool CHAKRA_CALLBACK DummyScriptLoadSourceCallback(_In_ JsSourceContext sourceContext, _Outptr_result_z_ const wchar_t** scriptBuffer)
- {
- // sourceContext is actually the script source pointer
- *scriptBuffer = reinterpret_cast<const wchar_t*>(sourceContext);
- return true;
- }
- CHAKRA_API JsParseSerializedScript(_In_z_ const wchar_t * script, _In_ unsigned char *buffer,
- _In_ JsSourceContext sourceContext,
- _In_z_ const wchar_t *sourceUrl,
- _Out_ JsValueRef * result)
- {
- return RunSerializedScriptCore(
- DummyScriptLoadSourceCallback, DummyScriptUnloadCallback,
- reinterpret_cast<JsSourceContext>(script), // use script source pointer as scriptLoadSourceContext
- buffer, nullptr, sourceContext, sourceUrl, true, result);
- }
- CHAKRA_API JsRunSerializedScript(_In_z_ const wchar_t * script, _In_ unsigned char *buffer,
- _In_ JsSourceContext sourceContext,
- _In_z_ const wchar_t *sourceUrl,
- _Out_ JsValueRef * result)
- {
- return RunSerializedScriptCore(
- DummyScriptLoadSourceCallback, DummyScriptUnloadCallback,
- reinterpret_cast<JsSourceContext>(script), // use script source pointer as scriptLoadSourceContext
- buffer, nullptr, sourceContext, sourceUrl, false, result);
- }
- CHAKRA_API JsParseSerializedScriptWithCallback(_In_ JsSerializedScriptLoadSourceCallback scriptLoadCallback,
- _In_ JsSerializedScriptUnloadCallback scriptUnloadCallback,
- _In_ unsigned char *buffer, _In_ JsSourceContext sourceContext,
- _In_z_ const wchar_t *sourceUrl, _Out_ JsValueRef * result)
- {
- return RunSerializedScriptCore(
- scriptLoadCallback, scriptUnloadCallback,
- sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
- buffer, nullptr, sourceContext, sourceUrl, true, result);
- }
- CHAKRA_API JsRunSerializedScriptWithCallback(_In_ JsSerializedScriptLoadSourceCallback scriptLoadCallback,
- _In_ JsSerializedScriptUnloadCallback scriptUnloadCallback,
- _In_ unsigned char *buffer, _In_ JsSourceContext sourceContext,
- _In_z_ const wchar_t *sourceUrl, _Out_opt_ JsValueRef * result)
- {
- return RunSerializedScriptCore(
- scriptLoadCallback, scriptUnloadCallback,
- sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
- buffer, nullptr, sourceContext, sourceUrl, false, result);
- }
- #endif // _WIN32
- /////////////////////
- CHAKRA_API JsTTDCreateRecordRuntime(_In_ JsRuntimeAttributes attributes, _In_reads_(infoUriCount) const byte* infoUri, _In_ size_t infoUriCount, _In_ size_t snapInterval, _In_ size_t snapHistoryLength,
- _In_ JsTTDInitializeForWriteLogStreamCallback writeInitializeFunction, _In_ TTDOpenResourceStreamCallback openResourceStream,
- _In_ JsTTDReadBytesFromStreamCallback readBytesFromStream, _In_ JsTTDWriteBytesToStreamCallback writeBytesToStream, _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
- _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtime)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- if(snapInterval > UINT32_MAX || snapHistoryLength > UINT32_MAX)
- {
- return JsErrorInvalidArgument;
- }
- return CreateRuntimeCore(attributes, infoUri, infoUriCount, true, false, false, (uint32)snapInterval, (uint32)snapHistoryLength,
- writeInitializeFunction, openResourceStream, readBytesFromStream, writeBytesToStream, flushAndCloseStream,
- threadService, runtime);
- #endif
- }
- CHAKRA_API JsTTDCreateReplayRuntime(_In_ JsRuntimeAttributes attributes, _In_reads_(infoUriCount) const byte* infoUri, _In_ size_t infoUriCount, _In_ bool enableDebugging,
- _In_ JsTTDInitializeForWriteLogStreamCallback writeInitializeFunction, _In_ TTDOpenResourceStreamCallback openResourceStream,
- _In_ JsTTDReadBytesFromStreamCallback readBytesFromStream, _In_ JsTTDWriteBytesToStreamCallback writeBytesToStream, _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
- _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtime)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- return CreateRuntimeCore(attributes, infoUri, infoUriCount, false, true, enableDebugging, UINT_MAX, UINT_MAX,
- writeInitializeFunction, openResourceStream, readBytesFromStream, writeBytesToStream, flushAndCloseStream,
- threadService, runtime);
- #endif
- }
- CHAKRA_API JsTTDCreateContext(_In_ JsRuntimeHandle runtimeHandle, _In_ bool useRuntimeTTDMode, _Out_ JsContextRef *newContext)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- PARAM_NOT_NULL(newContext);
- VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
- JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext * threadContext = runtime->GetThreadContext();
- TTDAssert(threadContext->IsRuntimeInTTDMode(), "Need to create in TTD Mode.");
- bool inRecord = false;
- bool activelyRecording = false;
- bool inReplay = false;
- TTDRecorder dummyActionEntryPopper;
- if(useRuntimeTTDMode)
- {
- threadContext->TTDLog->GetModesForExplicitContextCreate(inRecord, activelyRecording, inReplay);
- }
- return CreateContextCore(runtimeHandle, dummyActionEntryPopper, inRecord, activelyRecording, inReplay, newContext);
- });
- #endif
- }
- CHAKRA_API JsTTDNotifyContextDestroy(_In_ JsContextRef context)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
- if(threadContext->IsRuntimeInTTDMode())
- {
- Js::ScriptContext* ctx = static_cast<JsrtContext*>(context)->GetScriptContext();
- threadContext->TTDContext->NotifyCtxDestroyInRecord(ctx);
- }
- return JsNoError;
- #endif
- }
- CHAKRA_API JsTTDStart()
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- JsErrorCode cCheck = CheckContext(currentContext, true);
- TTDAssert(cCheck == JsNoError, "Must have valid context when starting TTD.");
- Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
- TTDAssert(scriptContext->IsTTDRecordOrReplayModeEnabled(), "Need to create in TTD Record Mode.");
- TTDAssert(JITManager::GetJITManager() == nullptr || !JITManager::GetJITManager()->IsOOPJITEnabled(), "TTD cannot run with OOP JIT yet!!!");
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
- {
- if(scriptContext->IsTTDRecordModeEnabled())
- {
- scriptContext->GetThreadContext()->TTDLog->DoSnapshotExtract();
- }
- //Want to verify that we are at top-level of dispatch
- scriptContext->GetThreadContext()->TTDLog->PushMode(TTD::TTDMode::CurrentlyEnabled);
- return JsNoError;
- });
- #endif
- }
- CHAKRA_API JsTTDStop()
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- JsErrorCode cCheck = CheckContext(currentContext, true);
- TTDAssert(cCheck == JsNoError, "Must have valid context when starting TTD.");
- Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
- TTDAssert(scriptContext->IsTTDRecordOrReplayModeEnabled(), "Need to create in TTD mode.");
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
- {
- scriptContext->GetThreadContext()->TTDLog->PopMode(TTD::TTDMode::CurrentlyEnabled);
- if(scriptContext->IsTTDRecordModeEnabled())
- {
- scriptContext->GetThreadContext()->TTDLog->UnloadAllLogData();
- }
- return JsNoError;
- });
- #endif
- }
- CHAKRA_API JsTTDEmitRecording()
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- JsErrorCode cCheck = CheckContext(currentContext, true);
- TTDAssert(cCheck == JsNoError, "Must have valid context when starting TTD.");
- Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
- TTDAssert(scriptContext->ShouldPerformRecordAction(), "Need to be running in TTD mode.");
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
- {
- scriptContext->GetThreadContext()->TTDLog->EmitLog();
- return JsNoError;
- });
- #endif
- }
- CHAKRA_API JsTTDPauseTimeTravelBeforeRuntimeOperation()
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- JsErrorCode cCheck = CheckContext(currentContext, true);
- TTDAssert(cCheck == JsNoError, "Must have valid context when changing debugger mode.");
- Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
- ThreadContext* threadContext = scriptContext->GetThreadContext();
- if(threadContext->IsRuntimeInTTDMode())
- {
- threadContext->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionDebuggerAction);
- }
- return JsNoError;
- #endif
- }
- CHAKRA_API JsTTDReStartTimeTravelAfterRuntimeOperation()
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- JsErrorCode cCheck = CheckContext(currentContext, true);
- TTDAssert(cCheck == JsNoError, "Must have valid context when changing debugger mode.");
- Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
- ThreadContext* threadContext = scriptContext->GetThreadContext();
- if(threadContext->IsRuntimeInTTDMode())
- {
- threadContext->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionDebuggerAction);
- }
- return JsNoError;
- #endif
- }
- CHAKRA_API JsTTDNotifyYield()
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- JsErrorCode cCheck = CheckContext(currentContext, true);
- if(cCheck != JsNoError)
- {
- return JsNoError; //we are ok just aren't going to do any TTD related work
- }
- Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
- {
- if(scriptContext->IsTTDRecordModeEnabled())
- {
- JsUtil::List<TTD::DeadScriptLogTagInfo, HeapAllocator>& deadScripts = scriptContext->GetThreadContext()->TTDContext->GetTTDDeadContextsForRecord();
- if(scriptContext->ShouldPerformRecordAction())
- {
- for(int32 i = 0; i < deadScripts.Count(); ++i)
- {
- const TTD::DeadScriptLogTagInfo& deadCtx = deadScripts.Item(i);
- scriptContext->GetThreadContext()->TTDLog->RecordJsRTDeadScriptEvent(deadCtx);
- }
- }
- deadScripts.Clear();
- }
- if(scriptContext->IsTTDRecordModeEnabled())
- {
- scriptContext->GetThreadContext()->TTDLog->RecordJsRTEventLoopYieldPoint();
- }
- return JsNoError;
- });
- #endif
- }
- CHAKRA_API JsTTDHostExit(_In_ int statusCode)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTHostExitProcess, statusCode);
- return JsNoError;
- });
- #endif
- }
- CHAKRA_API JsTTDRawBufferCopySyncIndirect(_In_ JsValueRef dst, _In_ size_t dstIndex, _In_ JsValueRef src, _In_ size_t srcIndex, _In_ size_t count)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- if(dstIndex > UINT32_MAX || srcIndex > UINT32_MAX || count > UINT32_MAX)
- {
- return JsErrorInvalidArgument;
- }
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferCopySync, dst, (uint32)dstIndex, src, (uint32)srcIndex, (uint32)count);
- return JsNoError;
- });
- #endif
- }
- CHAKRA_API JsTTDRawBufferModifySyncIndirect(_In_ JsValueRef buffer, _In_ size_t index, _In_ size_t count)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- if(index > UINT32_MAX || count > UINT32_MAX)
- {
- return JsErrorInvalidArgument;
- }
- return ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferModifySync, buffer, (uint32)index, (uint32)count);
- return JsNoError;
- });
- #endif
- }
- CHAKRA_API JsTTDRawBufferAsyncModificationRegister(_In_ JsValueRef instance, _In_ byte* initialModPos)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsValueRef addRefObj = nullptr;
- JsErrorCode addRefResult = ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- if (scriptContext->IsTTDRecordModeEnabled())
- {
- TTDAssert(Js::ArrayBuffer::Is(instance), "Not array buffer object!!!");
- Js::ArrayBuffer* dstBuff = Js::ArrayBuffer::FromVar(instance);
- addRefObj = dstBuff;
- TTDAssert(dstBuff->GetBuffer() <= initialModPos && initialModPos < dstBuff->GetBuffer() + dstBuff->GetByteLength(), "Not array buffer object!!!");
- TTDAssert(initialModPos - dstBuff->GetBuffer() < UINT32_MAX, "This is really big!!!");
- ptrdiff_t index = initialModPos - Js::ArrayBuffer::FromVar(instance)->GetBuffer();
- scriptContext->TTDContextInfo->AddToAsyncPendingList(dstBuff, (uint32)index);
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferAsyncModificationRegister, instance, (uint32)index);
- }
- return JsNoError;
- });
- if(addRefResult != JsNoError)
- {
- return addRefResult;
- }
- //We need to root add ref so we can find this during replay!!!
- if(addRefObj == nullptr)
- {
- return JsNoError;
- }
- else
- {
- return JsAddRef(addRefObj, nullptr);
- }
- #endif
- }
- CHAKRA_API JsTTDRawBufferAsyncModifyComplete(_In_ byte* finalModPos)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsValueRef releaseObj = nullptr;
- JsErrorCode releaseStatus = ContextAPIWrapper<true>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
- if (scriptContext->IsTTDRecordModeEnabled())
- {
- TTD::TTDPendingAsyncBufferModification pendingAsyncInfo = { 0 };
- scriptContext->TTDContextInfo->GetFromAsyncPendingList(&pendingAsyncInfo, finalModPos);
- Js::ArrayBuffer* dstBuff = Js::ArrayBuffer::FromVar(pendingAsyncInfo.ArrayBufferVar);
- releaseObj = dstBuff;
- PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferAsyncModifyComplete, pendingAsyncInfo, finalModPos);
- }
- return JsNoError;
- });
- if(releaseStatus != JsNoError)
- {
- return releaseStatus;
- }
- //We need to root release ref so we can free this in replay if needed!!!
- if(releaseObj == nullptr)
- {
- return JsNoError;
- }
- else
- {
- return JsRelease(releaseObj, nullptr);
- }
- #endif
- }
- CHAKRA_API JsTTDCheckAndAssertIfTTDRunning(_In_ const char* msg)
- {
- #if ENABLE_TTD
- JsrtContext* context = JsrtContext::GetCurrent();
- TTDAssert(context == nullptr || !context->GetScriptContext()->ShouldPerformRecordAction(), msg);
- #endif
- return JsNoError;
- }
- CHAKRA_API JsTTDGetSnapTimeTopLevelEventMove(_In_ JsRuntimeHandle runtimeHandle,
- _In_ JsTTDMoveMode moveMode, _In_opt_ uint32_t kthEvent,
- _Inout_ int64_t* targetEventTime, _Out_ int64_t* targetStartSnapTime,
- _Out_opt_ int64_t* targetEndSnapTime)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext* threadContext = runtime->GetThreadContext();
- *targetStartSnapTime = -1;
- if(targetEndSnapTime != nullptr)
- {
- *targetEndSnapTime = -1;
- }
- TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
- //If we requested a move to a specific event then extract the event count and try to find it
- if((moveMode & JsTTDMoveMode::JsTTDMoveFirstEvent) == JsTTDMoveMode::JsTTDMoveFirstEvent)
- {
- *targetEventTime = threadContext->TTDLog->GetFirstEventTimeInLog();
- if(*targetEventTime == -1)
- {
- return JsErrorCategoryUsage;
- }
- }
- else if((moveMode & JsTTDMoveMode::JsTTDMoveLastEvent) == JsTTDMoveMode::JsTTDMoveLastEvent)
- {
- *targetEventTime = threadContext->TTDLog->GetLastEventTimeInLog();
- if(*targetEventTime == -1)
- {
- return JsErrorCategoryUsage;
- }
- }
- else if((moveMode & JsTTDMoveMode::JsTTDMoveKthEvent) == JsTTDMoveMode::JsTTDMoveKthEvent)
- {
- *targetEventTime = threadContext->TTDLog->GetKthEventTimeInLog(kthEvent);
- if(*targetEventTime == -1)
- {
- return JsErrorCategoryUsage;
- }
- }
- else
- {
- ;
- }
- #ifdef __APPLE__
- //TODO: Explicit cast of ptr since compiler gets confused -- resolve in PAL later
- static_assert(sizeof(int64_t) == sizeof(int64));
- *targetStartSnapTime = threadContext->TTDLog->FindSnapTimeForEventTime(*targetEventTime, (int64*)targetEndSnapTime);
- #else
- *targetStartSnapTime = threadContext->TTDLog->FindSnapTimeForEventTime(*targetEventTime, targetEndSnapTime);
- #endif
- return JsNoError;
- #endif
- }
- CHAKRA_API JsTTDGetSnapShotBoundInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t targetEventTime, _Out_ int64_t* startSnapTime, _Out_ int64_t* endSnapTime)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext* threadContext = runtime->GetThreadContext();
- TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
- #ifdef __APPLE__
- //TODO: Explicit cast of ptr since compiler gets confused -- resolve in PAL later
- static_assert(sizeof(int64_t) == sizeof(int64));
- threadContext->TTDLog->GetSnapShotBoundInterval(targetEventTime, (int64*)startSnapTime, (int64*)endSnapTime);
- #else
- threadContext->TTDLog->GetSnapShotBoundInterval(targetEventTime, startSnapTime, endSnapTime);
- #endif
- return JsNoError;
- #endif
- }
- CHAKRA_API JsTTDGetPreviousSnapshotInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t currentSnapStartTime, _Out_ int64_t* previousSnapTime)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext * threadContext = runtime->GetThreadContext();
- TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
- *previousSnapTime = threadContext->TTDLog->GetPreviousSnapshotInterval(currentSnapStartTime);
- return JsNoError;
- #endif
- }
- #if ENABLE_TTD
- //Helper method for resetting breakpoint info around snapshot inflate
- JsErrorCode TTDHandleBreakpointInfoAndInflate(TTD::EventLog* elog, int64_t snapTime, JsrtRuntime* runtime, ThreadContext* threadContext)
- {
- return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
- {
- elog->LoadPreservedBPInfo();
- elog->DoSnapshotInflate(snapTime);
- if(elog->GetPerservedBPInfoCount() != 0)
- {
- JsrtDebugManager* jsrtDebugManager = runtime->GetJsrtDebugManager();
- TTD_LOG_PTR_ID* ctxIdList = elog->GetPerservedBPInfoScriptArray();
- TTD::TTDebuggerSourceLocation** locationList = elog->GetPerservedBPInfoLocationArray();
- for(uint32 i = 0; i < elog->GetPerservedBPInfoCount(); ++i)
- {
- const TTD::TTDebuggerSourceLocation* bpLocation = locationList[i];
- Js::ScriptContext* bpContext = threadContext->TTDContext->LookupContextForScriptId(ctxIdList[i]);
- if(bpContext != nullptr)
- {
- Js::FunctionBody* body = bpLocation->ResolveAssociatedSourceInfo(bpContext);
- Js::Utf8SourceInfo* utf8SourceInfo = body->GetUtf8SourceInfo();
- bool isNewBP = false;
- jsrtDebugManager->SetBreakpointHelper_TTD(bpContext, utf8SourceInfo, bpLocation->GetLine(), bpLocation->GetColumn(), &isNewBP);
- }
- }
- }
- elog->UnLoadPreservedBPInfo();
- return JsNoError;
- });
- }
- #endif
- CHAKRA_API JsTTDPreExecuteSnapShotInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t startSnapTime, _In_ int64_t endSnapTime, _In_ JsTTDMoveMode moveMode, _Out_ int64_t* newTargetEventTime)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- *newTargetEventTime = -1;
- JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext* threadContext = runtime->GetThreadContext();
- TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
- TTD::EventLog* elog = threadContext->TTDLog;
- JsErrorCode res = JsNoError;
- JsErrorCode inflateStatus = TTDHandleBreakpointInfoAndInflate(elog, startSnapTime, runtime, threadContext);
- if(inflateStatus != JsNoError)
- {
- return inflateStatus;
- }
- elog->ClearBPScanInfo();
- elog->PushMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
- elog->PushMode(TTD::TTDMode::DebuggerLogBreakpoints);
- try
- {
- if(endSnapTime == -1)
- {
- elog->ReplayRootEventsToTime(TTD_EVENT_MAXTIME);
- }
- else
- {
- elog->ReplayRootEventsToTime(endSnapTime);
- }
- }
- catch(TTD::TTDebuggerAbortException abortException)
- {
- //If we hit the end of the log or we hit a terminal exception that is fine -- anything else is a problem
- if(!abortException.IsEndOfLog() && !abortException.IsTopLevelException())
- {
- res = JsErrorFatal;
- }
- }
- catch(...) //we are replaying something that should be known to execute successfully so encountering any error is very bad
- {
- res = JsErrorFatal;
- TTDAssert(false, "Unexpected fatal Error");
- }
- elog->PopMode(TTD::TTDMode::DebuggerLogBreakpoints);
- elog->PopMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
- if((moveMode & JsTTDMoveMode::JsTTDMoveScanIntervalForContinue) == JsTTDMoveMode::JsTTDMoveScanIntervalForContinue)
- {
- bool bpFound = elog->TryFindAndSetPreviousBP();
- if(bpFound)
- {
- *newTargetEventTime = elog->GetPendingTTDBPTargetEventTime();
- }
- }
- elog->ClearBPScanInfo();
- return res;
- #endif
- }
- CHAKRA_API JsTTDMoveToTopLevelEvent(_In_ JsRuntimeHandle runtimeHandle, _In_ JsTTDMoveMode moveMode, _In_ int64_t snapshotTime, _In_ int64_t eventTime)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
- ThreadContext* threadContext = runtime->GetThreadContext();
- TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
- TTD::EventLog* elog = threadContext->TTDLog;
- JsErrorCode res = JsNoError;
- JsErrorCode inflateStatus = TTDHandleBreakpointInfoAndInflate(elog, snapshotTime, runtime, threadContext);
- if(inflateStatus != JsNoError)
- {
- return inflateStatus;
- }
- elog->PushMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
- try
- {
- elog->ReplayRootEventsToTime(eventTime);
- elog->DoRtrSnapIfNeeded();
- }
- catch(...) //we are replaying something that should be known to execute successfully so encountering any error is very bad
- {
- res = JsErrorFatal;
- TTDAssert(false, "Unexpected fatal Error");
- }
- elog->PopMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
- return res;
- #endif
- }
- CHAKRA_API JsTTDReplayExecution(_Inout_ JsTTDMoveMode* moveMode, _Out_ int64_t* rootEventTime)
- {
- #if !ENABLE_TTD
- return JsErrorCategoryUsage;
- #else
- JsrtContext *currentContext = JsrtContext::GetCurrent();
- JsErrorCode cCheck = CheckContext(currentContext, true);
- TTDAssert(cCheck == JsNoError, "This shouldn't happen!!!");
- Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
- ThreadContext* threadContext = scriptContext->GetThreadContext();
- TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
- TTD::EventLog* elog = threadContext->TTDLog;
- if((*moveMode & JsTTDMoveMode::JsTTDMoveBreakOnEntry) == JsTTDMoveMode::JsTTDMoveBreakOnEntry)
- {
- elog->SetBreakOnFirstUserCode();
- }
- //reset any breakpoints that we preserved accross a TTD move
- if(elog->HasPendingTTDBP())
- {
- GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- JsrtDebugManager* jsrtDebugManager = currentContext->GetRuntime()->GetJsrtDebugManager();
- //If the log has a BP requested then we should set the actual bp here
- if(elog->HasPendingTTDBP())
- {
- TTD::TTDebuggerSourceLocation bpLocation;
- elog->GetPendingTTDBPInfo(bpLocation);
- Js::FunctionBody* body = bpLocation.ResolveAssociatedSourceInfo(scriptContext);
- Js::Utf8SourceInfo* utf8SourceInfo = body->GetUtf8SourceInfo();
- bool isNewBP = false;
- Js::BreakpointProbe* probe = jsrtDebugManager->SetBreakpointHelper_TTD(scriptContext, utf8SourceInfo, bpLocation.GetLine(), bpLocation.GetColumn(), &isNewBP);
- if(probe != nullptr)
- {
- elog->SetActiveBP(probe->GetId(), isNewBP, bpLocation);
- }
- //Finally clear the pending BP info so we don't get confused later
- elog->ClearPendingTTDBPInfo();
- }
- return JsNoError;
- });
- }
- *moveMode = JsTTDMoveMode::JsTTDMoveNone;
- *rootEventTime = -1;
- JsErrorCode res = JsNoError;
- try
- {
- elog->ReplayRootEventsToTime(TTD_EVENT_MAXTIME);
- }
- catch(TTD::TTDebuggerAbortException abortException)
- {
- //if the debugger bails out with a move time request set info on the requested event time here
- //rest of breakpoint info should have been set by the debugger callback before aborting
- if (abortException.IsEventTimeMove() || abortException.IsTopLevelException())
- {
- *moveMode = (JsTTDMoveMode)abortException.GetMoveMode();
- *rootEventTime = abortException.GetTargetEventTime();
- if(abortException.IsTopLevelException())
- {
- TTD::TTDebuggerSourceLocation throwLocation;
- elog->GetLastExecutedTimeAndPositionForDebugger(throwLocation);
- elog->SetPendingTTDBPInfo(throwLocation);
- }
- }
- res = abortException.IsTopLevelException() ? JsErrorCategoryScript : JsNoError;
- }
- catch(...)
- {
- res = JsErrorFatal;
- TTDAssert(false, "Unexpected fatal Error");
- }
- return res;
- #endif
- }
- #ifndef NTBUILD // ChakraCore Only
- template <class SrcChar, class DstChar>
- static void CastCopy(const SrcChar* src, DstChar* dst, size_t count)
- {
- const SrcChar* end = src + count;
- while (src < end)
- {
- *dst++ = static_cast<DstChar>(*src++);
- }
- }
- CHAKRA_API JsCreateString(
- _In_ const char *content,
- _In_ size_t length,
- _Out_ JsValueRef *value)
- {
- PARAM_NOT_NULL(content);
- AutoArrayPtr<uint16_t> data(HeapNewNoThrowArray(uint16_t, length), length);
- if (!data)
- {
- return JsErrorOutOfMemory;
- }
- // Cast source char to "unsigned" for correct cast
- CastCopy((unsigned char*)content, (uint16_t*)data, length);
- return JsPointerToString(
- reinterpret_cast<const char16*>((uint16_t*)data), length, value);
- }
- CHAKRA_API JsCreateStringUtf8(
- _In_ const uint8_t *content,
- _In_ size_t length,
- _Out_ JsValueRef *value)
- {
- PARAM_NOT_NULL(content);
- utf8::NarrowToWide wstr((LPCSTR)content, length);
- if (!wstr)
- {
- return JsErrorOutOfMemory;
- }
- return JsPointerToString(wstr, wstr.Length(), value);
- }
- CHAKRA_API JsCreateStringUtf16(
- _In_ const uint16_t *content,
- _In_ size_t length,
- _Out_ JsValueRef *value)
- {
- PARAM_NOT_NULL(content);
- return JsPointerToString(
- reinterpret_cast<const char16*>(content), length, value);
- }
- template <class CopyFunc>
- JsErrorCode WriteStringCopy(
- JsValueRef value,
- int start,
- int length,
- _Out_opt_ size_t* written,
- const CopyFunc& copyFunc)
- {
- if (written)
- {
- *written = 0; // init to 0 for default
- }
- const char16* str = nullptr;
- size_t strLength = 0;
- JsErrorCode errorCode = JsStringToPointer(value, &str, &strLength);
- if (errorCode != JsNoError)
- {
- return errorCode;
- }
- if (start < 0 || (size_t)start > strLength)
- {
- return JsErrorInvalidArgument; // start out of range, no chars written
- }
- size_t count = min(static_cast<size_t>(length), strLength - start);
- if (count == 0)
- {
- return JsNoError; // no chars written
- }
- errorCode = copyFunc(str + start, count, written);
- if (errorCode != JsNoError)
- {
- return errorCode;
- }
- if (written)
- {
- *written = count;
- }
- return JsNoError;
- }
- CHAKRA_API JsCopyString(
- _In_ JsValueRef value,
- _In_ int start,
- _In_ int length,
- _Out_opt_ char* buffer,
- _Out_opt_ size_t* written)
- {
- PARAM_NOT_NULL(value);
- VALIDATE_JSREF(value);
- return WriteStringCopy(value, start, length, written,
- [buffer](const char16* src, size_t count, size_t *needed)
- {
- if (buffer)
- {
- CastCopy(src, buffer, count);
- }
- else
- {
- *needed = count;
- }
- return JsNoError;
- });
- }
- CHAKRA_API JsCopyStringUtf16(
- _In_ JsValueRef value,
- _In_ int start,
- _In_ int length,
- _Out_opt_ uint16_t* buffer,
- _Out_opt_ size_t* written)
- {
- PARAM_NOT_NULL(value);
- VALIDATE_JSREF(value);
- return WriteStringCopy(value, start, length, written,
- [buffer](const char16* src, size_t count, size_t *needed)
- {
- if (buffer)
- {
- memmove(buffer, src, sizeof(char16) * count);
- }
- else
- {
- *needed = count;
- }
- return JsNoError;
- });
- }
- CHAKRA_API JsCopyStringUtf8(
- _In_ JsValueRef value,
- _Out_opt_ uint8_t* buffer,
- _In_ size_t bufferSize,
- _Out_opt_ size_t* length)
- {
- PARAM_NOT_NULL(value);
- VALIDATE_JSREF(value);
- const char16* str = nullptr;
- size_t strLength = 0;
- JsErrorCode errorCode = JsStringToPointer(value, &str, &strLength);
- if (errorCode != JsNoError)
- {
- return errorCode;
- }
- utf8::WideToNarrow utf8Str(str, strLength);
- if (!buffer)
- {
- if (length)
- {
- *length = utf8Str.Length();
- }
- }
- else
- {
- size_t count = min(bufferSize, utf8Str.Length());
- // Try to copy whole characters if buffer size insufficient
- auto maxFitChars = utf8::ByteIndexIntoCharacterIndex(
- (LPCUTF8)(const char*)utf8Str, count,
- utf8::DecodeOptions::doChunkedEncoding);
- count = utf8::CharacterIndexToByteIndex(
- (LPCUTF8)(const char*)utf8Str, utf8Str.Length(), maxFitChars);
- memmove(buffer, utf8Str, sizeof(uint8_t) * count);
- if (length)
- {
- *length = count;
- }
- }
- return JsNoError;
- }
- _ALWAYSINLINE JsErrorCode CompileRun(
- JsValueRef scriptVal,
- JsSourceContext sourceContext,
- JsValueRef sourceUrl,
- JsParseScriptAttributes parseAttributes,
- _Out_ JsValueRef *result,
- bool parseOnly)
- {
- PARAM_NOT_NULL(scriptVal);
- VALIDATE_JSREF(scriptVal);
- PARAM_NOT_NULL(sourceUrl);
- bool isExternalArray = Js::ExternalArrayBuffer::Is(scriptVal),
- isString = false;
- bool isUtf8 = !(parseAttributes & JsParseScriptAttributeArrayBufferIsUtf16Encoded);
- LoadScriptFlag scriptFlag = LoadScriptFlag_None;
- const byte* script;
- size_t cb;
- const wchar_t *url;
- if (isExternalArray)
- {
- script = ((Js::ExternalArrayBuffer*)(scriptVal))->GetBuffer();
- cb = ((Js::ExternalArrayBuffer*)(scriptVal))->GetByteLength();
- scriptFlag = (LoadScriptFlag)(isUtf8 ?
- LoadScriptFlag_ExternalArrayBuffer | LoadScriptFlag_Utf8Source :
- LoadScriptFlag_ExternalArrayBuffer);
- }
- else
- {
- isString = Js::JavascriptString::Is(scriptVal);
- if (!isString)
- {
- return JsErrorInvalidArgument;
- }
- }
- JsErrorCode error = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
- if (isString)
- {
- Js::JavascriptString* jsString = Js::JavascriptString::FromVar(scriptVal);
- script = (const byte*)jsString->GetSz();
- // JavascriptString is 2 bytes (wchar_t/char16)
- cb = jsString->GetLength() * sizeof(wchar_t);
- }
- if (!Js::JavascriptString::Is(sourceUrl))
- {
- return JsErrorInvalidArgument;
- }
- url = Js::JavascriptString::FromVar(sourceUrl)->GetSz();
- return JsNoError;
- });
- if (error != JsNoError)
- {
- return error;
- }
- return RunScriptCore(scriptVal, script, cb, scriptFlag,
- sourceContext, url, parseOnly, parseAttributes, false, result);
- }
- CHAKRA_API JsParse(
- _In_ JsValueRef scriptVal,
- _In_ JsSourceContext sourceContext,
- _In_ JsValueRef sourceUrl,
- _In_ JsParseScriptAttributes parseAttributes,
- _Out_ JsValueRef *result)
- {
- return CompileRun(scriptVal, sourceContext, sourceUrl, parseAttributes,
- result, true);
- }
- CHAKRA_API JsRun(
- _In_ JsValueRef scriptVal,
- _In_ JsSourceContext sourceContext,
- _In_ JsValueRef sourceUrl,
- _In_ JsParseScriptAttributes parseAttributes,
- _Out_ JsValueRef *result)
- {
- return CompileRun(scriptVal, sourceContext, sourceUrl, parseAttributes,
- result, false);
- }
- CHAKRA_API JsCreatePropertyIdUtf8(
- _In_z_ const char *name,
- _In_ size_t length,
- _Out_ JsPropertyIdRef *propertyId)
- {
- PARAM_NOT_NULL(name);
- utf8::NarrowToWide wname(name, length);
- if (!wname)
- {
- return JsErrorOutOfMemory;
- }
- return JsGetPropertyIdFromName(wname, propertyId);
- }
- CHAKRA_API JsCopyPropertyIdUtf8(
- _In_ JsPropertyIdRef propertyId,
- _Out_ uint8_t* buffer,
- _In_ size_t bufferSize,
- _Out_ size_t* length)
- {
- PARAM_NOT_NULL(propertyId);
- const char16* str = nullptr;
- JsErrorCode errorCode = JsGetPropertyNameFromId(propertyId, &str);
- if (errorCode != JsNoError)
- {
- return errorCode;
- }
- utf8::WideToNarrow utf8Str(str);
- if (!buffer)
- {
- if (length)
- {
- *length = utf8Str.Length();
- }
- }
- else
- {
- size_t count = min(bufferSize, utf8Str.Length());
- // Try to copy whole characters if buffer size insufficient
- auto maxFitChars = utf8::ByteIndexIntoCharacterIndex(
- (LPCUTF8)(const char*)utf8Str, count,
- utf8::DecodeOptions::doChunkedEncoding);
- count = utf8::CharacterIndexToByteIndex(
- (LPCUTF8)(const char*)utf8Str, utf8Str.Length(), maxFitChars);
- memmove(buffer, utf8Str, sizeof(uint8_t) * count);
- if (length)
- {
- *length = count;
- }
- }
- return JsNoError;
- }
- CHAKRA_API JsSerialize(
- _In_ JsValueRef scriptVal,
- _Out_ JsValueRef *bufferVal,
- _In_ JsParseScriptAttributes parseAttributes)
- {
- PARAM_NOT_NULL(scriptVal);
- PARAM_NOT_NULL(bufferVal);
- VALIDATE_JSREF(scriptVal);
- *bufferVal = nullptr;
- bool isExternalArray = Js::ExternalArrayBuffer::Is(scriptVal),
- isString = false;
- bool isUtf8 = !(parseAttributes & JsParseScriptAttributeArrayBufferIsUtf16Encoded);
- if (!isExternalArray)
- {
- isString = Js::JavascriptString::Is(scriptVal);
- if (!isString)
- {
- return JsErrorInvalidArgument;
- }
- }
- LoadScriptFlag scriptFlag;
- const byte* script = isExternalArray ?
- ((Js::ExternalArrayBuffer*)(scriptVal))->GetBuffer() :
- (const byte*)((Js::JavascriptString*)(scriptVal))->GetSz();
- const size_t cb = isExternalArray ?
- ((Js::ExternalArrayBuffer*)(scriptVal))->GetByteLength() :
- ((Js::JavascriptString*)(scriptVal))->GetLength();
- if (isExternalArray && isUtf8)
- {
- scriptFlag = (LoadScriptFlag) (LoadScriptFlag_ExternalArrayBuffer | LoadScriptFlag_Utf8Source);
- }
- else if (isUtf8)
- {
- scriptFlag = (LoadScriptFlag) (LoadScriptFlag_Utf8Source);
- }
- else
- {
- scriptFlag = LoadScriptFlag_None;
- }
- unsigned int bufferSize = 0;
- JsErrorCode errorCode = JsSerializeScriptCore(script, cb, scriptFlag, nullptr,
- 0, nullptr, &bufferSize, scriptVal);
- if (errorCode != JsNoError)
- {
- return errorCode;
- }
- if (bufferSize == 0)
- {
- return JsErrorScriptCompile;
- }
- if ((errorCode = JsCreateArrayBuffer(bufferSize, bufferVal)) == JsNoError)
- {
- byte* buffer = ((Js::ArrayBuffer*)(*bufferVal))->GetBuffer();
- errorCode = JsSerializeScriptCore(script, cb, scriptFlag, nullptr,
- 0, buffer, &bufferSize, scriptVal);
- }
- return errorCode;
- }
- CHAKRA_API JsParseSerialized(
- _In_ JsValueRef bufferVal,
- _In_ JsSerializedLoadScriptCallback scriptLoadCallback,
- _In_ JsSourceContext sourceContext,
- _In_ JsValueRef sourceUrl,
- _Out_ JsValueRef *result)
- {
- PARAM_NOT_NULL(bufferVal);
- PARAM_NOT_NULL(sourceUrl);
- const wchar_t *url;
- if (Js::JavascriptString::Is(sourceUrl))
- {
- url = ((Js::JavascriptString*)(sourceUrl))->GetSz();
- }
- else
- {
- return JsErrorInvalidArgument;
- }
- // JsParseSerialized only accepts ArrayBuffer (incl. ExternalArrayBuffer)
- if (!Js::ExternalArrayBuffer::Is(bufferVal))
- {
- return JsErrorInvalidArgument;
- }
- byte* buffer = Js::ArrayBuffer::FromVar(bufferVal)->GetBuffer();
- return RunSerializedScriptCore(
- scriptLoadCallback, DummyScriptUnloadCallback,
- sourceContext,// use the same user provided sourceContext as scriptLoadSourceContext
- buffer, bufferVal, sourceContext, url, true, result);
- }
- CHAKRA_API JsRunSerialized(
- _In_ JsValueRef bufferVal,
- _In_ JsSerializedLoadScriptCallback scriptLoadCallback,
- _In_ JsSourceContext sourceContext,
- _In_ JsValueRef sourceUrl,
- _Out_ JsValueRef *result)
- {
- PARAM_NOT_NULL(bufferVal);
- const wchar_t *url;
- if (sourceUrl && Js::JavascriptString::Is(sourceUrl))
- {
- url = ((Js::JavascriptString*)(sourceUrl))->GetSz();
- }
- else
- {
- return JsErrorInvalidArgument;
- }
- // JsParseSerialized only accepts ArrayBuffer (incl. ExternalArrayBuffer)
- if (!Js::ExternalArrayBuffer::Is(bufferVal))
- {
- return JsErrorInvalidArgument;
- }
- byte* buffer = Js::ArrayBuffer::FromVar(bufferVal)->GetBuffer();
- return RunSerializedScriptCore(
- scriptLoadCallback, DummyScriptUnloadCallback,
- sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
- buffer, bufferVal, sourceContext, url, false, result);
- }
- #endif // NTBUILD
|