Jsrt.cpp 188 KB

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