Jsrt.cpp 191 KB

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