source: trunk/FACT++/src/InterpreterV8.cc@ 14553

Last change on this file since 14553 was 14548, checked in by tbretz, 12 years ago
Do only escape string arguments in the command string.
File size: 31.1 KB
Line 
1#include "InterpreterV8.h"
2
3#ifdef HAVE_SQL
4#include "Database.h"
5#endif
6
7#include <boost/tokenizer.hpp>
8
9InterpreterV8 *InterpreterV8::This = 0;
10
11#ifdef HAVE_V8
12
13#include <v8.h>
14#include <fstream>
15#include <sstream>
16#include <iomanip>
17
18using namespace std;
19using namespace v8;
20
21bool InterpreterV8::ReportException(TryCatch* try_catch)
22{
23 if (!try_catch->CanContinue())
24 return false;
25
26 const HandleScope handle_scope;
27
28 const String::Utf8Value exception(try_catch->Exception());
29
30 if (*exception && string(*exception)=="exit")
31 return true;
32 if (*exception && string(*exception)=="null")
33 return false;
34
35 const Handle<Message> message = try_catch->Message();
36 if (message.IsEmpty())
37 return false;
38
39 // Print (filename):(line number): (message).
40 const String::Utf8Value filename(message->GetScriptResourceName());
41
42 ostringstream out;
43
44 if (*filename)
45 out << *filename << ": ";
46 out << "l." << message->GetLineNumber();
47 if (*exception)
48 out << ": " << *exception;
49
50 JsException(out.str());
51
52 // Print line of source code.
53 const String::Utf8Value sourceline(message->GetSourceLine());
54 if (*sourceline)
55 JsException(*sourceline);
56
57 // Print wavy underline (GetUnderline is deprecated).
58 const int start = message->GetStartColumn();
59 const int end = message->GetEndColumn();
60
61 out.str("");
62 if (start>0)
63 out << setfill(' ') << setw(start) << ' ';
64 out << setfill('^') << setw(end-start) << '^';
65
66 JsException(out.str());
67
68 String::Utf8Value stack_trace(try_catch->StackTrace());
69 if (stack_trace.length()<=0)
70 return false;
71
72 //if (*stack_trace)
73 // JsException(string("\n")+*stack_trace);
74
75 return false;
76}
77
78// Executes a string within the current v8 context.
79bool InterpreterV8::ExecuteStringNT(const Handle<String> &code, const Handle<Value> &file)
80{
81 if (code.IsEmpty())
82 return true;
83
84 const HandleScope handle_scope;
85
86 const Handle<Script> script = Script::Compile(code, file);
87 if (script.IsEmpty())
88 return false;
89
90 const Handle<Value> result = script->Run();
91 if (result.IsEmpty())
92 return false;
93
94 // If all went well and the result wasn't undefined then print
95 // the returned value.
96 if (!result->IsUndefined())
97 JsResult(*String::Utf8Value(result));
98
99 return true;
100}
101
102bool InterpreterV8::ExecuteCode(const Handle<String> &code, const Handle<Value> &file)
103{
104 TryCatch exception;
105
106 const bool rc = ExecuteStringNT(code, file);
107
108 // Check if this is a termination exception
109 //if (!exception.CanContinue())
110 // return false;
111
112 if (exception.HasCaught())
113 return ReportException(&exception);
114
115 return rc;
116}
117
118bool InterpreterV8::ExecuteCode(const string &code, const string &file)
119{
120 return ExecuteCode(String::New(code.c_str(), code.size()),
121 String::New(file.c_str()));
122}
123
124bool InterpreterV8::ExecuteFile(const string &name)
125{
126 ifstream fin(name.c_str());
127 if (!fin)
128 {
129 JsException("Error - Could not open file '"+name+"'");
130 return false;
131 }
132
133 string buffer;
134 if (!getline(fin, buffer, '\0'))
135 return true;
136
137 if (fin.fail())
138 {
139 JsException("Error - reading file.");
140 return false;
141 }
142
143 return ExecuteCode(buffer, name);
144}
145
146Handle<Value> InterpreterV8::FuncWait(const Arguments& args)
147{
148 if (args.Length()!=2 && args.Length()!=3)
149 return ThrowException(String::New("Number of arguments must be 2 or 3."));
150
151 if (!args[0]->IsString())
152 return ThrowException(String::New("Argument 1 not a string."));
153
154 if (!args[1]->IsInt32() && !args[1]->IsString())
155 return ThrowException(String::New("Argument 2 not an int32 and not a string."));
156
157 if (args.Length()==3 && !args[2]->IsUint32())
158 return ThrowException(String::New("Argument 3 not an uint32."));
159
160 // Using a Javascript function has the advantage that it is fully
161 // interruptable without the need of C++ code
162
163 const string index = args[1]->IsInt32() ? "s.index" : "s.name";
164 const bool timeout = args.Length()==3;
165 const string arg0 = *String::Utf8Value(args[0]);
166 const string state = args[1]->IsString() ? *String::Utf8Value(args[1]) : "";
167 const string arg1 = args[1]->IsString() ? ("\""+state+"\"") : to_string(args[1]->Int32Value());
168
169 if (arg0.find_first_of("\"'")!=string::npos)
170 return ThrowException(String::New("Server name must not contain quotation marks."));
171
172 if (args[1]->IsString())
173 if (state.find_first_of("\"'")!=string::npos)
174 return ThrowException(String::New("State name must not contain quotation marks."));
175
176 string code = "(function(name,state,ms)"
177 "{";
178 if (timeout)
179 code += "var t = new Date();";
180 code += "while (1)"
181 "{"
182 "var s = dim.state(name);"
183 "if(!"+index+")throw 'Waitig for state "+arg1+" of server "+arg0+" failed.';"
184 "if(state=="+index+")return true;";
185 if (timeout)
186 code += "if((new Date()-t)>ms)return false;";
187
188 code += "dim.sleep();"
189 "}"
190 "})('"+arg0+"',"+arg1;
191 if (timeout)
192 code += "," + to_string(args[2]->Int32Value());
193 code += ");";
194
195 const HandleScope handle_scope;
196
197 // It is not strictly necessary to catch the exception, instead
198 // script->Run() could just be returned, but catching the
199 // exception allow to print the position in the file in
200 // the exception handler instead of just the posiiton in the script.
201 TryCatch exception;
202
203 const Handle<Script> script = Script::Compile(String::New(code.c_str()));
204 const Handle<Value> result = script->Run();
205
206 return exception.HasCaught() ? exception.ReThrow() : result;
207
208 /*
209 const string server = *String::Utf8Value(args[0]);
210 const int32_t state = args[1]->Int32Value();
211 const uint32_t millisec = args.Length()==3 ? args[2]->Int32Value() : 0;
212
213 const int rc = JsWait(server, state, millisec);
214
215 if (rc==0 || rc==1)
216 return Boolean::New(rc);
217
218 return ThrowException(String::New(("Waitig for state "+to_string(state)+" of server '"+server+"' failed.").c_str()));
219 */
220}
221
222Handle<Value> InterpreterV8::FuncSend(const Arguments& args)
223{
224 if (args.Length()==0)
225 return ThrowException(String::New("Number of arguments must be at least 1."));
226
227 if (!args[0]->IsString())
228 return ThrowException(String::New("Argument 1 must be a string."));
229
230 const HandleScope handle_scope;
231
232 const String::Utf8Value str(args[0]);
233
234 string command = *str;
235
236 // Escape all string arguments. All others can be kept as they are.
237 for (int i=1; i<args.Length(); i++)
238 {
239 const String::Utf8Value arg(args[i]);
240 if (args[i]->IsString())
241 command += " \""+string(*arg)+"\"";
242 else
243 command += " "+string(*arg);
244 }
245
246 return Boolean::New(JsSend(command));
247}
248
249Handle<Value> InterpreterV8::FuncSleep(const Arguments& args)
250{
251 if (args.Length()==0)
252 {
253 // Theoretically, the CPU usage can be reduced by maybe a factor
254 // of four using a larger value, but this also means that the
255 // JavaScript is locked for a longer time.
256 usleep(1000);
257 return Undefined();
258 }
259
260 if (args.Length()!=1)
261 return ThrowException(String::New("Number of arguments must be exactly 1."));
262
263 if (!args[0]->IsUint32())
264 return ThrowException(String::New("Argument 1 must be an uint32."));
265
266 // Using a Javascript function has the advantage that it is fully
267 // interruptable without the need of C++ code
268
269 const string code =
270 "(function(){"
271 "var t=new Date();"
272 "while ((new Date()-t)<"+to_string(args[0]->Int32Value())+") dim.sleep();"
273 "})();";
274
275 const HandleScope handle_scope;
276
277 const Handle<Script> script = Script::Compile(String::New(code.c_str()));
278 return script->Run();
279
280 //JsSleep(args[0]->Int32Value());
281 //return Undefined();
282}
283
284Handle<Value> InterpreterV8::FuncState(const Arguments& args)
285{
286 if (args.Length()!=1)
287 return ThrowException(String::New("Number of arguments must be exactly 1."));
288
289 if (!args[0]->IsString())
290 return ThrowException(String::New("Argument 1 must be a string."));
291
292 // Return state.name/state.index
293
294 const String::Utf8Value str(args[0]);
295
296 const State rc = JsState(*str);
297
298 //if (rc.first<=-256)
299 // return Undefined();
300
301 HandleScope handle_scope;
302
303 // It is important to catch the exception thrown
304 // by Date::New in case of thread termination!
305 Local<Value> date;
306 {
307 TryCatch exception;
308 date = Date::New(rc.time.JavaDate());
309 if (exception.HasCaught())
310 return exception.ReThrow();
311 }
312
313 Handle<ObjectTemplate> obj = ObjectTemplate::New();
314 obj->Set(String::New("time"), date);
315 obj->Set(String::New("index"), rc.index<=-256?Undefined():Integer::New(rc.index), ReadOnly);
316 obj->Set(String::New("name"), rc.index<=-256?Undefined():String::New(rc.name.c_str()), ReadOnly);
317 //obj->Set(String::New("toString"), String::New(("[Object state "+string(*str)+":"+to_string(rc.index)+"]").c_str()));
318
319 return handle_scope.Close(obj->NewInstance());
320}
321
322Handle<Value> InterpreterV8::FuncExit(const Arguments &)
323{
324 V8::TerminateExecution(fThreadId);
325 return ThrowException(String::New("exit"));
326/*
327 if (args.Length()!=1)
328 return ThrowException(String::New("Number of arguments must be exactly 1."));
329
330 if (!args[0]->IsUint32())
331 return ThrowException(String::New("Argument 1 must be an uint32."));
332
333 const HandleScope handle_scope;
334
335 JsSleep(args[0]->Int32Value());
336*/
337 return Undefined();
338}
339
340// The callback that is invoked by v8 whenever the JavaScript 'print'
341// function is called. Prints its arguments on stdout separated by
342// spaces and ending with a newline.
343Handle<Value> InterpreterV8::FuncPrint(const Arguments& args)
344{
345 for (int i=0; i<args.Length(); i++)
346 {
347 const HandleScope handle_scope;
348
349 const String::Utf8Value str(args[i]);
350 if (*str)
351 JsPrint(*str);
352 }
353 return Undefined();
354}
355
356Handle<Value> InterpreterV8::FuncAlarm(const Arguments& args)
357{
358 for (int i=0; i<args.Length(); i++)
359 {
360 const HandleScope handle_scope;
361
362 const String::Utf8Value str(args[i]);
363 if (*str)
364 JsAlarm(*str);
365 }
366
367 if (args.Length()==0)
368 JsAlarm();
369
370 return Undefined();
371}
372
373Handle<Value> InterpreterV8::FuncOut(const Arguments& args)
374{
375 for (int i=0; i<args.Length(); i++)
376 {
377 const HandleScope handle_scope;
378
379 const String::Utf8Value str(args[i]);
380 if (*str)
381 JsOut(*str);
382 }
383 return Undefined();
384}
385
386// The callback that is invoked by v8 whenever the JavaScript 'load'
387// function is called. Loads, compiles and executes its argument
388// JavaScript file.
389Handle<Value> InterpreterV8::FuncInclude(const Arguments& args)
390{
391 for (int i=0; i<args.Length(); i++)
392 {
393 const HandleScope handle_scope;
394
395 const String::Utf8Value file(args[i]);
396 if (*file == NULL)
397 return ThrowException(String::New(("Error loading file '"+string(*file)+"'").c_str()));
398
399 if (!ExecuteFile(*file))
400 return ThrowException(String::New(("Execution of '"+string(*file)+"' failed").c_str()));
401 }
402 return Undefined();
403}
404
405Handle<Value> InterpreterV8::FuncVersion(const Arguments&)
406{
407 return String::New(V8::GetVersion());
408}
409
410Handle<Value> InterpreterV8::FuncDbClose(const Arguments &args)
411{
412 HandleScope handle_scope;
413
414 void *ptr = Handle<External>::Cast(args.This()->GetInternalField(0))->Value();
415 if (!ptr)
416 return Boolean::New(false);
417
418#ifdef HAVE_SQL
419 Database *db = reinterpret_cast<Database*>(ptr);
420 auto it = find(fDatabases.begin(), fDatabases.end(), db);
421 fDatabases.erase(it);
422 delete db;
423#endif
424
425 args.This()->SetInternalField(0, External::New(0));
426
427 return Boolean::New(true);
428}
429Handle<Value> InterpreterV8::FuncDbQuery(const Arguments &args)
430{
431 if (args.Length()!=1)
432 return ThrowException(String::New("Number of arguments must be exactly 1."));
433
434 if (!args[0]->IsString())
435 return ThrowException(String::New("Both arguments must be a string."));
436
437 HandleScope handle_scope;
438
439 void *ptr = Handle<External>::Cast(args.This()->GetInternalField(0))->Value();
440 if (!ptr)
441 return Undefined();
442
443 const String::Utf8Value query(args[0]);
444
445#ifdef HAVE_SQL
446 try
447 {
448 Database *db = reinterpret_cast<Database*>(ptr);
449
450 const mysqlpp::StoreQueryResult res = db->query(*query).store();
451
452 Handle<Array> ret = Array::New();
453 ret->Set(String::New("table"), String::New(res.table()), ReadOnly);
454
455 Handle<Array> cols = Array::New();
456
457 int irow=0;
458 for (vector<mysqlpp::Row>::const_iterator it=res.begin(); it<res.end(); it++)
459 {
460 Handle<Array> row = Array::New();
461
462 const mysqlpp::FieldNames *list = it->field_list().list;
463
464 for (size_t i=0; i<it->size(); i++)
465 {
466 const Handle<Value> name = String::New((*list)[i].c_str());
467 if (irow==0)
468 cols->Set(Integer::NewFromUnsigned(i), name, ReadOnly);
469
470 if ((*it)[i].is_null())
471 {
472 row->Set(name, Undefined(), ReadOnly);
473 continue;
474 }
475
476 const string sql_type = (*it)[i].type().sql_name();
477
478 const bool uns = sql_type.find("UNSIGNED")==string::npos;
479
480 if (sql_type.find("BIGINT")!=string::npos)
481 {
482 if (uns)
483 {
484 const uint64_t val = (uint64_t)(*it)[i];
485 if (val>UINT32_MAX)
486 row->Set(name, Number::New(val), ReadOnly);
487 else
488 row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
489 }
490 else
491 {
492 const int64_t val = (int64_t)(*it)[i];
493 if (val<INT32_MIN || val>INT32_MAX)
494 row->Set(name, Number::New(val), ReadOnly);
495 else
496 row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
497 }
498 continue;
499 }
500
501 // 32 bit
502 if (sql_type.find("INT")!=string::npos)
503 {
504 if (uns)
505 row->Set(name, Integer::NewFromUnsigned((uint32_t)(*it)[i]), ReadOnly);
506 else
507 row->Set(name, Integer::New((int32_t)(*it)[i]), ReadOnly);
508 }
509
510 if (sql_type.find("BOOL")!=string::npos )
511 {
512 row->Set(name, Boolean::New((bool)(*it)[i]), ReadOnly);
513 continue;
514 }
515
516 if (sql_type.find("FLOAT")!=string::npos)
517 {
518 ostringstream val;
519 val << setprecision(7) << (float)(*it)[i];
520 row->Set(name, Number::New(stod(val.str())), ReadOnly);
521 continue;
522
523 }
524 if (sql_type.find("DOUBLE")!=string::npos)
525 {
526 row->Set(name, Number::New((double)(*it)[i]), ReadOnly);
527 continue;
528 }
529
530 if (sql_type.find("CHAR")!=string::npos ||
531 sql_type.find("TEXT")!=string::npos)
532 {
533 row->Set(name, String::New((const char*)(*it)[i]), ReadOnly);
534 continue;
535 }
536
537 time_t date = 0;
538 if (sql_type.find("TIMESTAMP")!=string::npos)
539 date = mysqlpp::Time((*it)[i]);
540
541 if (sql_type.find("DATETIME")!=string::npos)
542 date = mysqlpp::DateTime((*it)[i]);
543
544 if (sql_type.find(" DATE ")!=string::npos)
545 date = mysqlpp::Date((*it)[i]);
546
547 if (date>0)
548 {
549 // It is important to catch the exception thrown
550 // by Date::New in case of thread termination!
551 TryCatch exception;
552 Local<Value> val = Date::New(date*1000);
553 if (exception.HasCaught())
554 return exception.ReThrow();
555 //if (V8::IsExecutionTerminating())
556 // return Undefined();
557
558 row->Set(name, val, ReadOnly);
559 }
560 }
561
562 ret->Set(Integer::NewFromUnsigned(irow++), row, ReadOnly);
563 }
564
565 if (irow>0)
566 ret->Set(String::New("cols"), cols, ReadOnly);
567
568 return handle_scope.Close(ret);
569 }
570 catch (const exception &e)
571 {
572 return ThrowException(String::New(e.what()));
573 }
574#endif
575}
576
577Handle<Value> InterpreterV8::FuncDatabase(const Arguments &args)
578{
579 if (args.Length()!=1)
580 return ThrowException(String::New("Number of arguments must be exactly 1."));
581
582 if (!args[0]->IsString())
583 return ThrowException(String::New("Argument 1 must be a string."));
584
585 HandleScope handle_scope;
586
587 const String::Utf8Value database(args[0]);
588 const String::Utf8Value query (args[1]);
589
590#ifdef HAVE_SQL
591 try
592 {
593 Database *db = new Database(*database);
594 fDatabases.push_back(db);
595
596 Handle<ObjectTemplate> tem = ObjectTemplate::New();
597 tem->Set(String::New("user"), String::New(db->user.c_str()), ReadOnly);
598 tem->Set(String::New("server"), String::New(db->server.c_str()), ReadOnly);
599 tem->Set(String::New("database"), String::New(db->db.c_str()), ReadOnly);
600 tem->Set(String::New("port"), db->port==0?Undefined():Integer::NewFromUnsigned(db->port), ReadOnly);
601 tem->Set(String::New("query"), FunctionTemplate::New(WrapDbQuery), ReadOnly);
602 tem->Set(String::New("close"), FunctionTemplate::New(WrapDbClose), ReadOnly);
603 tem->SetInternalFieldCount(1);
604
605 Handle<Object> obj = tem->NewInstance();
606 obj->SetInternalField(0, External::New(db));
607
608 return handle_scope.Close(obj);
609 }
610 catch (const exception &e)
611 {
612 return ThrowException(String::New(e.what()));
613 }
614#endif
615}
616
617Handle<Value> InterpreterV8::Convert(char type, const char* &ptr)
618{
619 // Dim values are always unsigned per (FACT++) definition
620 switch (type)
621 {
622 case 'F':
623 {
624 // Remove the "imprecision" effect coming from casting a float to
625 // a double and then showing it with double precision
626 ostringstream val;
627 val << setprecision(7) << *reinterpret_cast<const float*>(ptr);
628 Handle<Value> v=Number::New(stod(val.str()));
629 ptr+=4;
630 return v;
631 }
632 case 'D': { Handle<Value> v=Number::New(*reinterpret_cast<const double*>(ptr)); ptr+=8; return v; }
633 case 'I':
634 case 'L': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint32_t*>(ptr)); ptr += 4; return v; }
635 case 'X':
636 {
637 const uint64_t val = *reinterpret_cast<const uint64_t*>(ptr);
638 ptr += 8;
639 if (val>UINT32_MAX)
640 return Number::New(val);
641 return Integer::NewFromUnsigned(val);
642 }
643 case 'S': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint16_t*>(ptr)); ptr += 2; return v; }
644 case 'C': { Handle<Value> v=Integer::NewFromUnsigned((uint16_t)*reinterpret_cast<const uint8_t*>(ptr)); ptr += 1; return v; }
645 case ':': { Handle<Value> v=String::New(ptr); return v; }
646 }
647 return Undefined();
648}
649
650Handle<Value> InterpreterV8::FuncClose(const Arguments &args)
651{
652 const HandleScope handle_scope;
653
654 //const void *ptr = Local<External>::Cast(args.Holder()->GetInternalField(0))->Value();
655
656 const String::Utf8Value str(args.Holder()->Get(String::New("name")));
657
658 const auto it = fReverseMap.find(*str);
659 if (it!=fReverseMap.end())
660 {
661 it->second.Dispose();
662 fReverseMap.erase(it);
663 }
664
665 return Boolean::New(JsUnsubscribe(*str));
666}
667
668Handle<Value> InterpreterV8::ConvertEvent(const EventImp *evt, uint64_t counter, const char *str)
669{
670 Local<Value> date;
671
672 // It is important to catch the exception thrown
673 // by Date::New in case of thread termination!
674 {
675 TryCatch exception;
676 date = Date::New(evt->GetJavaDate());
677 if (exception.HasCaught())
678 return exception.ReThrow();
679 }
680
681 const vector<Description> vec = JsDescription(str);
682
683 Handle<Array> ret = Array::New();
684 ret->Set(String::New("name"), String::New(str), ReadOnly);
685 ret->Set(String::New("format"), String::New(evt->GetFormat().c_str()), ReadOnly);
686 ret->Set(String::New("named"), Boolean::New(vec.size()>0), ReadOnly);
687 ret->Set(String::New("qos"), Integer::New(evt->GetQoS()), ReadOnly);
688 ret->Set(String::New("size"), Integer::New(evt->GetSize()), ReadOnly);
689 ret->Set(String::New("counter"), Integer::New(counter), ReadOnly);
690 ret->Set(String::New("time"), date, ReadOnly);
691
692 typedef boost::char_separator<char> separator;
693 const boost::tokenizer<separator> tokenizer(evt->GetFormat(), separator(";:"));
694
695 const vector<string> tok(tokenizer.begin(), tokenizer.end());
696
697 Handle<Array> obj = tok.size()==1 ? ret : Array::New();
698
699 const char *ptr = evt->GetText();
700 try
701 {
702 size_t pos = 1;
703 for (auto it=tok.begin(); it!=tok.end(); it++, pos++)
704 {
705 if (ptr>=evt->GetText())
706 return ret;
707
708 char type = (*it)[0];
709 it++;
710
711 if (it==tok.end() && type=='C')
712 type = ':';
713
714 if (it==tok.end() && type!=':')
715 return Exception::Error(String::New(("Format string invalid '"+evt->GetFormat()+"'").c_str()));
716
717 string name = pos<vec.size() ? vec[pos].name : "";
718 if (tok.size()==1)
719 name = "data";
720
721 const uint32_t cnt = it==tok.end() ? 1 : stoi(it->c_str());
722
723 if (cnt==1)
724 {
725 const Handle<Value> v = Convert(type, ptr);
726 if (tok.size()>1)
727 obj->Set(pos-1, v);
728 if (!name.empty())
729 obj->Set(String::New(name.c_str()), v);
730 }
731 else
732 {
733 Handle<Array> a = Array::New(cnt);
734 for (uint32_t i=0; i<cnt; i++)
735 a->Set(i, Convert(type, ptr));
736 if (tok.size()>1)
737 obj->Set(pos-1, a);
738 if (!name.empty())
739 obj->Set(String::New(name.c_str()), a);
740 }
741
742 if (it==tok.end())
743 break;
744 }
745
746 if (tok.size()>1)
747 ret->Set(String::New("data"), obj, ReadOnly);
748
749 return ret;
750 }
751 catch (...)
752 {
753 return Exception::Error(String::New(("Format string conversion '"+evt->GetFormat()+"' failed.").c_str()));
754 }
755}
756
757Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
758{
759 HandleScope handle_scope;
760
761 const String::Utf8Value str(args.Holder()->Get(String::New("name")));
762
763 const pair<uint64_t, EventImp *> p = JsGetEvent(*str);
764
765 const EventImp *evt = p.second;
766 if (!evt)
767 return Undefined();
768
769 //if (counter==cnt)
770 // return info.Holder();//Holder()->Get(String::New("data"));
771
772 Handle<Value> ret = ConvertEvent(evt, p.first, *str);
773 return ret->IsNativeError() ? ThrowException(ret) : handle_scope.Close(ret);
774}
775
776// This is a callback from the RemoteControl piping event handling
777// to the java script ---> in test phase!
778void InterpreterV8::JsHandleEvent(const EventImp &evt, uint64_t cnt, const string &service)
779{
780 if (fThreadId<0)
781 return;
782
783 const auto it = fReverseMap.find(service);
784 if (it==fReverseMap.end())
785 return;
786
787 Locker locker;
788
789 const HandleScope handle_scope;
790
791 Handle<Object> obj = it->second;
792 if (obj.IsEmpty())
793 return;
794
795 const Handle<String> onchange = String::New("onchange");
796 if (!obj->Has(onchange))
797 return;
798
799 const Handle<Value> val = obj->Get(onchange);
800 if (!val->IsFunction())
801 return;
802
803 // -------------------------------------------------------------------
804 // We are not in a context... we need to get into one for Array::New
805
806 Persistent<Context> context = Context::New();
807 if (context.IsEmpty())
808 return;
809
810 const Context::Scope scope(context);
811
812 // -------------------------------------------------------------------
813
814 TryCatch exception;
815
816 Handle<Value> ret = ConvertEvent(&evt, cnt, service.c_str());
817 if (ret->IsArray())
818 {
819 Handle<Array> data = Handle<Array>::Cast(ret);
820 Handle<Value> args[] = { data };
821
822 Handle<Function>::Cast(val)->Call(obj, 1, args);
823 }
824
825 if (exception.HasCaught())
826 ReportException(&exception);
827
828 if (ret->IsNativeError())
829 JsException(service+".onchange callback - "+*String::Utf8Value(ret));
830
831 context.Dispose();
832
833 if (ret->IsUndefined() || ret->IsNativeError() || exception.HasCaught())
834 V8::TerminateExecution(fThreadId);
835}
836
837/*
838void Cleanup( Persistent<Value> object, void *parameter )
839{
840 cout << "======================> RemoveMyObj()" << endl;
841}*/
842
843Handle<Value> InterpreterV8::FuncOpen(const Arguments &args)
844{
845 if (args.Length()!=1)
846 return ThrowException(String::New("Number of arguments must be exactly 1."));
847
848 if (!args[0]->IsString())
849 return ThrowException(String::New("Argument 1 must be a string."));
850
851 //if (!args.IsConstructCall())
852 // return ThrowException(String::New("Must be used as constructor."));
853
854 HandleScope handle_scope;
855
856 const String::Utf8Value str(args[0]);
857
858 void *ptr = JsSubscribe(*str);
859 if (ptr==0)
860 return ThrowException(String::New(("Subscription to '"+string(*str)+"' already exists.").c_str()));
861
862 Handle<ObjectTemplate> tem = ObjectTemplate::New();
863 tem->Set(String::New("get"), FunctionTemplate::New(WrapGetData), ReadOnly);
864 tem->Set(String::New("close"), FunctionTemplate::New(WrapClose), ReadOnly);
865 tem->Set(String::New("name"), String::New(*str), ReadOnly);
866 tem->SetInternalFieldCount(1);
867 //tem->Set(String::New("toString"), String::New(("[object Dim "+string(*str)+"]").c_str()), ReadOnly);
868
869 Handle<Object> obj = tem->NewInstance();
870 obj->SetInternalField(0, External::New(ptr));
871
872 fReverseMap[*str] = Persistent<Object>::New(obj);
873
874 return handle_scope.Close(obj);
875
876 // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
877 // obj.MakeWeak((void*)1, Cleanup);
878 // return obj;
879}
880
881bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
882{
883 Locker locker;
884 fThreadId = V8::GetCurrentThreadId();
885
886 JsLoad(filename);
887
888 HandleScope handle_scope;
889
890 // Create a template for the global object.
891 Handle<ObjectTemplate> dim = ObjectTemplate::New();
892 dim->Set(String::New("print"), FunctionTemplate::New(WrapPrint), ReadOnly);
893 dim->Set(String::New("alarm"), FunctionTemplate::New(WrapAlarm), ReadOnly);
894 dim->Set(String::New("out"), FunctionTemplate::New(WrapOut), ReadOnly);
895 dim->Set(String::New("wait"), FunctionTemplate::New(WrapWait), ReadOnly);
896 dim->Set(String::New("send"), FunctionTemplate::New(WrapSend), ReadOnly);
897 dim->Set(String::New("state"), FunctionTemplate::New(WrapState), ReadOnly);
898 dim->Set(String::New("sleep"), FunctionTemplate::New(WrapSleep), ReadOnly);
899 dim->Set(String::New("open"), FunctionTemplate::New(WrapOpen), ReadOnly);
900 dim->Set(String::New("database"), FunctionTemplate::New(WrapDatabase), ReadOnly);
901
902 Handle<ObjectTemplate> global = ObjectTemplate::New();
903 global->Set(String::New("dim"), dim, ReadOnly);
904 global->Set(String::New("include"), FunctionTemplate::New(WrapInclude), ReadOnly);
905 global->Set(String::New("exit"), FunctionTemplate::New(WrapExit), ReadOnly);
906 global->Set(String::New("version"), FunctionTemplate::New(InterpreterV8::FuncVersion), ReadOnly);
907
908 // Persistent
909 Persistent<Context> context = Context::New(NULL, global);
910 if (context.IsEmpty())
911 {
912 //printf("Error creating context\n");
913 return false;
914 }
915
916 Context::Scope scope(context);
917
918 Handle<Array> args = Array::New(map.size());
919 for (auto it=map.begin(); it!=map.end(); it++)
920 args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
921 context->Global()->Set(String::New("$"), args, ReadOnly);
922 context->Global()->Set(String::New("arg"), args, ReadOnly);
923
924 JsStart(filename);
925
926 //context->Enter();
927 Locker::StartPreemption(10);
928 const bool rc = ExecuteFile(filename);
929
930 // -----
931 // This is how an exit handler could look like, but there is no way to interrupt it
932 // -----
933 // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
934 // if (!obj.IsEmpty())
935 // {
936 // Handle<Value> onexit = obj->Get(String::New("onexit"));
937 // if (!onexit->IsUndefined())
938 // Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
939 // // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
940 // }
941
942 Locker::StopPreemption();
943 //context->Exit();
944
945 for (auto it=fReverseMap.begin(); it!=fReverseMap.end(); it++)
946 it->second.Dispose();
947 fReverseMap.clear();
948
949 context.Dispose();
950
951#ifdef HAVE_SQL
952 for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
953 delete *it;
954 fDatabases.clear();
955#endif
956
957 JsEnd(filename);
958
959 return rc;
960}
961
962void InterpreterV8::JsStop()
963{
964 Locker locker;
965
966 //cout << "Terminate " << fThreadId << endl;
967 if (This->fThreadId>=0)
968 V8::TerminateExecution(This->fThreadId);
969 //cout << "Terminate " << fThreadId << endl;
970
971 //Unlocker unlocker;
972}
973
974#endif
975
976/*
977#0 0x00007ffff5ae0e62 in ?? () from /usr/lib/libv8.so.3.7.12.22
978#1 0x00007ffff5ae1969 in ?? () from /usr/lib/libv8.so.3.7.12.22
979#2 0x00007ffff5af1976 in v8::V8::Dispose() () from /usr/lib/libv8.so.3.7.12.22
980#3 0x0000000000426459 in RemoteControl<Console>::~RemoteControl() ()
981#4 0x00007ffff51e9901 in __run_exit_handlers (status=3, listp=0x7ffff5566688, run_list_atexi
982#5 0x00007ffff51e9985 in __GI_exit (status=<optimized out>) at exit.c:100
983#6 0x00000000004374db in DimErrorRedirecter::exitHandler(int) ()
984#7 0x00007ffff66bce72 in exit_user_routine () from /home/fact/FACT++.in-run-fad-loss/.libs/l
985#8 0x00007ffff6477387 in recv_dns_dis_rout () from /home/fact/FACT++.in-run-fad-loss/.libs/l
986#9 0x00007ffff647b79f in ast_read_h () from /home/fact/FACT++.in-run-fad-loss/.libs/libDim.s
987#10 0x00007ffff647f388 in do_read () from /home/fact/FACT++.in-run-fad-loss/.libs/libDim.so
988#11 0x00007ffff647ff32 in tcpip_task () from /home/fact/FACT++.in-run-fad-loss/.libs/libDim.s
989#12 0x00007ffff6482c57 in dim_tcpip_thread () from /home/fact/FACT++.in-run-fad-loss/.libs/li
990#13 0x00007ffff7bc4e9a in start_thread (arg=0x7ffff13be700) at pthread_create.c:308
991#14 0x00007ffff52a1cbd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:112
992*/
Note: See TracBrowser for help on using the repository browser.