src: deduplicate CHECK_EQ/CHECK_NE macros
[platform/upstream/nodejs.git] / src / node_buffer.cc
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23 #include "node.h"
24 #include "node_buffer.h"
25
26 #include "env.h"
27 #include "env-inl.h"
28 #include "smalloc.h"
29 #include "string_bytes.h"
30 #include "v8-profiler.h"
31 #include "v8.h"
32
33 #include <assert.h>
34 #include <string.h>
35 #include <limits.h>
36
37 #define MIN(a, b) ((a) < (b) ? (a) : (b))
38
39 #define CHECK_NOT_OOB(r)                                                    \
40   do {                                                                      \
41     if (!(r)) return env->ThrowRangeError("out of range index");            \
42   } while (0)
43
44 #define ARGS_THIS(argT)                                                     \
45   Local<Object> obj = argT;                                                 \
46   size_t obj_length = obj->GetIndexedPropertiesExternalArrayDataLength();   \
47   char* obj_data = static_cast<char*>(                                      \
48     obj->GetIndexedPropertiesExternalArrayData());                          \
49   if (obj_length > 0)                                                       \
50     assert(obj_data != NULL);
51
52 #define SLICE_START_END(start_arg, end_arg, end_max)                        \
53   size_t start;                                                             \
54   size_t end;                                                               \
55   CHECK_NOT_OOB(ParseArrayIndex(start_arg, 0, &start));                     \
56   CHECK_NOT_OOB(ParseArrayIndex(end_arg, end_max, &end));                   \
57   if (end < start) end = start;                                             \
58   CHECK_NOT_OOB(end <= end_max);                                            \
59   size_t length = end - start;
60
61 namespace node {
62 namespace Buffer {
63
64 using v8::ArrayBuffer;
65 using v8::Context;
66 using v8::EscapableHandleScope;
67 using v8::Function;
68 using v8::FunctionCallbackInfo;
69 using v8::FunctionTemplate;
70 using v8::Handle;
71 using v8::HandleScope;
72 using v8::Isolate;
73 using v8::Local;
74 using v8::Number;
75 using v8::Object;
76 using v8::String;
77 using v8::Uint32;
78 using v8::Value;
79
80
81 bool HasInstance(Handle<Value> val) {
82   return val->IsObject() && HasInstance(val.As<Object>());
83 }
84
85
86 bool HasInstance(Handle<Object> obj) {
87   if (!obj->HasIndexedPropertiesInExternalArrayData())
88     return false;
89   v8::ExternalArrayType type = obj->GetIndexedPropertiesExternalArrayDataType();
90   return type == v8::kExternalUnsignedByteArray;
91 }
92
93
94 char* Data(Handle<Value> val) {
95   assert(val->IsObject());
96   // Use a fully qualified name here to work around a bug in gcc 4.2.
97   // It mistakes an unadorned call to Data() for the v8::String::Data type.
98   return node::Buffer::Data(val.As<Object>());
99 }
100
101
102 char* Data(Handle<Object> obj) {
103   assert(obj->HasIndexedPropertiesInExternalArrayData());
104   return static_cast<char*>(obj->GetIndexedPropertiesExternalArrayData());
105 }
106
107
108 size_t Length(Handle<Value> val) {
109   assert(val->IsObject());
110   return Length(val.As<Object>());
111 }
112
113
114 size_t Length(Handle<Object> obj) {
115   assert(obj->HasIndexedPropertiesInExternalArrayData());
116   return obj->GetIndexedPropertiesExternalArrayDataLength();
117 }
118
119
120 Local<Object> New(Isolate* isolate, Handle<String> string, enum encoding enc) {
121   EscapableHandleScope scope(isolate);
122
123   size_t length = StringBytes::Size(isolate, string, enc);
124
125   Local<Object> buf = New(length);
126   char* data = Buffer::Data(buf);
127   StringBytes::Write(isolate, data, length, string, enc);
128
129   return scope.Escape(buf);
130 }
131
132
133 Local<Object> New(Isolate* isolate, size_t length) {
134   EscapableHandleScope handle_scope(isolate);
135   Local<Object> obj = Buffer::New(Environment::GetCurrent(isolate), length);
136   return handle_scope.Escape(obj);
137 }
138
139
140 // TODO(trevnorris): these have a flaw by needing to call the Buffer inst then
141 // Alloc. continue to look for a better architecture.
142 Local<Object> New(Environment* env, size_t length) {
143   EscapableHandleScope scope(env->isolate());
144
145   assert(length <= kMaxLength);
146
147   Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
148   Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
149
150   // TODO(trevnorris): done like this to handle HasInstance since only checks
151   // if external array data has been set, but would like to use a better
152   // approach if v8 provided one.
153   char* data;
154   if (length > 0) {
155     data = static_cast<char*>(malloc(length));
156     if (data == NULL)
157       FatalError("node::Buffer::New(size_t)", "Out Of Memory");
158   } else {
159     data = NULL;
160   }
161   smalloc::Alloc(env, obj, data, length);
162
163   return scope.Escape(obj);
164 }
165
166
167 Local<Object> New(Isolate* isolate, const char* data, size_t length) {
168   Environment* env = Environment::GetCurrent(isolate);
169   EscapableHandleScope handle_scope(env->isolate());
170   Local<Object> obj = Buffer::New(env, data, length);
171   return handle_scope.Escape(obj);
172 }
173
174
175 // TODO(trevnorris): for backwards compatibility this is left to copy the data,
176 // but for consistency w/ the other should use data. And a copy version renamed
177 // to something else.
178 Local<Object> New(Environment* env, const char* data, size_t length) {
179   EscapableHandleScope scope(env->isolate());
180
181   assert(length <= kMaxLength);
182
183   Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
184   Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
185
186   // TODO(trevnorris): done like this to handle HasInstance since only checks
187   // if external array data has been set, but would like to use a better
188   // approach if v8 provided one.
189   char* new_data;
190   if (length > 0) {
191     new_data = static_cast<char*>(malloc(length));
192     if (new_data == NULL)
193       FatalError("node::Buffer::New(const char*, size_t)", "Out Of Memory");
194     memcpy(new_data, data, length);
195   } else {
196     new_data = NULL;
197   }
198
199   smalloc::Alloc(env, obj, new_data, length);
200
201   return scope.Escape(obj);
202 }
203
204
205 Local<Object> New(Isolate* isolate,
206                   char* data,
207                   size_t length,
208                   smalloc::FreeCallback callback,
209                   void* hint) {
210   Environment* env = Environment::GetCurrent(isolate);
211   EscapableHandleScope handle_scope(env->isolate());
212   Local<Object> obj = Buffer::New(env, data, length, callback, hint);
213   return handle_scope.Escape(obj);
214 }
215
216
217 Local<Object> New(Environment* env,
218                   char* data,
219                   size_t length,
220                   smalloc::FreeCallback callback,
221                   void* hint) {
222   EscapableHandleScope scope(env->isolate());
223
224   assert(length <= kMaxLength);
225
226   Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
227   Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
228
229   smalloc::Alloc(env, obj, data, length, callback, hint);
230
231   return scope.Escape(obj);
232 }
233
234
235 Local<Object> Use(Isolate* isolate, char* data, uint32_t length) {
236   Environment* env = Environment::GetCurrent(isolate);
237   EscapableHandleScope handle_scope(env->isolate());
238   Local<Object> obj = Buffer::Use(env, data, length);
239   return handle_scope.Escape(obj);
240 }
241
242
243 Local<Object> Use(Environment* env, char* data, uint32_t length) {
244   EscapableHandleScope scope(env->isolate());
245
246   assert(length <= kMaxLength);
247
248   Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
249   Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
250
251   smalloc::Alloc(env, obj, data, length);
252
253   return scope.Escape(obj);
254 }
255
256
257 template <encoding encoding>
258 void StringSlice(const FunctionCallbackInfo<Value>& args) {
259   Environment* env = Environment::GetCurrent(args.GetIsolate());
260   HandleScope scope(env->isolate());
261
262   ARGS_THIS(args.This())
263   SLICE_START_END(args[0], args[1], obj_length)
264
265   args.GetReturnValue().Set(
266       StringBytes::Encode(env->isolate(), obj_data + start, length, encoding));
267 }
268
269
270 void BinarySlice(const FunctionCallbackInfo<Value>& args) {
271   StringSlice<BINARY>(args);
272 }
273
274
275 void AsciiSlice(const FunctionCallbackInfo<Value>& args) {
276   StringSlice<ASCII>(args);
277 }
278
279
280 void Utf8Slice(const FunctionCallbackInfo<Value>& args) {
281   StringSlice<UTF8>(args);
282 }
283
284
285 void Ucs2Slice(const FunctionCallbackInfo<Value>& args) {
286   StringSlice<UCS2>(args);
287 }
288
289
290 void HexSlice(const FunctionCallbackInfo<Value>& args) {
291   StringSlice<HEX>(args);
292 }
293
294
295 void Base64Slice(const FunctionCallbackInfo<Value>& args) {
296   StringSlice<BASE64>(args);
297 }
298
299
300 // bytesCopied = buffer.copy(target[, targetStart][, sourceStart][, sourceEnd]);
301 void Copy(const FunctionCallbackInfo<Value> &args) {
302   Environment* env = Environment::GetCurrent(args.GetIsolate());
303   HandleScope scope(env->isolate());
304
305   Local<Object> target = args[0]->ToObject();
306
307   if (!HasInstance(target))
308     return env->ThrowTypeError("first arg should be a Buffer");
309
310   ARGS_THIS(args.This())
311   size_t target_length = target->GetIndexedPropertiesExternalArrayDataLength();
312   char* target_data = static_cast<char*>(
313       target->GetIndexedPropertiesExternalArrayData());
314   size_t target_start;
315   size_t source_start;
316   size_t source_end;
317
318   CHECK_NOT_OOB(ParseArrayIndex(args[1], 0, &target_start));
319   CHECK_NOT_OOB(ParseArrayIndex(args[2], 0, &source_start));
320   CHECK_NOT_OOB(ParseArrayIndex(args[3], obj_length, &source_end));
321
322   // Copy 0 bytes; we're done
323   if (target_start >= target_length || source_start >= source_end)
324     return args.GetReturnValue().Set(0);
325
326   if (source_start > obj_length)
327     return env->ThrowRangeError("out of range index");
328
329   if (source_end - source_start > target_length - target_start)
330     source_end = source_start + target_length - target_start;
331
332   uint32_t to_copy = MIN(MIN(source_end - source_start,
333                              target_length - target_start),
334                              obj_length - source_start);
335
336   memmove(target_data + target_start, obj_data + source_start, to_copy);
337   args.GetReturnValue().Set(to_copy);
338 }
339
340
341 // buffer.fill(value[, start][, end]);
342 void Fill(const FunctionCallbackInfo<Value>& args) {
343   Environment* env = Environment::GetCurrent(args.GetIsolate());
344   HandleScope scope(env->isolate());
345
346   ARGS_THIS(args.This())
347   SLICE_START_END(args[1], args[2], obj_length)
348   args.GetReturnValue().Set(args.This());
349
350   if (args[0]->IsNumber()) {
351     int value = args[0]->Uint32Value() & 255;
352     memset(obj_data + start, value, length);
353     return;
354   }
355
356   String::Utf8Value at(args[0]);
357   size_t at_length = at.length();
358
359   // optimize single ascii character case
360   if (at_length == 1) {
361     int value = static_cast<int>((*at)[0]);
362     memset(obj_data + start, value, length);
363     return;
364   }
365
366   size_t in_there = at_length;
367   char* ptr = obj_data + start + at_length;
368
369   memcpy(obj_data + start, *at, MIN(at_length, length));
370
371   if (at_length >= length)
372     return;
373
374   while (in_there < length - in_there) {
375     memcpy(ptr, obj_data + start, in_there);
376     ptr += in_there;
377     in_there *= 2;
378   }
379
380   if (in_there < length) {
381     memcpy(ptr, obj_data + start, length - in_there);
382     in_there = length;
383   }
384 }
385
386
387 template <encoding encoding>
388 void StringWrite(const FunctionCallbackInfo<Value>& args) {
389   Environment* env = Environment::GetCurrent(args.GetIsolate());
390   HandleScope scope(env->isolate());
391
392   ARGS_THIS(args.This())
393
394   if (!args[0]->IsString())
395     return env->ThrowTypeError("Argument must be a string");
396
397   Local<String> str = args[0]->ToString();
398
399   if (encoding == HEX && str->Length() % 2 != 0)
400     return env->ThrowTypeError("Invalid hex string");
401
402   size_t offset;
403   size_t max_length;
404
405   CHECK_NOT_OOB(ParseArrayIndex(args[1], 0, &offset));
406   CHECK_NOT_OOB(ParseArrayIndex(args[2], obj_length - offset, &max_length));
407
408   max_length = MIN(obj_length - offset, max_length);
409
410   if (max_length == 0)
411     return args.GetReturnValue().Set(0);
412
413   if (encoding == UCS2)
414     max_length = max_length / 2;
415
416   if (offset >= obj_length)
417     return env->ThrowRangeError("Offset is out of bounds");
418
419   uint32_t written = StringBytes::Write(env->isolate(),
420                                         obj_data + offset,
421                                         max_length,
422                                         str,
423                                         encoding,
424                                         NULL);
425   args.GetReturnValue().Set(written);
426 }
427
428
429 void Base64Write(const FunctionCallbackInfo<Value>& args) {
430   StringWrite<BASE64>(args);
431 }
432
433
434 void BinaryWrite(const FunctionCallbackInfo<Value>& args) {
435   StringWrite<BINARY>(args);
436 }
437
438
439 void Utf8Write(const FunctionCallbackInfo<Value>& args) {
440   StringWrite<UTF8>(args);
441 }
442
443
444 void Ucs2Write(const FunctionCallbackInfo<Value>& args) {
445   StringWrite<UCS2>(args);
446 }
447
448
449 void HexWrite(const FunctionCallbackInfo<Value>& args) {
450   StringWrite<HEX>(args);
451 }
452
453
454 void AsciiWrite(const FunctionCallbackInfo<Value>& args) {
455   StringWrite<ASCII>(args);
456 }
457
458
459 static inline void Swizzle(char* start, unsigned int len) {
460   char* end = start + len - 1;
461   while (start < end) {
462     char tmp = *start;
463     *start++ = *end;
464     *end-- = tmp;
465   }
466 }
467
468
469 template <typename T, enum Endianness endianness>
470 void ReadFloatGeneric(const FunctionCallbackInfo<Value>& args) {
471   Environment* env = Environment::GetCurrent(args.GetIsolate());
472   bool doAssert = !args[1]->BooleanValue();
473   size_t offset;
474
475   CHECK_NOT_OOB(ParseArrayIndex(args[0], 0, &offset));
476
477   if (doAssert) {
478     size_t len = Length(args.This());
479     if (offset + sizeof(T) > len || offset + sizeof(T) < offset)
480       return env->ThrowRangeError("Trying to read beyond buffer length");
481   }
482
483   union NoAlias {
484     T val;
485     char bytes[sizeof(T)];
486   };
487
488   union NoAlias na;
489   const void* data = args.This()->GetIndexedPropertiesExternalArrayData();
490   const char* ptr = static_cast<const char*>(data) + offset;
491   memcpy(na.bytes, ptr, sizeof(na.bytes));
492   if (endianness != GetEndianness())
493     Swizzle(na.bytes, sizeof(na.bytes));
494
495   args.GetReturnValue().Set(na.val);
496 }
497
498
499 void ReadFloatLE(const FunctionCallbackInfo<Value>& args) {
500   ReadFloatGeneric<float, kLittleEndian>(args);
501 }
502
503
504 void ReadFloatBE(const FunctionCallbackInfo<Value>& args) {
505   ReadFloatGeneric<float, kBigEndian>(args);
506 }
507
508
509 void ReadDoubleLE(const FunctionCallbackInfo<Value>& args) {
510   ReadFloatGeneric<double, kLittleEndian>(args);
511 }
512
513
514 void ReadDoubleBE(const FunctionCallbackInfo<Value>& args) {
515   ReadFloatGeneric<double, kBigEndian>(args);
516 }
517
518
519 template <typename T, enum Endianness endianness>
520 uint32_t WriteFloatGeneric(const FunctionCallbackInfo<Value>& args) {
521   Environment* env = Environment::GetCurrent(args.GetIsolate());
522   bool doAssert = !args[2]->BooleanValue();
523
524   T val = static_cast<T>(args[0]->NumberValue());
525   size_t offset;
526
527   if (!ParseArrayIndex(args[1], 0, &offset)) {
528     env->ThrowRangeError("out of range index");
529     return 0;
530   }
531
532   if (doAssert) {
533     size_t len = Length(args.This());
534     if (offset + sizeof(T) > len || offset + sizeof(T) < offset) {
535       env->ThrowRangeError("Trying to write beyond buffer length");
536       return 0;
537     }
538   }
539
540   union NoAlias {
541     T val;
542     char bytes[sizeof(T)];
543   };
544
545   union NoAlias na = { val };
546   void* data = args.This()->GetIndexedPropertiesExternalArrayData();
547   char* ptr = static_cast<char*>(data) + offset;
548   if (endianness != GetEndianness())
549     Swizzle(na.bytes, sizeof(na.bytes));
550   memcpy(ptr, na.bytes, sizeof(na.bytes));
551   return offset + sizeof(na.bytes);
552 }
553
554
555 void WriteFloatLE(const FunctionCallbackInfo<Value>& args) {
556   args.GetReturnValue().Set(WriteFloatGeneric<float, kLittleEndian>(args));
557 }
558
559
560 void WriteFloatBE(const FunctionCallbackInfo<Value>& args) {
561   args.GetReturnValue().Set(WriteFloatGeneric<float, kBigEndian>(args));
562 }
563
564
565 void WriteDoubleLE(const FunctionCallbackInfo<Value>& args) {
566   args.GetReturnValue().Set(WriteFloatGeneric<double, kLittleEndian>(args));
567 }
568
569
570 void WriteDoubleBE(const FunctionCallbackInfo<Value>& args) {
571   args.GetReturnValue().Set(WriteFloatGeneric<double, kBigEndian>(args));
572 }
573
574
575 void ToArrayBuffer(const FunctionCallbackInfo<Value>& args) {
576   Environment* env = Environment::GetCurrent(args.GetIsolate());
577   HandleScope scope(env->isolate());
578
579   ARGS_THIS(args.This());
580   void* adata = malloc(obj_length);
581
582   if (adata == NULL) {
583     FatalError("node::Buffer::ToArrayBuffer("
584         "const FunctionCallbackInfo<v8::Value>&)",
585         "Out Of Memory");
586   }
587
588   memcpy(adata, obj_data, obj_length);
589
590   Local<ArrayBuffer> abuf = ArrayBuffer::New(env->isolate(), adata, obj_length);
591   args.GetReturnValue().Set(abuf);
592 }
593
594
595 void ByteLength(const FunctionCallbackInfo<Value> &args) {
596   Environment* env = Environment::GetCurrent(args.GetIsolate());
597   HandleScope scope(env->isolate());
598
599   if (!args[0]->IsString())
600     return env->ThrowTypeError("Argument must be a string");
601
602   Local<String> s = args[0]->ToString();
603   enum encoding e = ParseEncoding(env->isolate(), args[1], UTF8);
604
605   uint32_t size = StringBytes::Size(env->isolate(), s, e);
606   args.GetReturnValue().Set(size);
607 }
608
609
610 // pass Buffer object to load prototype methods
611 void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
612   Environment* env = Environment::GetCurrent(args.GetIsolate());
613   HandleScope scope(env->isolate());
614
615   assert(args[0]->IsFunction());
616
617   Local<Function> bv = args[0].As<Function>();
618   env->set_buffer_constructor_function(bv);
619   Local<Value> proto_v = bv->Get(env->prototype_string());
620
621   assert(proto_v->IsObject());
622
623   Local<Object> proto = proto_v.As<Object>();
624
625   NODE_SET_METHOD(proto, "asciiSlice", AsciiSlice);
626   NODE_SET_METHOD(proto, "base64Slice", Base64Slice);
627   NODE_SET_METHOD(proto, "binarySlice", BinarySlice);
628   NODE_SET_METHOD(proto, "hexSlice", HexSlice);
629   NODE_SET_METHOD(proto, "ucs2Slice", Ucs2Slice);
630   NODE_SET_METHOD(proto, "utf8Slice", Utf8Slice);
631
632   NODE_SET_METHOD(proto, "asciiWrite", AsciiWrite);
633   NODE_SET_METHOD(proto, "base64Write", Base64Write);
634   NODE_SET_METHOD(proto, "binaryWrite", BinaryWrite);
635   NODE_SET_METHOD(proto, "hexWrite", HexWrite);
636   NODE_SET_METHOD(proto, "ucs2Write", Ucs2Write);
637   NODE_SET_METHOD(proto, "utf8Write", Utf8Write);
638
639   NODE_SET_METHOD(proto, "readDoubleBE", ReadDoubleBE);
640   NODE_SET_METHOD(proto, "readDoubleLE", ReadDoubleLE);
641   NODE_SET_METHOD(proto, "readFloatBE", ReadFloatBE);
642   NODE_SET_METHOD(proto, "readFloatLE", ReadFloatLE);
643
644   NODE_SET_METHOD(proto, "writeDoubleBE", WriteDoubleBE);
645   NODE_SET_METHOD(proto, "writeDoubleLE", WriteDoubleLE);
646   NODE_SET_METHOD(proto, "writeFloatBE", WriteFloatBE);
647   NODE_SET_METHOD(proto, "writeFloatLE", WriteFloatLE);
648
649   NODE_SET_METHOD(proto, "toArrayBuffer", ToArrayBuffer);
650
651   NODE_SET_METHOD(proto, "copy", Copy);
652   NODE_SET_METHOD(proto, "fill", Fill);
653
654   // for backwards compatibility
655   proto->Set(env->offset_string(),
656              Uint32::New(env->isolate(), 0),
657              v8::ReadOnly);
658
659   assert(args[1]->IsObject());
660
661   Local<Object> internal = args[1].As<Object>();
662
663   internal->Set(env->byte_length_string(),
664                 FunctionTemplate::New(
665                     env->isolate(), ByteLength)->GetFunction());
666 }
667
668
669 void Initialize(Handle<Object> target,
670                 Handle<Value> unused,
671                 Handle<Context> context) {
672   Environment* env = Environment::GetCurrent(context);
673   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "setupBufferJS"),
674               FunctionTemplate::New(env->isolate(), SetupBufferJS)
675                   ->GetFunction());
676 }
677
678
679 }  // namespace Buffer
680 }  // namespace node
681
682 NODE_MODULE_CONTEXT_AWARE_BUILTIN(buffer, node::Buffer::Initialize)