nan.h 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802
  1. /*********************************************************************
  2. * NAN - Native Abstractions for Node.js
  3. *
  4. * Copyright (c) 2018 NAN contributors:
  5. * - Rod Vagg <https://github.com/rvagg>
  6. * - Benjamin Byholm <https://github.com/kkoopa>
  7. * - Trevor Norris <https://github.com/trevnorris>
  8. * - Nathan Rajlich <https://github.com/TooTallNate>
  9. * - Brett Lawson <https://github.com/brett19>
  10. * - Ben Noordhuis <https://github.com/bnoordhuis>
  11. * - David Siegel <https://github.com/agnat>
  12. * - Michael Ira Krufky <https://github.com/mkrufky>
  13. *
  14. * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
  15. *
  16. * Version 2.11.1: current Node 10.11.0, Node 12: 0.12.18, Node 10: 0.10.48, iojs: 3.3.1
  17. *
  18. * See https://github.com/nodejs/nan for the latest update to this file
  19. **********************************************************************************/
  20. #ifndef NAN_H_
  21. #define NAN_H_
  22. #include <node_version.h>
  23. #define NODE_0_10_MODULE_VERSION 11
  24. #define NODE_0_12_MODULE_VERSION 14
  25. #define ATOM_0_21_MODULE_VERSION 41
  26. #define IOJS_1_0_MODULE_VERSION 42
  27. #define IOJS_1_1_MODULE_VERSION 43
  28. #define IOJS_2_0_MODULE_VERSION 44
  29. #define IOJS_3_0_MODULE_VERSION 45
  30. #define NODE_4_0_MODULE_VERSION 46
  31. #define NODE_5_0_MODULE_VERSION 47
  32. #define NODE_6_0_MODULE_VERSION 48
  33. #define NODE_7_0_MODULE_VERSION 51
  34. #define NODE_8_0_MODULE_VERSION 57
  35. #define NODE_9_0_MODULE_VERSION 59
  36. #define NODE_10_0_MODULE_VERSION 64
  37. #ifdef _MSC_VER
  38. # define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800)
  39. #else
  40. # define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L)
  41. #endif
  42. #if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11
  43. # error This version of node/NAN/v8 requires a C++11 compiler
  44. #endif
  45. #include <uv.h>
  46. #include <node.h>
  47. #include <node_buffer.h>
  48. #include <node_object_wrap.h>
  49. #include <algorithm>
  50. #include <cstring>
  51. #include <climits>
  52. #include <cstdlib>
  53. #include <utility>
  54. #if defined(_MSC_VER)
  55. # pragma warning( push )
  56. # pragma warning( disable : 4530 )
  57. # include <queue>
  58. # include <string>
  59. # include <vector>
  60. # pragma warning( pop )
  61. #else
  62. # include <queue>
  63. # include <string>
  64. # include <vector>
  65. #endif
  66. // uv helpers
  67. #ifdef UV_VERSION_MAJOR
  68. # ifndef UV_VERSION_PATCH
  69. # define UV_VERSION_PATCH 0
  70. # endif
  71. # define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \
  72. (UV_VERSION_MINOR << 8) | \
  73. (UV_VERSION_PATCH))
  74. #else
  75. # define NAUV_UVVERSION 0x000b00
  76. #endif
  77. #if NAUV_UVVERSION < 0x000b0b
  78. # ifdef WIN32
  79. # include <windows.h>
  80. # else
  81. # include <pthread.h>
  82. # endif
  83. #endif
  84. namespace Nan {
  85. #define NAN_CONCAT(a, b) NAN_CONCAT_HELPER(a, b)
  86. #define NAN_CONCAT_HELPER(a, b) a##b
  87. #define NAN_INLINE inline // TODO(bnoordhuis) Remove in v3.0.0.
  88. #if defined(__GNUC__) && \
  89. !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
  90. # define NAN_DEPRECATED __attribute__((deprecated))
  91. #elif defined(_MSC_VER) && \
  92. !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
  93. # define NAN_DEPRECATED __declspec(deprecated)
  94. #else
  95. # define NAN_DEPRECATED
  96. #endif
  97. #if NAN_HAS_CPLUSPLUS_11
  98. # define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete;
  99. # define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete;
  100. # define NAN_DISALLOW_MOVE(CLASS) \
  101. CLASS(CLASS&&) = delete; /* NOLINT(build/c++11) */ \
  102. void operator=(CLASS&&) = delete;
  103. #else
  104. # define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&);
  105. # define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&);
  106. # define NAN_DISALLOW_MOVE(CLASS)
  107. #endif
  108. #define NAN_DISALLOW_ASSIGN_COPY(CLASS) \
  109. NAN_DISALLOW_ASSIGN(CLASS) \
  110. NAN_DISALLOW_COPY(CLASS)
  111. #define NAN_DISALLOW_ASSIGN_MOVE(CLASS) \
  112. NAN_DISALLOW_ASSIGN(CLASS) \
  113. NAN_DISALLOW_MOVE(CLASS)
  114. #define NAN_DISALLOW_COPY_MOVE(CLASS) \
  115. NAN_DISALLOW_COPY(CLASS) \
  116. NAN_DISALLOW_MOVE(CLASS)
  117. #define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS) \
  118. NAN_DISALLOW_ASSIGN(CLASS) \
  119. NAN_DISALLOW_COPY(CLASS) \
  120. NAN_DISALLOW_MOVE(CLASS)
  121. #define TYPE_CHECK(T, S) \
  122. while (false) { \
  123. *(static_cast<T *volatile *>(0)) = static_cast<S*>(0); \
  124. }
  125. //=== RegistrationFunction =====================================================
  126. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  127. typedef v8::Handle<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
  128. #else
  129. typedef v8::Local<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
  130. #endif
  131. #define NAN_MODULE_INIT(name) \
  132. void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target)
  133. #if NODE_MAJOR_VERSION >= 10 || \
  134. NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3
  135. #define NAN_MODULE_WORKER_ENABLED(module_name, registration) \
  136. extern "C" NODE_MODULE_EXPORT void \
  137. NAN_CONCAT(node_register_module_v, NODE_MODULE_VERSION)( \
  138. v8::Local<v8::Object> exports, v8::Local<v8::Value> module, \
  139. v8::Local<v8::Context> context) \
  140. { \
  141. registration(exports); \
  142. }
  143. #else
  144. #define NAN_MODULE_WORKER_ENABLED(module_name, registration) \
  145. NODE_MODULE(module_name, registration)
  146. #endif
  147. //=== CallbackInfo =============================================================
  148. #include "nan_callbacks.h" // NOLINT(build/include)
  149. //==============================================================================
  150. #if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION)
  151. typedef v8::Script UnboundScript;
  152. typedef v8::Script BoundScript;
  153. #else
  154. typedef v8::UnboundScript UnboundScript;
  155. typedef v8::Script BoundScript;
  156. #endif
  157. #if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION)
  158. typedef v8::String::ExternalAsciiStringResource
  159. ExternalOneByteStringResource;
  160. #else
  161. typedef v8::String::ExternalOneByteStringResource
  162. ExternalOneByteStringResource;
  163. #endif
  164. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  165. template<typename T>
  166. class NonCopyablePersistentTraits :
  167. public v8::NonCopyablePersistentTraits<T> {};
  168. template<typename T>
  169. class CopyablePersistentTraits :
  170. public v8::CopyablePersistentTraits<T> {};
  171. template<typename T>
  172. class PersistentBase :
  173. public v8::PersistentBase<T> {};
  174. template<typename T, typename M = v8::NonCopyablePersistentTraits<T> >
  175. class Persistent;
  176. #else
  177. template<typename T> class NonCopyablePersistentTraits;
  178. template<typename T> class PersistentBase;
  179. template<typename T, typename P> class WeakCallbackData;
  180. template<typename T, typename M = NonCopyablePersistentTraits<T> >
  181. class Persistent;
  182. #endif // NODE_MODULE_VERSION
  183. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  184. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  185. # include "nan_maybe_43_inl.h" // NOLINT(build/include)
  186. #else
  187. # include "nan_maybe_pre_43_inl.h" // NOLINT(build/include)
  188. #endif
  189. #include "nan_converters.h" // NOLINT(build/include)
  190. #include "nan_new.h" // NOLINT(build/include)
  191. #if NAUV_UVVERSION < 0x000b17
  192. #define NAUV_WORK_CB(func) \
  193. void func(uv_async_t *async, int)
  194. #else
  195. #define NAUV_WORK_CB(func) \
  196. void func(uv_async_t *async)
  197. #endif
  198. #if NAUV_UVVERSION >= 0x000b0b
  199. typedef uv_key_t nauv_key_t;
  200. inline int nauv_key_create(nauv_key_t *key) {
  201. return uv_key_create(key);
  202. }
  203. inline void nauv_key_delete(nauv_key_t *key) {
  204. uv_key_delete(key);
  205. }
  206. inline void* nauv_key_get(nauv_key_t *key) {
  207. return uv_key_get(key);
  208. }
  209. inline void nauv_key_set(nauv_key_t *key, void *value) {
  210. uv_key_set(key, value);
  211. }
  212. #else
  213. /* Implement thread local storage for older versions of libuv.
  214. * This is essentially a backport of libuv commit 5d2434bf
  215. * written by Ben Noordhuis, adjusted for names and inline.
  216. */
  217. #ifndef WIN32
  218. typedef pthread_key_t nauv_key_t;
  219. inline int nauv_key_create(nauv_key_t* key) {
  220. return -pthread_key_create(key, NULL);
  221. }
  222. inline void nauv_key_delete(nauv_key_t* key) {
  223. if (pthread_key_delete(*key))
  224. abort();
  225. }
  226. inline void* nauv_key_get(nauv_key_t* key) {
  227. return pthread_getspecific(*key);
  228. }
  229. inline void nauv_key_set(nauv_key_t* key, void* value) {
  230. if (pthread_setspecific(*key, value))
  231. abort();
  232. }
  233. #else
  234. typedef struct {
  235. DWORD tls_index;
  236. } nauv_key_t;
  237. inline int nauv_key_create(nauv_key_t* key) {
  238. key->tls_index = TlsAlloc();
  239. if (key->tls_index == TLS_OUT_OF_INDEXES)
  240. return UV_ENOMEM;
  241. return 0;
  242. }
  243. inline void nauv_key_delete(nauv_key_t* key) {
  244. if (TlsFree(key->tls_index) == FALSE)
  245. abort();
  246. key->tls_index = TLS_OUT_OF_INDEXES;
  247. }
  248. inline void* nauv_key_get(nauv_key_t* key) {
  249. void* value = TlsGetValue(key->tls_index);
  250. if (value == NULL)
  251. if (GetLastError() != ERROR_SUCCESS)
  252. abort();
  253. return value;
  254. }
  255. inline void nauv_key_set(nauv_key_t* key, void* value) {
  256. if (TlsSetValue(key->tls_index, value) == FALSE)
  257. abort();
  258. }
  259. #endif
  260. #endif
  261. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  262. template<typename T>
  263. v8::Local<T> New(v8::Handle<T>);
  264. #endif
  265. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  266. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  267. typedef v8::WeakCallbackType WeakCallbackType;
  268. #else
  269. struct WeakCallbackType {
  270. enum E {kParameter, kInternalFields};
  271. E type;
  272. WeakCallbackType(E other) : type(other) {} // NOLINT(runtime/explicit)
  273. inline bool operator==(E other) { return other == this->type; }
  274. inline bool operator!=(E other) { return !operator==(other); }
  275. };
  276. #endif
  277. template<typename P> class WeakCallbackInfo;
  278. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  279. # include "nan_persistent_12_inl.h" // NOLINT(build/include)
  280. #else
  281. # include "nan_persistent_pre_12_inl.h" // NOLINT(build/include)
  282. #endif
  283. namespace imp {
  284. static const size_t kMaxLength = 0x3fffffff;
  285. // v8::String::REPLACE_INVALID_UTF8 was introduced
  286. // in node.js v0.10.29 and v0.8.27.
  287. #if NODE_MAJOR_VERSION > 0 || \
  288. NODE_MINOR_VERSION > 10 || \
  289. NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \
  290. NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27
  291. static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8;
  292. #else
  293. static const unsigned kReplaceInvalidUtf8 = 0;
  294. #endif
  295. } // end of namespace imp
  296. //=== HandleScope ==============================================================
  297. class HandleScope {
  298. v8::HandleScope scope;
  299. public:
  300. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  301. inline HandleScope() : scope(v8::Isolate::GetCurrent()) {}
  302. inline static int NumberOfHandles() {
  303. return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
  304. }
  305. #else
  306. inline HandleScope() : scope() {}
  307. inline static int NumberOfHandles() {
  308. return v8::HandleScope::NumberOfHandles();
  309. }
  310. #endif
  311. private:
  312. // Make it hard to create heap-allocated or illegal handle scopes by
  313. // disallowing certain operations.
  314. HandleScope(const HandleScope &);
  315. void operator=(const HandleScope &);
  316. void *operator new(size_t size);
  317. void operator delete(void *, size_t) {
  318. abort();
  319. }
  320. };
  321. class EscapableHandleScope {
  322. public:
  323. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  324. inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {}
  325. inline static int NumberOfHandles() {
  326. return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
  327. }
  328. template<typename T>
  329. inline v8::Local<T> Escape(v8::Local<T> value) {
  330. return scope.Escape(value);
  331. }
  332. private:
  333. v8::EscapableHandleScope scope;
  334. #else
  335. inline EscapableHandleScope() : scope() {}
  336. inline static int NumberOfHandles() {
  337. return v8::HandleScope::NumberOfHandles();
  338. }
  339. template<typename T>
  340. inline v8::Local<T> Escape(v8::Local<T> value) {
  341. return scope.Close(value);
  342. }
  343. private:
  344. v8::HandleScope scope;
  345. #endif
  346. private:
  347. // Make it hard to create heap-allocated or illegal handle scopes by
  348. // disallowing certain operations.
  349. EscapableHandleScope(const EscapableHandleScope &);
  350. void operator=(const EscapableHandleScope &);
  351. void *operator new(size_t size);
  352. void operator delete(void *, size_t) {
  353. abort();
  354. }
  355. };
  356. //=== TryCatch =================================================================
  357. class TryCatch {
  358. v8::TryCatch try_catch_;
  359. friend void FatalException(const TryCatch&);
  360. public:
  361. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  362. TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {}
  363. #endif
  364. inline bool HasCaught() const { return try_catch_.HasCaught(); }
  365. inline bool CanContinue() const { return try_catch_.CanContinue(); }
  366. inline v8::Local<v8::Value> ReThrow() {
  367. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  368. return New(try_catch_.ReThrow());
  369. #else
  370. return try_catch_.ReThrow();
  371. #endif
  372. }
  373. inline v8::Local<v8::Value> Exception() const {
  374. return try_catch_.Exception();
  375. }
  376. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  377. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  378. inline v8::MaybeLocal<v8::Value> StackTrace() const {
  379. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  380. v8::EscapableHandleScope scope(isolate);
  381. return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext())
  382. .FromMaybe(v8::Local<v8::Value>()));
  383. }
  384. #else
  385. inline MaybeLocal<v8::Value> StackTrace() const {
  386. return try_catch_.StackTrace();
  387. }
  388. #endif
  389. inline v8::Local<v8::Message> Message() const {
  390. return try_catch_.Message();
  391. }
  392. inline void Reset() { try_catch_.Reset(); }
  393. inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); }
  394. inline void SetCaptureMessage(bool value) {
  395. try_catch_.SetCaptureMessage(value);
  396. }
  397. };
  398. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  399. v8::Local<v8::Function> func,
  400. int argc,
  401. v8::Local<v8::Value>* argv);
  402. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  403. v8::Local<v8::String> symbol,
  404. int argc,
  405. v8::Local<v8::Value>* argv);
  406. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  407. const char* method,
  408. int argc,
  409. v8::Local<v8::Value>* argv);
  410. // === AsyncResource ===========================================================
  411. class AsyncResource {
  412. public:
  413. AsyncResource(
  414. v8::Local<v8::String> name
  415. , v8::Local<v8::Object> resource = New<v8::Object>()) {
  416. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  417. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  418. if (resource.IsEmpty()) {
  419. resource = New<v8::Object>();
  420. }
  421. context = node::EmitAsyncInit(isolate, resource, name);
  422. #endif
  423. }
  424. AsyncResource(
  425. const char* name
  426. , v8::Local<v8::Object> resource = New<v8::Object>()) {
  427. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  428. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  429. if (resource.IsEmpty()) {
  430. resource = New<v8::Object>();
  431. }
  432. v8::Local<v8::String> name_string =
  433. New<v8::String>(name).ToLocalChecked();
  434. context = node::EmitAsyncInit(isolate, resource, name_string);
  435. #endif
  436. }
  437. ~AsyncResource() {
  438. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  439. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  440. node::EmitAsyncDestroy(isolate, context);
  441. #endif
  442. }
  443. inline MaybeLocal<v8::Value> runInAsyncScope(
  444. v8::Local<v8::Object> target
  445. , v8::Local<v8::Function> func
  446. , int argc
  447. , v8::Local<v8::Value>* argv) {
  448. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  449. return MakeCallback(target, func, argc, argv);
  450. #else
  451. return node::MakeCallback(
  452. v8::Isolate::GetCurrent(), target, func, argc, argv, context);
  453. #endif
  454. }
  455. inline MaybeLocal<v8::Value> runInAsyncScope(
  456. v8::Local<v8::Object> target
  457. , v8::Local<v8::String> symbol
  458. , int argc
  459. , v8::Local<v8::Value>* argv) {
  460. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  461. return MakeCallback(target, symbol, argc, argv);
  462. #else
  463. return node::MakeCallback(
  464. v8::Isolate::GetCurrent(), target, symbol, argc, argv, context);
  465. #endif
  466. }
  467. inline MaybeLocal<v8::Value> runInAsyncScope(
  468. v8::Local<v8::Object> target
  469. , const char* method
  470. , int argc
  471. , v8::Local<v8::Value>* argv) {
  472. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  473. return MakeCallback(target, method, argc, argv);
  474. #else
  475. return node::MakeCallback(
  476. v8::Isolate::GetCurrent(), target, method, argc, argv, context);
  477. #endif
  478. }
  479. private:
  480. NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource)
  481. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  482. node::async_context context;
  483. #endif
  484. };
  485. inline uv_loop_t* GetCurrentEventLoop() {
  486. #if NODE_MAJOR_VERSION >= 10 || \
  487. NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 || \
  488. NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION >= 10
  489. return node::GetCurrentEventLoop(v8::Isolate::GetCurrent());
  490. #else
  491. return uv_default_loop();
  492. #endif
  493. }
  494. //============ =================================================================
  495. /* node 0.12 */
  496. #if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
  497. inline
  498. void SetCounterFunction(v8::CounterLookupCallback cb) {
  499. v8::Isolate::GetCurrent()->SetCounterFunction(cb);
  500. }
  501. inline
  502. void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
  503. v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb);
  504. }
  505. inline
  506. void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
  507. v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb);
  508. }
  509. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  510. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  511. inline bool IdleNotification(int idle_time_in_ms) {
  512. return v8::Isolate::GetCurrent()->IdleNotificationDeadline(
  513. idle_time_in_ms * 0.001);
  514. }
  515. # else
  516. inline bool IdleNotification(int idle_time_in_ms) {
  517. return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms);
  518. }
  519. #endif
  520. inline void LowMemoryNotification() {
  521. v8::Isolate::GetCurrent()->LowMemoryNotification();
  522. }
  523. inline void ContextDisposedNotification() {
  524. v8::Isolate::GetCurrent()->ContextDisposedNotification();
  525. }
  526. #else
  527. inline
  528. void SetCounterFunction(v8::CounterLookupCallback cb) {
  529. v8::V8::SetCounterFunction(cb);
  530. }
  531. inline
  532. void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
  533. v8::V8::SetCreateHistogramFunction(cb);
  534. }
  535. inline
  536. void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
  537. v8::V8::SetAddHistogramSampleFunction(cb);
  538. }
  539. inline bool IdleNotification(int idle_time_in_ms) {
  540. return v8::V8::IdleNotification(idle_time_in_ms);
  541. }
  542. inline void LowMemoryNotification() {
  543. v8::V8::LowMemoryNotification();
  544. }
  545. inline void ContextDisposedNotification() {
  546. v8::V8::ContextDisposedNotification();
  547. }
  548. #endif
  549. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) // Node 0.12
  550. inline v8::Local<v8::Primitive> Undefined() {
  551. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  552. EscapableHandleScope scope;
  553. return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent())));
  554. # else
  555. return v8::Undefined(v8::Isolate::GetCurrent());
  556. # endif
  557. }
  558. inline v8::Local<v8::Primitive> Null() {
  559. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  560. EscapableHandleScope scope;
  561. return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent())));
  562. # else
  563. return v8::Null(v8::Isolate::GetCurrent());
  564. # endif
  565. }
  566. inline v8::Local<v8::Boolean> True() {
  567. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  568. EscapableHandleScope scope;
  569. return scope.Escape(New(v8::True(v8::Isolate::GetCurrent())));
  570. # else
  571. return v8::True(v8::Isolate::GetCurrent());
  572. # endif
  573. }
  574. inline v8::Local<v8::Boolean> False() {
  575. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  576. EscapableHandleScope scope;
  577. return scope.Escape(New(v8::False(v8::Isolate::GetCurrent())));
  578. # else
  579. return v8::False(v8::Isolate::GetCurrent());
  580. # endif
  581. }
  582. inline v8::Local<v8::String> EmptyString() {
  583. return v8::String::Empty(v8::Isolate::GetCurrent());
  584. }
  585. inline int AdjustExternalMemory(int bc) {
  586. return static_cast<int>(
  587. v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc));
  588. }
  589. inline void SetTemplate(
  590. v8::Local<v8::Template> templ
  591. , const char *name
  592. , v8::Local<v8::Data> value) {
  593. templ->Set(v8::Isolate::GetCurrent(), name, value);
  594. }
  595. inline void SetTemplate(
  596. v8::Local<v8::Template> templ
  597. , v8::Local<v8::String> name
  598. , v8::Local<v8::Data> value
  599. , v8::PropertyAttribute attributes) {
  600. templ->Set(name, value, attributes);
  601. }
  602. inline v8::Local<v8::Context> GetCurrentContext() {
  603. return v8::Isolate::GetCurrent()->GetCurrentContext();
  604. }
  605. inline void* GetInternalFieldPointer(
  606. v8::Local<v8::Object> object
  607. , int index) {
  608. return object->GetAlignedPointerFromInternalField(index);
  609. }
  610. inline void SetInternalFieldPointer(
  611. v8::Local<v8::Object> object
  612. , int index
  613. , void* value) {
  614. object->SetAlignedPointerInInternalField(index, value);
  615. }
  616. # define NAN_GC_CALLBACK(name) \
  617. void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags)
  618. #if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION
  619. typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback;
  620. typedef v8::Isolate::GCPrologueCallback GCPrologueCallback;
  621. #else
  622. typedef v8::Isolate::GCCallback GCEpilogueCallback;
  623. typedef v8::Isolate::GCCallback GCPrologueCallback;
  624. #endif
  625. inline void AddGCEpilogueCallback(
  626. GCEpilogueCallback callback
  627. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  628. v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter);
  629. }
  630. inline void RemoveGCEpilogueCallback(
  631. GCEpilogueCallback callback) {
  632. v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback);
  633. }
  634. inline void AddGCPrologueCallback(
  635. GCPrologueCallback callback
  636. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  637. v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter);
  638. }
  639. inline void RemoveGCPrologueCallback(
  640. GCPrologueCallback callback) {
  641. v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback);
  642. }
  643. inline void GetHeapStatistics(
  644. v8::HeapStatistics *heap_statistics) {
  645. v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics);
  646. }
  647. # define X(NAME) \
  648. inline v8::Local<v8::Value> NAME(const char *msg) { \
  649. EscapableHandleScope scope; \
  650. return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  651. } \
  652. \
  653. inline \
  654. v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \
  655. return v8::Exception::NAME(msg); \
  656. } \
  657. \
  658. inline void Throw ## NAME(const char *msg) { \
  659. HandleScope scope; \
  660. v8::Isolate::GetCurrent()->ThrowException( \
  661. v8::Exception::NAME(New(msg).ToLocalChecked())); \
  662. } \
  663. \
  664. inline void Throw ## NAME(v8::Local<v8::String> msg) { \
  665. HandleScope scope; \
  666. v8::Isolate::GetCurrent()->ThrowException( \
  667. v8::Exception::NAME(msg)); \
  668. }
  669. X(Error)
  670. X(RangeError)
  671. X(ReferenceError)
  672. X(SyntaxError)
  673. X(TypeError)
  674. # undef X
  675. inline void ThrowError(v8::Local<v8::Value> error) {
  676. v8::Isolate::GetCurrent()->ThrowException(error);
  677. }
  678. inline MaybeLocal<v8::Object> NewBuffer(
  679. char *data
  680. , size_t length
  681. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  682. , node::Buffer::FreeCallback callback
  683. #else
  684. , node::smalloc::FreeCallback callback
  685. #endif
  686. , void *hint
  687. ) {
  688. // arbitrary buffer lengths requires
  689. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  690. assert(length <= imp::kMaxLength && "too large buffer");
  691. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  692. return node::Buffer::New(
  693. v8::Isolate::GetCurrent(), data, length, callback, hint);
  694. #else
  695. return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback,
  696. hint);
  697. #endif
  698. }
  699. inline MaybeLocal<v8::Object> CopyBuffer(
  700. const char *data
  701. , uint32_t size
  702. ) {
  703. // arbitrary buffer lengths requires
  704. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  705. assert(size <= imp::kMaxLength && "too large buffer");
  706. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  707. return node::Buffer::Copy(
  708. v8::Isolate::GetCurrent(), data, size);
  709. #else
  710. return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
  711. #endif
  712. }
  713. inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
  714. // arbitrary buffer lengths requires
  715. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  716. assert(size <= imp::kMaxLength && "too large buffer");
  717. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  718. return node::Buffer::New(
  719. v8::Isolate::GetCurrent(), size);
  720. #else
  721. return node::Buffer::New(v8::Isolate::GetCurrent(), size);
  722. #endif
  723. }
  724. inline MaybeLocal<v8::Object> NewBuffer(
  725. char* data
  726. , uint32_t size
  727. ) {
  728. // arbitrary buffer lengths requires
  729. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  730. assert(size <= imp::kMaxLength && "too large buffer");
  731. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  732. return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
  733. #else
  734. return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
  735. #endif
  736. }
  737. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  738. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  739. inline MaybeLocal<v8::String>
  740. NewOneByteString(const uint8_t * value, int length = -1) {
  741. return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
  742. v8::NewStringType::kNormal, length);
  743. }
  744. inline MaybeLocal<BoundScript> CompileScript(
  745. v8::Local<v8::String> s
  746. , const v8::ScriptOrigin& origin
  747. ) {
  748. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  749. v8::EscapableHandleScope scope(isolate);
  750. v8::ScriptCompiler::Source source(s, origin);
  751. return scope.Escape(
  752. v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
  753. .FromMaybe(v8::Local<BoundScript>()));
  754. }
  755. inline MaybeLocal<BoundScript> CompileScript(
  756. v8::Local<v8::String> s
  757. ) {
  758. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  759. v8::EscapableHandleScope scope(isolate);
  760. v8::ScriptCompiler::Source source(s);
  761. return scope.Escape(
  762. v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
  763. .FromMaybe(v8::Local<BoundScript>()));
  764. }
  765. inline MaybeLocal<v8::Value> RunScript(
  766. v8::Local<UnboundScript> script
  767. ) {
  768. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  769. v8::EscapableHandleScope scope(isolate);
  770. return scope.Escape(script->BindToCurrentContext()
  771. ->Run(isolate->GetCurrentContext())
  772. .FromMaybe(v8::Local<v8::Value>()));
  773. }
  774. inline MaybeLocal<v8::Value> RunScript(
  775. v8::Local<BoundScript> script
  776. ) {
  777. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  778. v8::EscapableHandleScope scope(isolate);
  779. return scope.Escape(script->Run(isolate->GetCurrentContext())
  780. .FromMaybe(v8::Local<v8::Value>()));
  781. }
  782. #else
  783. inline MaybeLocal<v8::String>
  784. NewOneByteString(const uint8_t * value, int length = -1) {
  785. return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
  786. v8::String::kNormalString, length);
  787. }
  788. inline MaybeLocal<BoundScript> CompileScript(
  789. v8::Local<v8::String> s
  790. , const v8::ScriptOrigin& origin
  791. ) {
  792. v8::ScriptCompiler::Source source(s, origin);
  793. return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
  794. }
  795. inline MaybeLocal<BoundScript> CompileScript(
  796. v8::Local<v8::String> s
  797. ) {
  798. v8::ScriptCompiler::Source source(s);
  799. return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
  800. }
  801. inline MaybeLocal<v8::Value> RunScript(
  802. v8::Local<UnboundScript> script
  803. ) {
  804. EscapableHandleScope scope;
  805. return scope.Escape(script->BindToCurrentContext()->Run());
  806. }
  807. inline MaybeLocal<v8::Value> RunScript(
  808. v8::Local<BoundScript> script
  809. ) {
  810. return script->Run();
  811. }
  812. #endif
  813. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  814. v8::Local<v8::Object> target
  815. , v8::Local<v8::Function> func
  816. , int argc
  817. , v8::Local<v8::Value>* argv) {
  818. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  819. EscapableHandleScope scope;
  820. return scope.Escape(New(node::MakeCallback(
  821. v8::Isolate::GetCurrent(), target, func, argc, argv)));
  822. #else
  823. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  824. AsyncResource res("nan:makeCallback");
  825. return res.runInAsyncScope(target, func, argc, argv)
  826. .FromMaybe(v8::Local<v8::Value>());
  827. # else
  828. return node::MakeCallback(
  829. v8::Isolate::GetCurrent(), target, func, argc, argv);
  830. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  831. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  832. }
  833. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  834. v8::Local<v8::Object> target
  835. , v8::Local<v8::String> symbol
  836. , int argc
  837. , v8::Local<v8::Value>* argv) {
  838. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  839. EscapableHandleScope scope;
  840. return scope.Escape(New(node::MakeCallback(
  841. v8::Isolate::GetCurrent(), target, symbol, argc, argv)));
  842. #else
  843. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  844. AsyncResource res("nan:makeCallback");
  845. return res.runInAsyncScope(target, symbol, argc, argv)
  846. .FromMaybe(v8::Local<v8::Value>());
  847. # else
  848. return node::MakeCallback(
  849. v8::Isolate::GetCurrent(), target, symbol, argc, argv);
  850. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  851. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  852. }
  853. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  854. v8::Local<v8::Object> target
  855. , const char* method
  856. , int argc
  857. , v8::Local<v8::Value>* argv) {
  858. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  859. EscapableHandleScope scope;
  860. return scope.Escape(New(node::MakeCallback(
  861. v8::Isolate::GetCurrent(), target, method, argc, argv)));
  862. #else
  863. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  864. AsyncResource res("nan:makeCallback");
  865. return res.runInAsyncScope(target, method, argc, argv)
  866. .FromMaybe(v8::Local<v8::Value>());
  867. # else
  868. return node::MakeCallback(
  869. v8::Isolate::GetCurrent(), target, method, argc, argv);
  870. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  871. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  872. }
  873. inline void FatalException(const TryCatch& try_catch) {
  874. node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_);
  875. }
  876. inline v8::Local<v8::Value> ErrnoException(
  877. int errorno
  878. , const char* syscall = NULL
  879. , const char* message = NULL
  880. , const char* path = NULL) {
  881. return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall,
  882. message, path);
  883. }
  884. NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
  885. int errorno
  886. , const char* syscall = NULL
  887. , const char* message = NULL
  888. , const char* path = NULL) {
  889. return ErrnoException(errorno, syscall, message, path);
  890. }
  891. template<typename T>
  892. inline void SetIsolateData(
  893. v8::Isolate *isolate
  894. , T *data
  895. ) {
  896. isolate->SetData(0, data);
  897. }
  898. template<typename T>
  899. inline T *GetIsolateData(
  900. v8::Isolate *isolate
  901. ) {
  902. return static_cast<T*>(isolate->GetData(0));
  903. }
  904. class Utf8String {
  905. public:
  906. inline explicit Utf8String(v8::Local<v8::Value> from) :
  907. length_(0), str_(str_st_) {
  908. HandleScope scope;
  909. if (!from.IsEmpty()) {
  910. #if V8_MAJOR_VERSION >= 7
  911. v8::Local<v8::String> string = from->ToString(v8::Isolate::GetCurrent());
  912. #else
  913. v8::Local<v8::String> string = from->ToString();
  914. #endif
  915. if (!string.IsEmpty()) {
  916. size_t len = 3 * string->Length() + 1;
  917. assert(len <= INT_MAX);
  918. if (len > sizeof (str_st_)) {
  919. str_ = static_cast<char*>(malloc(len));
  920. assert(str_ != 0);
  921. }
  922. const int flags =
  923. v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
  924. #if V8_MAJOR_VERSION >= 7
  925. length_ = string->WriteUtf8(v8::Isolate::GetCurrent(), str_, static_cast<int>(len), 0, flags);
  926. #else
  927. length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
  928. #endif
  929. str_[length_] = '\0';
  930. }
  931. }
  932. }
  933. inline int length() const {
  934. return length_;
  935. }
  936. inline char* operator*() { return str_; }
  937. inline const char* operator*() const { return str_; }
  938. inline ~Utf8String() {
  939. if (str_ != str_st_) {
  940. free(str_);
  941. }
  942. }
  943. private:
  944. NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
  945. int length_;
  946. char *str_;
  947. char str_st_[1024];
  948. };
  949. #else // Node 0.8 and 0.10
  950. inline v8::Local<v8::Primitive> Undefined() {
  951. EscapableHandleScope scope;
  952. return scope.Escape(New(v8::Undefined()));
  953. }
  954. inline v8::Local<v8::Primitive> Null() {
  955. EscapableHandleScope scope;
  956. return scope.Escape(New(v8::Null()));
  957. }
  958. inline v8::Local<v8::Boolean> True() {
  959. EscapableHandleScope scope;
  960. return scope.Escape(New(v8::True()));
  961. }
  962. inline v8::Local<v8::Boolean> False() {
  963. EscapableHandleScope scope;
  964. return scope.Escape(New(v8::False()));
  965. }
  966. inline v8::Local<v8::String> EmptyString() {
  967. return v8::String::Empty();
  968. }
  969. inline int AdjustExternalMemory(int bc) {
  970. return static_cast<int>(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc));
  971. }
  972. inline void SetTemplate(
  973. v8::Local<v8::Template> templ
  974. , const char *name
  975. , v8::Local<v8::Data> value) {
  976. templ->Set(name, value);
  977. }
  978. inline void SetTemplate(
  979. v8::Local<v8::Template> templ
  980. , v8::Local<v8::String> name
  981. , v8::Local<v8::Data> value
  982. , v8::PropertyAttribute attributes) {
  983. templ->Set(name, value, attributes);
  984. }
  985. inline v8::Local<v8::Context> GetCurrentContext() {
  986. return v8::Context::GetCurrent();
  987. }
  988. inline void* GetInternalFieldPointer(
  989. v8::Local<v8::Object> object
  990. , int index) {
  991. return object->GetPointerFromInternalField(index);
  992. }
  993. inline void SetInternalFieldPointer(
  994. v8::Local<v8::Object> object
  995. , int index
  996. , void* value) {
  997. object->SetPointerInInternalField(index, value);
  998. }
  999. # define NAN_GC_CALLBACK(name) \
  1000. void name(v8::GCType type, v8::GCCallbackFlags flags)
  1001. inline void AddGCEpilogueCallback(
  1002. v8::GCEpilogueCallback callback
  1003. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  1004. v8::V8::AddGCEpilogueCallback(callback, gc_type_filter);
  1005. }
  1006. inline void RemoveGCEpilogueCallback(
  1007. v8::GCEpilogueCallback callback) {
  1008. v8::V8::RemoveGCEpilogueCallback(callback);
  1009. }
  1010. inline void AddGCPrologueCallback(
  1011. v8::GCPrologueCallback callback
  1012. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  1013. v8::V8::AddGCPrologueCallback(callback, gc_type_filter);
  1014. }
  1015. inline void RemoveGCPrologueCallback(
  1016. v8::GCPrologueCallback callback) {
  1017. v8::V8::RemoveGCPrologueCallback(callback);
  1018. }
  1019. inline void GetHeapStatistics(
  1020. v8::HeapStatistics *heap_statistics) {
  1021. v8::V8::GetHeapStatistics(heap_statistics);
  1022. }
  1023. # define X(NAME) \
  1024. inline v8::Local<v8::Value> NAME(const char *msg) { \
  1025. EscapableHandleScope scope; \
  1026. return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  1027. } \
  1028. \
  1029. inline \
  1030. v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \
  1031. return v8::Exception::NAME(msg); \
  1032. } \
  1033. \
  1034. inline void Throw ## NAME(const char *msg) { \
  1035. HandleScope scope; \
  1036. v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  1037. } \
  1038. \
  1039. inline \
  1040. void Throw ## NAME(v8::Local<v8::String> errmsg) { \
  1041. HandleScope scope; \
  1042. v8::ThrowException(v8::Exception::NAME(errmsg)); \
  1043. }
  1044. X(Error)
  1045. X(RangeError)
  1046. X(ReferenceError)
  1047. X(SyntaxError)
  1048. X(TypeError)
  1049. # undef X
  1050. inline void ThrowError(v8::Local<v8::Value> error) {
  1051. v8::ThrowException(error);
  1052. }
  1053. inline MaybeLocal<v8::Object> NewBuffer(
  1054. char *data
  1055. , size_t length
  1056. , node::Buffer::free_callback callback
  1057. , void *hint
  1058. ) {
  1059. EscapableHandleScope scope;
  1060. // arbitrary buffer lengths requires
  1061. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1062. assert(length <= imp::kMaxLength && "too large buffer");
  1063. return scope.Escape(
  1064. New(node::Buffer::New(data, length, callback, hint)->handle_));
  1065. }
  1066. inline MaybeLocal<v8::Object> CopyBuffer(
  1067. const char *data
  1068. , uint32_t size
  1069. ) {
  1070. EscapableHandleScope scope;
  1071. // arbitrary buffer lengths requires
  1072. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1073. assert(size <= imp::kMaxLength && "too large buffer");
  1074. #if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
  1075. return scope.Escape(New(node::Buffer::New(data, size)->handle_));
  1076. #else
  1077. return scope.Escape(
  1078. New(node::Buffer::New(const_cast<char *>(data), size)->handle_));
  1079. #endif
  1080. }
  1081. inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
  1082. // arbitrary buffer lengths requires
  1083. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1084. EscapableHandleScope scope;
  1085. assert(size <= imp::kMaxLength && "too large buffer");
  1086. return scope.Escape(New(node::Buffer::New(size)->handle_));
  1087. }
  1088. inline void FreeData(char *data, void *hint) {
  1089. (void) hint; // unused
  1090. delete[] data;
  1091. }
  1092. inline MaybeLocal<v8::Object> NewBuffer(
  1093. char* data
  1094. , uint32_t size
  1095. ) {
  1096. EscapableHandleScope scope;
  1097. // arbitrary buffer lengths requires
  1098. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1099. assert(size <= imp::kMaxLength && "too large buffer");
  1100. return scope.Escape(
  1101. New(node::Buffer::New(data, size, FreeData, NULL)->handle_));
  1102. }
  1103. namespace imp {
  1104. inline void
  1105. widenString(std::vector<uint16_t> *ws, const uint8_t *s, int l) {
  1106. size_t len = static_cast<size_t>(l);
  1107. if (l < 0) {
  1108. len = strlen(reinterpret_cast<const char*>(s));
  1109. }
  1110. assert(len <= INT_MAX && "string too long");
  1111. ws->resize(len);
  1112. std::copy(s, s + len, ws->begin()); // NOLINT(build/include_what_you_use)
  1113. }
  1114. } // end of namespace imp
  1115. inline MaybeLocal<v8::String>
  1116. NewOneByteString(const uint8_t * value, int length = -1) {
  1117. std::vector<uint16_t> wideString; // NOLINT(build/include_what_you_use)
  1118. imp::widenString(&wideString, value, length);
  1119. return v8::String::New(wideString.data(),
  1120. static_cast<int>(wideString.size()));
  1121. }
  1122. inline MaybeLocal<BoundScript> CompileScript(
  1123. v8::Local<v8::String> s
  1124. , const v8::ScriptOrigin& origin
  1125. ) {
  1126. return v8::Script::Compile(s, const_cast<v8::ScriptOrigin *>(&origin));
  1127. }
  1128. inline MaybeLocal<BoundScript> CompileScript(
  1129. v8::Local<v8::String> s
  1130. ) {
  1131. return v8::Script::Compile(s);
  1132. }
  1133. inline
  1134. MaybeLocal<v8::Value> RunScript(v8::Local<v8::Script> script) {
  1135. return script->Run();
  1136. }
  1137. inline v8::Local<v8::Value> MakeCallback(
  1138. v8::Local<v8::Object> target
  1139. , v8::Local<v8::Function> func
  1140. , int argc
  1141. , v8::Local<v8::Value>* argv) {
  1142. v8::HandleScope scope;
  1143. return scope.Close(New(node::MakeCallback(target, func, argc, argv)));
  1144. }
  1145. inline v8::Local<v8::Value> MakeCallback(
  1146. v8::Local<v8::Object> target
  1147. , v8::Local<v8::String> symbol
  1148. , int argc
  1149. , v8::Local<v8::Value>* argv) {
  1150. v8::HandleScope scope;
  1151. return scope.Close(New(node::MakeCallback(target, symbol, argc, argv)));
  1152. }
  1153. inline v8::Local<v8::Value> MakeCallback(
  1154. v8::Local<v8::Object> target
  1155. , const char* method
  1156. , int argc
  1157. , v8::Local<v8::Value>* argv) {
  1158. v8::HandleScope scope;
  1159. return scope.Close(New(node::MakeCallback(target, method, argc, argv)));
  1160. }
  1161. inline void FatalException(const TryCatch& try_catch) {
  1162. node::FatalException(const_cast<v8::TryCatch &>(try_catch.try_catch_));
  1163. }
  1164. inline v8::Local<v8::Value> ErrnoException(
  1165. int errorno
  1166. , const char* syscall = NULL
  1167. , const char* message = NULL
  1168. , const char* path = NULL) {
  1169. return node::ErrnoException(errorno, syscall, message, path);
  1170. }
  1171. NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
  1172. int errorno
  1173. , const char* syscall = NULL
  1174. , const char* message = NULL
  1175. , const char* path = NULL) {
  1176. return ErrnoException(errorno, syscall, message, path);
  1177. }
  1178. template<typename T>
  1179. inline void SetIsolateData(
  1180. v8::Isolate *isolate
  1181. , T *data
  1182. ) {
  1183. isolate->SetData(data);
  1184. }
  1185. template<typename T>
  1186. inline T *GetIsolateData(
  1187. v8::Isolate *isolate
  1188. ) {
  1189. return static_cast<T*>(isolate->GetData());
  1190. }
  1191. class Utf8String {
  1192. public:
  1193. inline explicit Utf8String(v8::Local<v8::Value> from) :
  1194. length_(0), str_(str_st_) {
  1195. v8::HandleScope scope;
  1196. if (!from.IsEmpty()) {
  1197. v8::Local<v8::String> string = from->ToString();
  1198. if (!string.IsEmpty()) {
  1199. size_t len = 3 * string->Length() + 1;
  1200. assert(len <= INT_MAX);
  1201. if (len > sizeof (str_st_)) {
  1202. str_ = static_cast<char*>(malloc(len));
  1203. assert(str_ != 0);
  1204. }
  1205. const int flags =
  1206. v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
  1207. length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
  1208. str_[length_] = '\0';
  1209. }
  1210. }
  1211. }
  1212. inline int length() const {
  1213. return length_;
  1214. }
  1215. inline char* operator*() { return str_; }
  1216. inline const char* operator*() const { return str_; }
  1217. inline ~Utf8String() {
  1218. if (str_ != str_st_) {
  1219. free(str_);
  1220. }
  1221. }
  1222. private:
  1223. NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
  1224. int length_;
  1225. char *str_;
  1226. char str_st_[1024];
  1227. };
  1228. #endif // NODE_MODULE_VERSION
  1229. typedef void (*FreeCallback)(char *data, void *hint);
  1230. typedef const FunctionCallbackInfo<v8::Value>& NAN_METHOD_ARGS_TYPE;
  1231. typedef void NAN_METHOD_RETURN_TYPE;
  1232. typedef const PropertyCallbackInfo<v8::Value>& NAN_GETTER_ARGS_TYPE;
  1233. typedef void NAN_GETTER_RETURN_TYPE;
  1234. typedef const PropertyCallbackInfo<void>& NAN_SETTER_ARGS_TYPE;
  1235. typedef void NAN_SETTER_RETURN_TYPE;
  1236. typedef const PropertyCallbackInfo<v8::Value>&
  1237. NAN_PROPERTY_GETTER_ARGS_TYPE;
  1238. typedef void NAN_PROPERTY_GETTER_RETURN_TYPE;
  1239. typedef const PropertyCallbackInfo<v8::Value>&
  1240. NAN_PROPERTY_SETTER_ARGS_TYPE;
  1241. typedef void NAN_PROPERTY_SETTER_RETURN_TYPE;
  1242. typedef const PropertyCallbackInfo<v8::Array>&
  1243. NAN_PROPERTY_ENUMERATOR_ARGS_TYPE;
  1244. typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE;
  1245. typedef const PropertyCallbackInfo<v8::Boolean>&
  1246. NAN_PROPERTY_DELETER_ARGS_TYPE;
  1247. typedef void NAN_PROPERTY_DELETER_RETURN_TYPE;
  1248. typedef const PropertyCallbackInfo<v8::Integer>&
  1249. NAN_PROPERTY_QUERY_ARGS_TYPE;
  1250. typedef void NAN_PROPERTY_QUERY_RETURN_TYPE;
  1251. typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_GETTER_ARGS_TYPE;
  1252. typedef void NAN_INDEX_GETTER_RETURN_TYPE;
  1253. typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_SETTER_ARGS_TYPE;
  1254. typedef void NAN_INDEX_SETTER_RETURN_TYPE;
  1255. typedef const PropertyCallbackInfo<v8::Array>&
  1256. NAN_INDEX_ENUMERATOR_ARGS_TYPE;
  1257. typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE;
  1258. typedef const PropertyCallbackInfo<v8::Boolean>&
  1259. NAN_INDEX_DELETER_ARGS_TYPE;
  1260. typedef void NAN_INDEX_DELETER_RETURN_TYPE;
  1261. typedef const PropertyCallbackInfo<v8::Integer>&
  1262. NAN_INDEX_QUERY_ARGS_TYPE;
  1263. typedef void NAN_INDEX_QUERY_RETURN_TYPE;
  1264. #define NAN_METHOD(name) \
  1265. Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info)
  1266. #define NAN_GETTER(name) \
  1267. Nan::NAN_GETTER_RETURN_TYPE name( \
  1268. v8::Local<v8::String> property \
  1269. , Nan::NAN_GETTER_ARGS_TYPE info)
  1270. #define NAN_SETTER(name) \
  1271. Nan::NAN_SETTER_RETURN_TYPE name( \
  1272. v8::Local<v8::String> property \
  1273. , v8::Local<v8::Value> value \
  1274. , Nan::NAN_SETTER_ARGS_TYPE info)
  1275. #define NAN_PROPERTY_GETTER(name) \
  1276. Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name( \
  1277. v8::Local<v8::String> property \
  1278. , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info)
  1279. #define NAN_PROPERTY_SETTER(name) \
  1280. Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name( \
  1281. v8::Local<v8::String> property \
  1282. , v8::Local<v8::Value> value \
  1283. , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info)
  1284. #define NAN_PROPERTY_ENUMERATOR(name) \
  1285. Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name( \
  1286. Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info)
  1287. #define NAN_PROPERTY_DELETER(name) \
  1288. Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name( \
  1289. v8::Local<v8::String> property \
  1290. , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info)
  1291. #define NAN_PROPERTY_QUERY(name) \
  1292. Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name( \
  1293. v8::Local<v8::String> property \
  1294. , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info)
  1295. # define NAN_INDEX_GETTER(name) \
  1296. Nan::NAN_INDEX_GETTER_RETURN_TYPE name( \
  1297. uint32_t index \
  1298. , Nan::NAN_INDEX_GETTER_ARGS_TYPE info)
  1299. #define NAN_INDEX_SETTER(name) \
  1300. Nan::NAN_INDEX_SETTER_RETURN_TYPE name( \
  1301. uint32_t index \
  1302. , v8::Local<v8::Value> value \
  1303. , Nan::NAN_INDEX_SETTER_ARGS_TYPE info)
  1304. #define NAN_INDEX_ENUMERATOR(name) \
  1305. Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE \
  1306. name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info)
  1307. #define NAN_INDEX_DELETER(name) \
  1308. Nan::NAN_INDEX_DELETER_RETURN_TYPE name( \
  1309. uint32_t index \
  1310. , Nan::NAN_INDEX_DELETER_ARGS_TYPE info)
  1311. #define NAN_INDEX_QUERY(name) \
  1312. Nan::NAN_INDEX_QUERY_RETURN_TYPE name( \
  1313. uint32_t index \
  1314. , Nan::NAN_INDEX_QUERY_ARGS_TYPE info)
  1315. class Callback {
  1316. public:
  1317. Callback() {}
  1318. explicit Callback(const v8::Local<v8::Function> &fn) : handle_(fn) {}
  1319. ~Callback() {
  1320. handle_.Reset();
  1321. }
  1322. bool operator==(const Callback &other) const {
  1323. return handle_ == other.handle_;
  1324. }
  1325. bool operator!=(const Callback &other) const {
  1326. return !operator==(other);
  1327. }
  1328. inline
  1329. v8::Local<v8::Function> operator*() const { return GetFunction(); }
  1330. NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
  1331. v8::Local<v8::Object> target
  1332. , int argc = 0
  1333. , v8::Local<v8::Value> argv[] = 0) const {
  1334. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1335. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1336. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1337. AsyncResource async("nan:Callback:operator()");
  1338. return Call_(isolate, target, argc, argv, &async)
  1339. .FromMaybe(v8::Local<v8::Value>());
  1340. # else
  1341. return Call_(isolate, target, argc, argv);
  1342. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1343. #else
  1344. return Call_(target, argc, argv);
  1345. #endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1346. }
  1347. NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
  1348. int argc = 0
  1349. , v8::Local<v8::Value> argv[] = 0) const {
  1350. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1351. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1352. v8::EscapableHandleScope scope(isolate);
  1353. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1354. AsyncResource async("nan:Callback:operator()");
  1355. return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
  1356. argc, argv, &async)
  1357. .FromMaybe(v8::Local<v8::Value>()));
  1358. # else
  1359. return scope.Escape(
  1360. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1361. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1362. #else
  1363. v8::HandleScope scope;
  1364. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1365. #endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1366. }
  1367. inline MaybeLocal<v8::Value> operator()(
  1368. AsyncResource* resource
  1369. , int argc = 0
  1370. , v8::Local<v8::Value> argv[] = 0) const {
  1371. return this->Call(argc, argv, resource);
  1372. }
  1373. inline MaybeLocal<v8::Value> operator()(
  1374. AsyncResource* resource
  1375. , v8::Local<v8::Object> target
  1376. , int argc = 0
  1377. , v8::Local<v8::Value> argv[] = 0) const {
  1378. return this->Call(target, argc, argv, resource);
  1379. }
  1380. // TODO(kkoopa): remove
  1381. inline void SetFunction(const v8::Local<v8::Function> &fn) {
  1382. Reset(fn);
  1383. }
  1384. inline void Reset(const v8::Local<v8::Function> &fn) {
  1385. handle_.Reset(fn);
  1386. }
  1387. inline void Reset() {
  1388. handle_.Reset();
  1389. }
  1390. inline v8::Local<v8::Function> GetFunction() const {
  1391. return New(handle_);
  1392. }
  1393. inline bool IsEmpty() const {
  1394. return handle_.IsEmpty();
  1395. }
  1396. // Deprecated: For async callbacks Use the versions that accept an
  1397. // AsyncResource. If this callback does not correspond to an async resource,
  1398. // that is, it is a synchronous function call on a non-empty JS stack, you
  1399. // should Nan::Call instead.
  1400. NAN_DEPRECATED inline v8::Local<v8::Value>
  1401. Call(v8::Local<v8::Object> target
  1402. , int argc
  1403. , v8::Local<v8::Value> argv[]) const {
  1404. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1405. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1406. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1407. AsyncResource async("nan:Callback:Call");
  1408. return Call_(isolate, target, argc, argv, &async)
  1409. .FromMaybe(v8::Local<v8::Value>());
  1410. # else
  1411. return Call_(isolate, target, argc, argv);
  1412. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1413. #else
  1414. return Call_(target, argc, argv);
  1415. #endif
  1416. }
  1417. // Deprecated: For async callbacks Use the versions that accept an
  1418. // AsyncResource. If this callback does not correspond to an async resource,
  1419. // that is, it is a synchronous function call on a non-empty JS stack, you
  1420. // should Nan::Call instead.
  1421. NAN_DEPRECATED inline v8::Local<v8::Value>
  1422. Call(int argc, v8::Local<v8::Value> argv[]) const {
  1423. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1424. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1425. v8::EscapableHandleScope scope(isolate);
  1426. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1427. AsyncResource async("nan:Callback:Call");
  1428. return Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv,
  1429. &async)
  1430. .FromMaybe(v8::Local<v8::Value>());
  1431. # else
  1432. return scope.Escape(
  1433. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1434. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1435. #else
  1436. v8::HandleScope scope;
  1437. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1438. #endif
  1439. }
  1440. inline MaybeLocal<v8::Value>
  1441. Call(v8::Local<v8::Object> target
  1442. , int argc
  1443. , v8::Local<v8::Value> argv[]
  1444. , AsyncResource* resource) const {
  1445. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1446. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1447. return Call_(isolate, target, argc, argv, resource);
  1448. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1449. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1450. return Call_(isolate, target, argc, argv);
  1451. #else
  1452. return Call_(target, argc, argv);
  1453. #endif
  1454. }
  1455. inline MaybeLocal<v8::Value>
  1456. Call(int argc, v8::Local<v8::Value> argv[], AsyncResource* resource) const {
  1457. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1458. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1459. return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource);
  1460. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1461. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1462. v8::EscapableHandleScope scope(isolate);
  1463. return scope.Escape(
  1464. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1465. #else
  1466. v8::HandleScope scope;
  1467. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1468. #endif
  1469. }
  1470. private:
  1471. NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback)
  1472. Persistent<v8::Function> handle_;
  1473. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1474. MaybeLocal<v8::Value> Call_(v8::Isolate *isolate
  1475. , v8::Local<v8::Object> target
  1476. , int argc
  1477. , v8::Local<v8::Value> argv[]
  1478. , AsyncResource* resource) const {
  1479. EscapableHandleScope scope;
  1480. v8::Local<v8::Function> func = New(handle_);
  1481. auto maybe = resource->runInAsyncScope(target, func, argc, argv);
  1482. v8::Local<v8::Value> local;
  1483. if (!maybe.ToLocal(&local)) return MaybeLocal<v8::Value>();
  1484. return scope.Escape(local);
  1485. }
  1486. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1487. v8::Local<v8::Value> Call_(v8::Isolate *isolate
  1488. , v8::Local<v8::Object> target
  1489. , int argc
  1490. , v8::Local<v8::Value> argv[]) const {
  1491. EscapableHandleScope scope;
  1492. v8::Local<v8::Function> callback = New(handle_);
  1493. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  1494. return scope.Escape(New(node::MakeCallback(
  1495. isolate
  1496. , target
  1497. , callback
  1498. , argc
  1499. , argv
  1500. )));
  1501. # else
  1502. return scope.Escape(node::MakeCallback(
  1503. isolate
  1504. , target
  1505. , callback
  1506. , argc
  1507. , argv
  1508. ));
  1509. # endif
  1510. }
  1511. #else
  1512. v8::Local<v8::Value> Call_(v8::Local<v8::Object> target
  1513. , int argc
  1514. , v8::Local<v8::Value> argv[]) const {
  1515. EscapableHandleScope scope;
  1516. v8::Local<v8::Function> callback = New(handle_);
  1517. return scope.Escape(New(node::MakeCallback(
  1518. target
  1519. , callback
  1520. , argc
  1521. , argv
  1522. )));
  1523. }
  1524. #endif
  1525. };
  1526. inline MaybeLocal<v8::Value> Call(
  1527. const Nan::Callback& callback
  1528. , v8::Local<v8::Object> recv
  1529. , int argc
  1530. , v8::Local<v8::Value> argv[]) {
  1531. return Call(*callback, recv, argc, argv);
  1532. }
  1533. inline MaybeLocal<v8::Value> Call(
  1534. const Nan::Callback& callback
  1535. , int argc
  1536. , v8::Local<v8::Value> argv[]) {
  1537. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1538. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1539. v8::EscapableHandleScope scope(isolate);
  1540. return scope.Escape(
  1541. Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv)
  1542. .FromMaybe(v8::Local<v8::Value>()));
  1543. #else
  1544. EscapableHandleScope scope;
  1545. return scope.Escape(
  1546. Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv)
  1547. .FromMaybe(v8::Local<v8::Value>()));
  1548. #endif
  1549. }
  1550. inline MaybeLocal<v8::Value> Call(
  1551. v8::Local<v8::String> symbol
  1552. , v8::Local<v8::Object> recv
  1553. , int argc
  1554. , v8::Local<v8::Value> argv[]) {
  1555. EscapableHandleScope scope;
  1556. v8::Local<v8::Value> fn_v =
  1557. Get(recv, symbol).FromMaybe(v8::Local<v8::Value>());
  1558. if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local<v8::Value>();
  1559. v8::Local<v8::Function> fn = fn_v.As<v8::Function>();
  1560. return scope.Escape(
  1561. Call(fn, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
  1562. }
  1563. inline MaybeLocal<v8::Value> Call(
  1564. const char* method
  1565. , v8::Local<v8::Object> recv
  1566. , int argc
  1567. , v8::Local<v8::Value> argv[]) {
  1568. EscapableHandleScope scope;
  1569. v8::Local<v8::String> method_string =
  1570. New<v8::String>(method).ToLocalChecked();
  1571. return scope.Escape(
  1572. Call(method_string, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
  1573. }
  1574. /* abstract */ class AsyncWorker {
  1575. public:
  1576. explicit AsyncWorker(Callback *callback_,
  1577. const char* resource_name = "nan:AsyncWorker")
  1578. : callback(callback_), errmsg_(NULL) {
  1579. request.data = this;
  1580. HandleScope scope;
  1581. v8::Local<v8::Object> obj = New<v8::Object>();
  1582. persistentHandle.Reset(obj);
  1583. async_resource = new AsyncResource(resource_name, obj);
  1584. }
  1585. virtual ~AsyncWorker() {
  1586. HandleScope scope;
  1587. if (!persistentHandle.IsEmpty())
  1588. persistentHandle.Reset();
  1589. delete callback;
  1590. delete[] errmsg_;
  1591. delete async_resource;
  1592. }
  1593. virtual void WorkComplete() {
  1594. HandleScope scope;
  1595. if (errmsg_ == NULL)
  1596. HandleOKCallback();
  1597. else
  1598. HandleErrorCallback();
  1599. delete callback;
  1600. callback = NULL;
  1601. }
  1602. inline void SaveToPersistent(
  1603. const char *key, const v8::Local<v8::Value> &value) {
  1604. HandleScope scope;
  1605. New(persistentHandle)->Set(New(key).ToLocalChecked(), value);
  1606. }
  1607. inline void SaveToPersistent(
  1608. const v8::Local<v8::String> &key, const v8::Local<v8::Value> &value) {
  1609. HandleScope scope;
  1610. New(persistentHandle)->Set(key, value);
  1611. }
  1612. inline void SaveToPersistent(
  1613. uint32_t index, const v8::Local<v8::Value> &value) {
  1614. HandleScope scope;
  1615. New(persistentHandle)->Set(index, value);
  1616. }
  1617. inline v8::Local<v8::Value> GetFromPersistent(const char *key) const {
  1618. EscapableHandleScope scope;
  1619. return scope.Escape(
  1620. New(persistentHandle)->Get(New(key).ToLocalChecked()));
  1621. }
  1622. inline v8::Local<v8::Value>
  1623. GetFromPersistent(const v8::Local<v8::String> &key) const {
  1624. EscapableHandleScope scope;
  1625. return scope.Escape(New(persistentHandle)->Get(key));
  1626. }
  1627. inline v8::Local<v8::Value> GetFromPersistent(uint32_t index) const {
  1628. EscapableHandleScope scope;
  1629. return scope.Escape(New(persistentHandle)->Get(index));
  1630. }
  1631. virtual void Execute() = 0;
  1632. uv_work_t request;
  1633. virtual void Destroy() {
  1634. delete this;
  1635. }
  1636. protected:
  1637. Persistent<v8::Object> persistentHandle;
  1638. Callback *callback;
  1639. AsyncResource *async_resource;
  1640. virtual void HandleOKCallback() {
  1641. HandleScope scope;
  1642. callback->Call(0, NULL, async_resource);
  1643. }
  1644. virtual void HandleErrorCallback() {
  1645. HandleScope scope;
  1646. v8::Local<v8::Value> argv[] = {
  1647. v8::Exception::Error(New<v8::String>(ErrorMessage()).ToLocalChecked())
  1648. };
  1649. callback->Call(1, argv, async_resource);
  1650. }
  1651. void SetErrorMessage(const char *msg) {
  1652. delete[] errmsg_;
  1653. size_t size = strlen(msg) + 1;
  1654. errmsg_ = new char[size];
  1655. memcpy(errmsg_, msg, size);
  1656. }
  1657. const char* ErrorMessage() const {
  1658. return errmsg_;
  1659. }
  1660. private:
  1661. NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker)
  1662. char *errmsg_;
  1663. };
  1664. /* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker {
  1665. public:
  1666. explicit AsyncBareProgressWorkerBase(
  1667. Callback *callback_,
  1668. const char* resource_name = "nan:AsyncBareProgressWorkerBase")
  1669. : AsyncWorker(callback_, resource_name) {
  1670. uv_async_init(
  1671. GetCurrentEventLoop()
  1672. , &async
  1673. , AsyncProgress_
  1674. );
  1675. async.data = this;
  1676. }
  1677. virtual ~AsyncBareProgressWorkerBase() {
  1678. }
  1679. virtual void WorkProgress() = 0;
  1680. virtual void Destroy() {
  1681. uv_close(reinterpret_cast<uv_handle_t*>(&async), AsyncClose_);
  1682. }
  1683. private:
  1684. inline static NAUV_WORK_CB(AsyncProgress_) {
  1685. AsyncBareProgressWorkerBase *worker =
  1686. static_cast<AsyncBareProgressWorkerBase*>(async->data);
  1687. worker->WorkProgress();
  1688. }
  1689. inline static void AsyncClose_(uv_handle_t* handle) {
  1690. AsyncBareProgressWorkerBase *worker =
  1691. static_cast<AsyncBareProgressWorkerBase*>(handle->data);
  1692. delete worker;
  1693. }
  1694. protected:
  1695. uv_async_t async;
  1696. };
  1697. template<class T>
  1698. /* abstract */
  1699. class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase {
  1700. public:
  1701. explicit AsyncBareProgressWorker(
  1702. Callback *callback_,
  1703. const char* resource_name = "nan:AsyncBareProgressWorker")
  1704. : AsyncBareProgressWorkerBase(callback_, resource_name) {
  1705. uv_mutex_init(&async_lock);
  1706. }
  1707. virtual ~AsyncBareProgressWorker() {
  1708. uv_mutex_destroy(&async_lock);
  1709. }
  1710. class ExecutionProgress {
  1711. friend class AsyncBareProgressWorker;
  1712. public:
  1713. void Signal() const {
  1714. uv_mutex_lock(&that_->async_lock);
  1715. uv_async_send(&that_->async);
  1716. uv_mutex_unlock(&that_->async_lock);
  1717. }
  1718. void Send(const T* data, size_t count) const {
  1719. that_->SendProgress_(data, count);
  1720. }
  1721. private:
  1722. explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {}
  1723. NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
  1724. AsyncBareProgressWorker* const that_;
  1725. };
  1726. virtual void Execute(const ExecutionProgress& progress) = 0;
  1727. virtual void HandleProgressCallback(const T *data, size_t size) = 0;
  1728. protected:
  1729. uv_mutex_t async_lock;
  1730. private:
  1731. void Execute() /*final override*/ {
  1732. ExecutionProgress progress(this);
  1733. Execute(progress);
  1734. }
  1735. virtual void SendProgress_(const T *data, size_t count) = 0;
  1736. };
  1737. template<class T>
  1738. /* abstract */
  1739. class AsyncProgressWorkerBase : public AsyncBareProgressWorker<T> {
  1740. public:
  1741. explicit AsyncProgressWorkerBase(
  1742. Callback *callback_,
  1743. const char* resource_name = "nan:AsyncProgressWorkerBase")
  1744. : AsyncBareProgressWorker<T>(callback_, resource_name), asyncdata_(NULL),
  1745. asyncsize_(0) {
  1746. }
  1747. virtual ~AsyncProgressWorkerBase() {
  1748. delete[] asyncdata_;
  1749. }
  1750. void WorkProgress() {
  1751. uv_mutex_lock(&this->async_lock);
  1752. T *data = asyncdata_;
  1753. size_t size = asyncsize_;
  1754. asyncdata_ = NULL;
  1755. asyncsize_ = 0;
  1756. uv_mutex_unlock(&this->async_lock);
  1757. // Don't send progress events after we've already completed.
  1758. if (this->callback) {
  1759. this->HandleProgressCallback(data, size);
  1760. }
  1761. delete[] data;
  1762. }
  1763. private:
  1764. void SendProgress_(const T *data, size_t count) {
  1765. T *new_data = new T[count];
  1766. {
  1767. T *it = new_data;
  1768. std::copy(data, data + count, it);
  1769. }
  1770. uv_mutex_lock(&this->async_lock);
  1771. T *old_data = asyncdata_;
  1772. asyncdata_ = new_data;
  1773. asyncsize_ = count;
  1774. uv_async_send(&this->async);
  1775. uv_mutex_unlock(&this->async_lock);
  1776. delete[] old_data;
  1777. }
  1778. T *asyncdata_;
  1779. size_t asyncsize_;
  1780. };
  1781. // This ensures compatibility to the previous un-templated AsyncProgressWorker
  1782. // class definition.
  1783. typedef AsyncProgressWorkerBase<char> AsyncProgressWorker;
  1784. template<class T>
  1785. /* abstract */
  1786. class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase {
  1787. public:
  1788. explicit AsyncBareProgressQueueWorker(
  1789. Callback *callback_,
  1790. const char* resource_name = "nan:AsyncBareProgressQueueWorker")
  1791. : AsyncBareProgressWorkerBase(callback_, resource_name) {
  1792. }
  1793. virtual ~AsyncBareProgressQueueWorker() {
  1794. }
  1795. class ExecutionProgress {
  1796. friend class AsyncBareProgressQueueWorker;
  1797. public:
  1798. void Send(const T* data, size_t count) const {
  1799. that_->SendProgress_(data, count);
  1800. }
  1801. private:
  1802. explicit ExecutionProgress(AsyncBareProgressQueueWorker *that)
  1803. : that_(that) {}
  1804. NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
  1805. AsyncBareProgressQueueWorker* const that_;
  1806. };
  1807. virtual void Execute(const ExecutionProgress& progress) = 0;
  1808. virtual void HandleProgressCallback(const T *data, size_t size) = 0;
  1809. private:
  1810. void Execute() /*final override*/ {
  1811. ExecutionProgress progress(this);
  1812. Execute(progress);
  1813. }
  1814. virtual void SendProgress_(const T *data, size_t count) = 0;
  1815. };
  1816. template<class T>
  1817. /* abstract */
  1818. class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker<T> {
  1819. public:
  1820. explicit AsyncProgressQueueWorker(
  1821. Callback *callback_,
  1822. const char* resource_name = "nan:AsyncProgressQueueWorker")
  1823. : AsyncBareProgressQueueWorker<T>(callback_) {
  1824. uv_mutex_init(&async_lock);
  1825. }
  1826. virtual ~AsyncProgressQueueWorker() {
  1827. uv_mutex_lock(&async_lock);
  1828. while (!asyncdata_.empty()) {
  1829. std::pair<T*, size_t> &datapair = asyncdata_.front();
  1830. T *data = datapair.first;
  1831. asyncdata_.pop();
  1832. delete[] data;
  1833. }
  1834. uv_mutex_unlock(&async_lock);
  1835. uv_mutex_destroy(&async_lock);
  1836. }
  1837. void WorkComplete() {
  1838. WorkProgress();
  1839. AsyncWorker::WorkComplete();
  1840. }
  1841. void WorkProgress() {
  1842. uv_mutex_lock(&async_lock);
  1843. while (!asyncdata_.empty()) {
  1844. std::pair<T*, size_t> &datapair = asyncdata_.front();
  1845. T *data = datapair.first;
  1846. size_t size = datapair.second;
  1847. asyncdata_.pop();
  1848. uv_mutex_unlock(&async_lock);
  1849. // Don't send progress events after we've already completed.
  1850. if (this->callback) {
  1851. this->HandleProgressCallback(data, size);
  1852. }
  1853. delete[] data;
  1854. uv_mutex_lock(&async_lock);
  1855. }
  1856. uv_mutex_unlock(&async_lock);
  1857. }
  1858. private:
  1859. void SendProgress_(const T *data, size_t count) {
  1860. T *new_data = new T[count];
  1861. {
  1862. T *it = new_data;
  1863. std::copy(data, data + count, it);
  1864. }
  1865. uv_mutex_lock(&async_lock);
  1866. asyncdata_.push(std::pair<T*, size_t>(new_data, count));
  1867. uv_mutex_unlock(&async_lock);
  1868. uv_async_send(&this->async);
  1869. }
  1870. uv_mutex_t async_lock;
  1871. std::queue<std::pair<T*, size_t> > asyncdata_;
  1872. };
  1873. inline void AsyncExecute (uv_work_t* req) {
  1874. AsyncWorker *worker = static_cast<AsyncWorker*>(req->data);
  1875. worker->Execute();
  1876. }
  1877. inline void AsyncExecuteComplete (uv_work_t* req) {
  1878. AsyncWorker* worker = static_cast<AsyncWorker*>(req->data);
  1879. worker->WorkComplete();
  1880. worker->Destroy();
  1881. }
  1882. inline void AsyncQueueWorker (AsyncWorker* worker) {
  1883. uv_queue_work(
  1884. GetCurrentEventLoop()
  1885. , &worker->request
  1886. , AsyncExecute
  1887. , reinterpret_cast<uv_after_work_cb>(AsyncExecuteComplete)
  1888. );
  1889. }
  1890. namespace imp {
  1891. inline
  1892. ExternalOneByteStringResource const*
  1893. GetExternalResource(v8::Local<v8::String> str) {
  1894. #if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
  1895. return str->GetExternalAsciiStringResource();
  1896. #else
  1897. return str->GetExternalOneByteStringResource();
  1898. #endif
  1899. }
  1900. inline
  1901. bool
  1902. IsExternal(v8::Local<v8::String> str) {
  1903. #if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
  1904. return str->IsExternalAscii();
  1905. #else
  1906. return str->IsExternalOneByte();
  1907. #endif
  1908. }
  1909. } // end of namespace imp
  1910. enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER};
  1911. #if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION
  1912. # include "nan_string_bytes.h" // NOLINT(build/include)
  1913. #endif
  1914. inline v8::Local<v8::Value> Encode(
  1915. const void *buf, size_t len, enum Encoding encoding = BINARY) {
  1916. #if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION)
  1917. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1918. node::encoding node_enc = static_cast<node::encoding>(encoding);
  1919. if (encoding == UCS2) {
  1920. return node::Encode(
  1921. isolate
  1922. , reinterpret_cast<const uint16_t *>(buf)
  1923. , len / 2);
  1924. } else {
  1925. return node::Encode(
  1926. isolate
  1927. , reinterpret_cast<const char *>(buf)
  1928. , len
  1929. , node_enc);
  1930. }
  1931. #elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  1932. return node::Encode(
  1933. v8::Isolate::GetCurrent()
  1934. , buf, len
  1935. , static_cast<node::encoding>(encoding));
  1936. #else
  1937. # if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
  1938. return node::Encode(buf, len, static_cast<node::encoding>(encoding));
  1939. # else
  1940. return imp::Encode(reinterpret_cast<const char*>(buf), len, encoding);
  1941. # endif
  1942. #endif
  1943. }
  1944. inline ssize_t DecodeBytes(
  1945. v8::Local<v8::Value> val, enum Encoding encoding = BINARY) {
  1946. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  1947. return node::DecodeBytes(
  1948. v8::Isolate::GetCurrent()
  1949. , val
  1950. , static_cast<node::encoding>(encoding));
  1951. #else
  1952. # if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
  1953. if (encoding == BUFFER) {
  1954. return node::DecodeBytes(val, node::BINARY);
  1955. }
  1956. # endif
  1957. return node::DecodeBytes(val, static_cast<node::encoding>(encoding));
  1958. #endif
  1959. }
  1960. inline ssize_t DecodeWrite(
  1961. char *buf
  1962. , size_t len
  1963. , v8::Local<v8::Value> val
  1964. , enum Encoding encoding = BINARY) {
  1965. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  1966. return node::DecodeWrite(
  1967. v8::Isolate::GetCurrent()
  1968. , buf
  1969. , len
  1970. , val
  1971. , static_cast<node::encoding>(encoding));
  1972. #else
  1973. # if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
  1974. if (encoding == BUFFER) {
  1975. return node::DecodeWrite(buf, len, val, node::BINARY);
  1976. }
  1977. # endif
  1978. return node::DecodeWrite(
  1979. buf
  1980. , len
  1981. , val
  1982. , static_cast<node::encoding>(encoding));
  1983. #endif
  1984. }
  1985. inline void SetPrototypeTemplate(
  1986. v8::Local<v8::FunctionTemplate> templ
  1987. , const char *name
  1988. , v8::Local<v8::Data> value
  1989. ) {
  1990. HandleScope scope;
  1991. SetTemplate(templ->PrototypeTemplate(), name, value);
  1992. }
  1993. inline void SetPrototypeTemplate(
  1994. v8::Local<v8::FunctionTemplate> templ
  1995. , v8::Local<v8::String> name
  1996. , v8::Local<v8::Data> value
  1997. , v8::PropertyAttribute attributes
  1998. ) {
  1999. HandleScope scope;
  2000. SetTemplate(templ->PrototypeTemplate(), name, value, attributes);
  2001. }
  2002. inline void SetInstanceTemplate(
  2003. v8::Local<v8::FunctionTemplate> templ
  2004. , const char *name
  2005. , v8::Local<v8::Data> value
  2006. ) {
  2007. HandleScope scope;
  2008. SetTemplate(templ->InstanceTemplate(), name, value);
  2009. }
  2010. inline void SetInstanceTemplate(
  2011. v8::Local<v8::FunctionTemplate> templ
  2012. , v8::Local<v8::String> name
  2013. , v8::Local<v8::Data> value
  2014. , v8::PropertyAttribute attributes
  2015. ) {
  2016. HandleScope scope;
  2017. SetTemplate(templ->InstanceTemplate(), name, value, attributes);
  2018. }
  2019. namespace imp {
  2020. // Note(@agnat): Helper to distinguish different receiver types. The first
  2021. // version deals with receivers derived from v8::Template. The second version
  2022. // handles everything else. The final argument only serves as discriminator and
  2023. // is unused.
  2024. template <typename T>
  2025. inline
  2026. void
  2027. SetMethodAux(T recv,
  2028. v8::Local<v8::String> name,
  2029. v8::Local<v8::FunctionTemplate> tpl,
  2030. v8::Template *) {
  2031. recv->Set(name, tpl);
  2032. }
  2033. template <typename T>
  2034. inline
  2035. void
  2036. SetMethodAux(T recv,
  2037. v8::Local<v8::String> name,
  2038. v8::Local<v8::FunctionTemplate> tpl,
  2039. ...) {
  2040. recv->Set(name, GetFunction(tpl).ToLocalChecked());
  2041. }
  2042. } // end of namespace imp
  2043. template <typename T, template <typename> class HandleType>
  2044. inline void SetMethod(
  2045. HandleType<T> recv
  2046. , const char *name
  2047. , FunctionCallback callback) {
  2048. HandleScope scope;
  2049. v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(callback);
  2050. v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
  2051. t->SetClassName(fn_name);
  2052. // Note(@agnat): Pass an empty T* as discriminator. See note on
  2053. // SetMethodAux(...) above
  2054. imp::SetMethodAux(recv, fn_name, t, static_cast<T*>(0));
  2055. }
  2056. inline void SetPrototypeMethod(
  2057. v8::Local<v8::FunctionTemplate> recv
  2058. , const char* name, FunctionCallback callback) {
  2059. HandleScope scope;
  2060. v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(
  2061. callback
  2062. , v8::Local<v8::Value>()
  2063. , New<v8::Signature>(recv));
  2064. v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
  2065. recv->PrototypeTemplate()->Set(fn_name, t);
  2066. t->SetClassName(fn_name);
  2067. }
  2068. //=== Accessors and Such =======================================================
  2069. inline void SetAccessor(
  2070. v8::Local<v8::ObjectTemplate> tpl
  2071. , v8::Local<v8::String> name
  2072. , GetterCallback getter
  2073. , SetterCallback setter = 0
  2074. , v8::Local<v8::Value> data = v8::Local<v8::Value>()
  2075. , v8::AccessControl settings = v8::DEFAULT
  2076. , v8::PropertyAttribute attribute = v8::None
  2077. , imp::Sig signature = imp::Sig()) {
  2078. HandleScope scope;
  2079. imp::NativeGetter getter_ =
  2080. imp::GetterCallbackWrapper;
  2081. imp::NativeSetter setter_ =
  2082. setter ? imp::SetterCallbackWrapper : 0;
  2083. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2084. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2085. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2086. obj->SetInternalField(
  2087. imp::kGetterIndex
  2088. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2089. if (setter != 0) {
  2090. obj->SetInternalField(
  2091. imp::kSetterIndex
  2092. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2093. }
  2094. if (!data.IsEmpty()) {
  2095. obj->SetInternalField(imp::kDataIndex, data);
  2096. }
  2097. tpl->SetAccessor(
  2098. name
  2099. , getter_
  2100. , setter_
  2101. , obj
  2102. , settings
  2103. , attribute
  2104. , signature);
  2105. }
  2106. inline bool SetAccessor(
  2107. v8::Local<v8::Object> obj
  2108. , v8::Local<v8::String> name
  2109. , GetterCallback getter
  2110. , SetterCallback setter = 0
  2111. , v8::Local<v8::Value> data = v8::Local<v8::Value>()
  2112. , v8::AccessControl settings = v8::DEFAULT
  2113. , v8::PropertyAttribute attribute = v8::None) {
  2114. HandleScope scope;
  2115. imp::NativeGetter getter_ =
  2116. imp::GetterCallbackWrapper;
  2117. imp::NativeSetter setter_ =
  2118. setter ? imp::SetterCallbackWrapper : 0;
  2119. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2120. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2121. v8::Local<v8::Object> dataobj = NewInstance(otpl).ToLocalChecked();
  2122. dataobj->SetInternalField(
  2123. imp::kGetterIndex
  2124. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2125. if (!data.IsEmpty()) {
  2126. dataobj->SetInternalField(imp::kDataIndex, data);
  2127. }
  2128. if (setter) {
  2129. dataobj->SetInternalField(
  2130. imp::kSetterIndex
  2131. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2132. }
  2133. #if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
  2134. return obj->SetAccessor(
  2135. GetCurrentContext()
  2136. , name
  2137. , getter_
  2138. , setter_
  2139. , dataobj
  2140. , settings
  2141. , attribute).FromMaybe(false);
  2142. #else
  2143. return obj->SetAccessor(
  2144. name
  2145. , getter_
  2146. , setter_
  2147. , dataobj
  2148. , settings
  2149. , attribute);
  2150. #endif
  2151. }
  2152. inline void SetNamedPropertyHandler(
  2153. v8::Local<v8::ObjectTemplate> tpl
  2154. , PropertyGetterCallback getter
  2155. , PropertySetterCallback setter = 0
  2156. , PropertyQueryCallback query = 0
  2157. , PropertyDeleterCallback deleter = 0
  2158. , PropertyEnumeratorCallback enumerator = 0
  2159. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2160. HandleScope scope;
  2161. imp::NativePropertyGetter getter_ =
  2162. imp::PropertyGetterCallbackWrapper;
  2163. imp::NativePropertySetter setter_ =
  2164. setter ? imp::PropertySetterCallbackWrapper : 0;
  2165. imp::NativePropertyQuery query_ =
  2166. query ? imp::PropertyQueryCallbackWrapper : 0;
  2167. imp::NativePropertyDeleter *deleter_ =
  2168. deleter ? imp::PropertyDeleterCallbackWrapper : 0;
  2169. imp::NativePropertyEnumerator enumerator_ =
  2170. enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0;
  2171. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2172. otpl->SetInternalFieldCount(imp::kPropertyFieldCount);
  2173. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2174. obj->SetInternalField(
  2175. imp::kPropertyGetterIndex
  2176. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2177. if (setter) {
  2178. obj->SetInternalField(
  2179. imp::kPropertySetterIndex
  2180. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2181. }
  2182. if (query) {
  2183. obj->SetInternalField(
  2184. imp::kPropertyQueryIndex
  2185. , New<v8::External>(reinterpret_cast<void *>(query)));
  2186. }
  2187. if (deleter) {
  2188. obj->SetInternalField(
  2189. imp::kPropertyDeleterIndex
  2190. , New<v8::External>(reinterpret_cast<void *>(deleter)));
  2191. }
  2192. if (enumerator) {
  2193. obj->SetInternalField(
  2194. imp::kPropertyEnumeratorIndex
  2195. , New<v8::External>(reinterpret_cast<void *>(enumerator)));
  2196. }
  2197. if (!data.IsEmpty()) {
  2198. obj->SetInternalField(imp::kDataIndex, data);
  2199. }
  2200. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  2201. tpl->SetHandler(v8::NamedPropertyHandlerConfiguration(
  2202. getter_, setter_, query_, deleter_, enumerator_, obj));
  2203. #else
  2204. tpl->SetNamedPropertyHandler(
  2205. getter_
  2206. , setter_
  2207. , query_
  2208. , deleter_
  2209. , enumerator_
  2210. , obj);
  2211. #endif
  2212. }
  2213. inline void SetIndexedPropertyHandler(
  2214. v8::Local<v8::ObjectTemplate> tpl
  2215. , IndexGetterCallback getter
  2216. , IndexSetterCallback setter = 0
  2217. , IndexQueryCallback query = 0
  2218. , IndexDeleterCallback deleter = 0
  2219. , IndexEnumeratorCallback enumerator = 0
  2220. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2221. HandleScope scope;
  2222. imp::NativeIndexGetter getter_ =
  2223. imp::IndexGetterCallbackWrapper;
  2224. imp::NativeIndexSetter setter_ =
  2225. setter ? imp::IndexSetterCallbackWrapper : 0;
  2226. imp::NativeIndexQuery query_ =
  2227. query ? imp::IndexQueryCallbackWrapper : 0;
  2228. imp::NativeIndexDeleter deleter_ =
  2229. deleter ? imp::IndexDeleterCallbackWrapper : 0;
  2230. imp::NativeIndexEnumerator enumerator_ =
  2231. enumerator ? imp::IndexEnumeratorCallbackWrapper : 0;
  2232. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2233. otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount);
  2234. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2235. obj->SetInternalField(
  2236. imp::kIndexPropertyGetterIndex
  2237. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2238. if (setter) {
  2239. obj->SetInternalField(
  2240. imp::kIndexPropertySetterIndex
  2241. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2242. }
  2243. if (query) {
  2244. obj->SetInternalField(
  2245. imp::kIndexPropertyQueryIndex
  2246. , New<v8::External>(reinterpret_cast<void *>(query)));
  2247. }
  2248. if (deleter) {
  2249. obj->SetInternalField(
  2250. imp::kIndexPropertyDeleterIndex
  2251. , New<v8::External>(reinterpret_cast<void *>(deleter)));
  2252. }
  2253. if (enumerator) {
  2254. obj->SetInternalField(
  2255. imp::kIndexPropertyEnumeratorIndex
  2256. , New<v8::External>(reinterpret_cast<void *>(enumerator)));
  2257. }
  2258. if (!data.IsEmpty()) {
  2259. obj->SetInternalField(imp::kDataIndex, data);
  2260. }
  2261. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  2262. tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration(
  2263. getter_, setter_, query_, deleter_, enumerator_, obj));
  2264. #else
  2265. tpl->SetIndexedPropertyHandler(
  2266. getter_
  2267. , setter_
  2268. , query_
  2269. , deleter_
  2270. , enumerator_
  2271. , obj);
  2272. #endif
  2273. }
  2274. inline void SetCallHandler(
  2275. v8::Local<v8::FunctionTemplate> tpl
  2276. , FunctionCallback callback
  2277. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2278. HandleScope scope;
  2279. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2280. otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
  2281. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2282. obj->SetInternalField(
  2283. imp::kFunctionIndex
  2284. , New<v8::External>(reinterpret_cast<void *>(callback)));
  2285. if (!data.IsEmpty()) {
  2286. obj->SetInternalField(imp::kDataIndex, data);
  2287. }
  2288. tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj);
  2289. }
  2290. inline void SetCallAsFunctionHandler(
  2291. v8::Local<v8::ObjectTemplate> tpl,
  2292. FunctionCallback callback,
  2293. v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2294. HandleScope scope;
  2295. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2296. otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
  2297. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2298. obj->SetInternalField(
  2299. imp::kFunctionIndex
  2300. , New<v8::External>(reinterpret_cast<void *>(callback)));
  2301. if (!data.IsEmpty()) {
  2302. obj->SetInternalField(imp::kDataIndex, data);
  2303. }
  2304. tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj);
  2305. }
  2306. //=== Weak Persistent Handling =================================================
  2307. #include "nan_weak.h" // NOLINT(build/include)
  2308. //=== ObjectWrap ===============================================================
  2309. #include "nan_object_wrap.h" // NOLINT(build/include)
  2310. //=== HiddenValue/Private ======================================================
  2311. #include "nan_private.h" // NOLINT(build/include)
  2312. //=== Export ==================================================================
  2313. inline
  2314. void
  2315. Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name,
  2316. FunctionCallback f) {
  2317. HandleScope scope;
  2318. Set(target, New<v8::String>(name).ToLocalChecked(),
  2319. GetFunction(New<v8::FunctionTemplate>(f)).ToLocalChecked());
  2320. }
  2321. //=== Tap Reverse Binding =====================================================
  2322. struct Tap {
  2323. explicit Tap(v8::Local<v8::Value> t) : t_() {
  2324. HandleScope scope;
  2325. t_.Reset(To<v8::Object>(t).ToLocalChecked());
  2326. }
  2327. ~Tap() { t_.Reset(); } // not sure if neccessary
  2328. inline void plan(int i) {
  2329. HandleScope scope;
  2330. v8::Local<v8::Value> arg = New(i);
  2331. Call("plan", New(t_), 1, &arg);
  2332. }
  2333. inline void ok(bool isOk, const char *msg = NULL) {
  2334. HandleScope scope;
  2335. v8::Local<v8::Value> args[2];
  2336. args[0] = New(isOk);
  2337. if (msg) args[1] = New(msg).ToLocalChecked();
  2338. Call("ok", New(t_), msg ? 2 : 1, args);
  2339. }
  2340. inline void pass(const char * msg = NULL) {
  2341. HandleScope scope;
  2342. v8::Local<v8::Value> hmsg;
  2343. if (msg) hmsg = New(msg).ToLocalChecked();
  2344. Call("pass", New(t_), msg ? 1 : 0, &hmsg);
  2345. }
  2346. inline void end() {
  2347. HandleScope scope;
  2348. Call("end", New(t_), 0, NULL);
  2349. }
  2350. private:
  2351. Persistent<v8::Object> t_;
  2352. };
  2353. #define NAN_STRINGIZE2(x) #x
  2354. #define NAN_STRINGIZE(x) NAN_STRINGIZE2(x)
  2355. #define NAN_TEST_EXPRESSION(expression) \
  2356. ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression
  2357. #define NAN_EXPORT(target, function) Export(target, #function, function)
  2358. #undef TYPE_CHECK
  2359. //=== Generic Maybefication ===================================================
  2360. namespace imp {
  2361. template <typename T> struct Maybefier;
  2362. template <typename T> struct Maybefier<v8::Local<T> > {
  2363. inline static MaybeLocal<T> convert(v8::Local<T> v) {
  2364. return v;
  2365. }
  2366. };
  2367. template <typename T> struct Maybefier<MaybeLocal<T> > {
  2368. inline static MaybeLocal<T> convert(MaybeLocal<T> v) {
  2369. return v;
  2370. }
  2371. };
  2372. } // end of namespace imp
  2373. template <typename T, template <typename> class MaybeMaybe>
  2374. inline MaybeLocal<T>
  2375. MakeMaybe(MaybeMaybe<T> v) {
  2376. return imp::Maybefier<MaybeMaybe<T> >::convert(v);
  2377. }
  2378. //=== TypedArrayContents =======================================================
  2379. #include "nan_typedarray_contents.h" // NOLINT(build/include)
  2380. //=== JSON =====================================================================
  2381. #include "nan_json.h" // NOLINT(build/include)
  2382. } // end of namespace Nan
  2383. #endif // NAN_H_