2
0

Jsrt.cpp 191 KB

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