Jsrt.cpp 198 KB

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