forked from php/php-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscriptengine.cpp
More file actions
1872 lines (1564 loc) · 50.5 KB
/
scriptengine.cpp
File metadata and controls
1872 lines (1564 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2002 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Wez Furlong <wez@thebrainroom.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* Implementation Notes:
*
* PHP stores scripting engine state in thread-local storage. That means
* that we need to create a dedicated thread per-engine so that a host can
* use more than one engine object per thread.
*
* There are some interesting synchronization issues: Anything to do with
* running script in the PHP/Zend engine must take place on the engine
* thread. Likewise, calling back to the host must take place on the base
* thread - the thread that set the script site.
* */
#define _WIN32_DCOM
#include "php.h"
extern "C" {
#include "php_main.h"
#include "SAPI.h"
#include "zend.h"
#include "zend_execute.h"
#include "zend_compile.h"
#include "php_globals.h"
#include "php_variables.h"
#include "php_ini.h"
#include "php4activescript.h"
#include "ext/com/com.h"
#include "ext/com/php_COM.h"
#include "ext/com/conversion.h"
}
#include "php_ticks.h"
#include "php4as_scriptengine.h"
#include "php4as_classfactory.h"
#include <objbase.h>
/* {{{ trace */
static inline void trace(char *fmt, ...)
{
va_list ap;
char buf[4096];
sprintf(buf, "T=%08x ", tsrm_thread_id());
OutputDebugString(buf);
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
OutputDebugString(buf);
va_end(ap);
}
/* }}} */
/* {{{ scriptstate_to_string */
static const char *scriptstate_to_string(SCRIPTSTATE ss)
{
switch(ss) {
case SCRIPTSTATE_UNINITIALIZED: return "SCRIPTSTATE_UNINITIALIZED";
case SCRIPTSTATE_INITIALIZED: return "SCRIPTSTATE_INITIALIZED";
case SCRIPTSTATE_STARTED: return "SCRIPTSTATE_STARTED";
case SCRIPTSTATE_CONNECTED: return "SCRIPTSTATE_CONNECTED";
case SCRIPTSTATE_DISCONNECTED: return "SCRIPTSTATE_DISCONNECTED";
case SCRIPTSTATE_CLOSED: return "SCRIPTSTATE_CLOSED";
default:
return "unknown";
}
}
/* }}} */
/* {{{ TWideString */
/* This class helps manipulate strings from OLE.
* It does not use emalloc, so it is better suited for passing pointers
* between threads. */
class TWideString {
public:
LPOLESTR m_ole;
char *m_ansi;
int m_ansi_strlen;
TWideString(LPOLESTR olestr) {
m_ole = olestr;
m_ansi = NULL;
}
TWideString(LPCOLESTR olestr) {
m_ole = (LPOLESTR)olestr;
m_ansi = NULL;
}
~TWideString() {
if (m_ansi) {
CoTaskMemFree(m_ansi);
}
m_ansi = NULL;
}
char *safe_ansi_string() {
char *ret = ansi_string();
if (ret == NULL)
return "<NULL>";
return ret;
}
int ansi_len(void) {
/* force conversion if it has not already occurred */
if (m_ansi == NULL)
ansi_string();
return m_ansi_strlen;
}
static BSTR bstr_from_ansi(char *ansi) {
OLECHAR *ole = NULL;
BSTR bstr = NULL;
int req = MultiByteToWideChar(CP_ACP, 0, ansi, -1, NULL, 0);
if (req) {
ole = (OLECHAR*)CoTaskMemAlloc((req + 1) * sizeof(OLECHAR));
if (ole) {
req = MultiByteToWideChar(CP_ACP, 0, ansi, -1, ole, req);
req--;
ole[req] = 0;
bstr = SysAllocString(ole);
CoTaskMemFree(ole);
}
}
return bstr;
}
char *ansi_string(void)
{
if (m_ansi)
return m_ansi;
if (m_ole == NULL)
return NULL;
int bufrequired = WideCharToMultiByte(CP_ACP, 0, m_ole, -1, NULL, 0, NULL, NULL);
if (bufrequired) {
m_ansi = (char*)CoTaskMemAlloc(bufrequired + 1);
if (m_ansi) {
m_ansi_strlen = WideCharToMultiByte(CP_ACP, 0, m_ole, -1, m_ansi, bufrequired + 1, NULL, NULL);
if (m_ansi_strlen) {
m_ansi_strlen--;
m_ansi[m_ansi_strlen] = 0;
} else {
trace("conversion failed with return code %08x\n", GetLastError());
}
}
}
return m_ansi;
}
};
/* }}} */
/* {{{ code fragment structures */
enum fragtype {
FRAG_MAIN,
FRAG_SCRIPTLET,
FRAG_PROCEDURE
};
typedef struct {
enum fragtype fragtype;
zend_op_array *opcodes;
char *code;
int persistent; /* should be retained for Clone */
int executed; /* for "main" */
char *functionname;
unsigned int codelen;
unsigned int starting_line;
TPHPScriptingEngine *engine;
void *ptr;
} code_frag;
#define FRAG_CREATE_FUNC (char*)-1
static code_frag *compile_code_fragment(
enum fragtype fragtype,
char *functionname,
LPCOLESTR code,
ULONG starting_line,
EXCEPINFO *excepinfo,
TPHPScriptingEngine *engine
TSRMLS_DC);
static int execute_code_fragment(code_frag *frag,
VARIANT *varResult,
EXCEPINFO *excepinfo
TSRMLS_DC);
static void free_code_fragment(code_frag *frag);
static code_frag *clone_code_fragment(code_frag *frag, TPHPScriptingEngine *engine TSRMLS_DC);
/* }}} */
/* Magic for handling threading correctly */
static inline HRESULT SEND_THREAD_MESSAGE(TPHPScriptingEngine *engine, LONG msg, WPARAM wparam, LPARAM lparam TSRMLS_DC)
{
if (engine->m_enginethread == 0)
return E_UNEXPECTED;
if (tsrm_thread_id() == (engine)->m_enginethread)
return (engine)->engine_thread_handler((msg), (wparam), (lparam), NULL TSRMLS_CC);
return (engine)->SendThreadMessage((msg), (wparam), (lparam));
}
/* These functions do some magic so that interfaces can be
* used across threads without worrying about marshalling
* or not marshalling, as appropriate.
* Win95 without DCOM 1.1, and NT SP 2 or lower do not have
* the GIT; so we emulate the GIT using other means.
* If you trace problems back to this code, installing the relevant
* SP should solve them.
* */
static inline HRESULT GIT_get(DWORD cookie, REFIID riid, void **obj)
{
IGlobalInterfaceTable *git;
HRESULT ret;
if (SUCCEEDED(CoCreateInstance(CLSID_StdGlobalInterfaceTable, NULL,
CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable,
(void**)&git))) {
ret = git->GetInterfaceFromGlobal(cookie, riid, obj);
git->Release();
return ret;
}
return CoGetInterfaceAndReleaseStream((LPSTREAM)cookie, riid, obj);
}
static inline HRESULT GIT_put(IUnknown *unk, REFIID riid, DWORD *cookie)
{
IGlobalInterfaceTable *git;
HRESULT ret;
if (SUCCEEDED(CoCreateInstance(CLSID_StdGlobalInterfaceTable, NULL,
CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable,
(void**)&git))) {
ret = git->RegisterInterfaceInGlobal(unk, riid, cookie);
git->Release();
return ret;
}
return CoMarshalInterThreadInterfaceInStream(riid, unk, (LPSTREAM*)cookie);
}
static inline HRESULT GIT_revoke(DWORD cookie, IUnknown *unk)
{
IGlobalInterfaceTable *git;
HRESULT ret;
if (SUCCEEDED(CoCreateInstance(CLSID_StdGlobalInterfaceTable, NULL,
CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable,
(void**)&git))) {
ret = git->RevokeInterfaceFromGlobal(cookie);
git->Release();
}
/* Kill remote clients */
return CoDisconnectObject(unk, 0);
}
/* {{{ A generic stupid IDispatch implementation */
class IDispatchImpl:
public IDispatch
{
protected:
volatile LONG m_refcount;
public:
/* IUnknown */
STDMETHODIMP QueryInterface(REFIID iid, void **ppvObject) {
*ppvObject = NULL;
if (IsEqualGUID(IID_IDispatch, iid)) {
*ppvObject = (IDispatch*)this;
} else if (IsEqualGUID(IID_IUnknown, iid)) {
*ppvObject = this;
}
if (*ppvObject) {
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
STDMETHODIMP_(DWORD) AddRef(void) {
return InterlockedIncrement(const_cast<long*> (&m_refcount));
}
STDMETHODIMP_(DWORD) Release(void) {
DWORD ret = InterlockedDecrement(const_cast<long*> (&m_refcount));
trace("%08x: IDispatchImpl: release ref count is now %d\n", this, ret);
if (ret == 0)
delete this;
return ret;
}
/* IDispatch */
STDMETHODIMP GetTypeInfoCount(unsigned int * pctinfo) {
*pctinfo = 0;
trace("%08x: IDispatchImpl: GetTypeInfoCount\n", this);
return S_OK;
}
STDMETHODIMP GetTypeInfo( unsigned int iTInfo, LCID lcid, ITypeInfo **ppTInfo) {
trace("%08x: IDispatchImpl: GetTypeInfo\n", this);
return DISP_E_BADINDEX;
}
STDMETHODIMP GetIDsOfNames( REFIID riid, OLECHAR **rgszNames, unsigned int cNames, LCID lcid, DISPID *rgDispId)
{
unsigned int i;
trace("%08x: IDispatchImpl: GetIDsOfNames: \n", this);
for (i = 0; i < cNames; i++) {
TWideString name(rgszNames[i]);
trace(" %s\n", name.ansi_string());
}
trace("----\n");
return DISP_E_UNKNOWNNAME;
}
STDMETHODIMP Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags,
DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo,
unsigned int FAR* puArgErr)
{
trace("%08x: IDispatchImpl: Invoke dispid %08x\n", this, dispIdMember);
return S_OK;
}
IDispatchImpl() {
m_refcount = 1;
}
virtual ~IDispatchImpl() {
}
};
/* }}} */
/* {{{ This object represents the PHP engine to the scripting host.
* Although the docs say it's implementation is optional, I found that
* the Windows Script host would crash if we did not provide it. */
class ScriptDispatch:
public IDispatchImpl
{
public:
ScriptDispatch() {
m_refcount = 1;
}
};
/* }}} */
/* {{{ This object is used in conjunction with IActiveScriptParseProcedure to
* allow scriptlets to be bound to events. IE uses this for declaring
* event handlers such as onclick="...".
* The compiled code is stored in this object; IE will call
* IDispatch::Invoke when the element is clicked.
* */
class ScriptProcedureDispatch:
public IDispatchImpl
{
public:
code_frag *m_frag;
DWORD m_procflags;
TPHPScriptingEngine *m_engine;
DWORD m_gitcookie;
STDMETHODIMP Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags,
DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo,
unsigned int FAR* puArgErr)
{
TSRMLS_FETCH();
if (m_frag) {
trace("%08x: Procedure Dispatch: Invoke dispid %08x\n", this, dispIdMember);
SEND_THREAD_MESSAGE(m_engine, PHPSE_EXEC_PROC, 0, (LPARAM)this TSRMLS_CC);
}
return S_OK;
}
ScriptProcedureDispatch() {
m_refcount = 1;
GIT_put((IDispatch*)this, IID_IDispatch, &m_gitcookie);
}
};
/* }}} */
/* {{{ code fragment management */
static code_frag *compile_code_fragment(
enum fragtype fragtype,
char *functionname,
LPCOLESTR code,
ULONG starting_line,
EXCEPINFO *excepinfo,
TPHPScriptingEngine *engine
TSRMLS_DC)
{
zval pv;
int code_offs = 0;
char namebuf[256];
code_frag *frag = (code_frag*)CoTaskMemAlloc(sizeof(code_frag));
memset(frag, 0, sizeof(code_frag));
frag->engine = engine;
/* handle the function name */
if (functionname) {
int namelen;
if (functionname == FRAG_CREATE_FUNC) {
ULONG n = ++engine->m_lambda_count;
sprintf(namebuf, "__frag_%08x_%u", engine, n);
functionname = namebuf;
}
namelen = strlen(functionname);
code_offs = namelen + sizeof("function (){");
frag->functionname = (char*)CoTaskMemAlloc((namelen + 1) * sizeof(char));
memcpy(frag->functionname, functionname, namelen+1);
}
frag->functionname = functionname;
trace("%08x: COMPILED FRAG\n", frag);
frag->codelen = WideCharToMultiByte(CP_ACP, 0, code, -1, NULL, 0, NULL, NULL);
frag->code = (char*)CoTaskMemAlloc(sizeof(char) * (frag->codelen + code_offs + 1));
if (functionname) {
sprintf(frag->code, "function %s(){ ", functionname);
}
frag->codelen = WideCharToMultiByte(CP_ACP, 0, code, -1, frag->code + code_offs, frag->codelen, NULL, NULL) - 1;
if (functionname) {
frag->codelen += code_offs + 1;
frag->code[frag->codelen-1] = '}';
frag->code[frag->codelen] = 0;
}
trace("code to compile is:\ncode_offs=%d func=%s\n%s\n", code_offs, functionname, frag->code);
frag->fragtype = fragtype;
frag->starting_line = starting_line;
pv.type = IS_STRING;
pv.value.str.val = frag->code;
pv.value.str.len = frag->codelen;
frag->opcodes = compile_string(&pv, "fragment" TSRMLS_CC);
if (frag->opcodes == NULL) {
free_code_fragment(frag);
if (excepinfo) {
memset(excepinfo, 0, sizeof(EXCEPINFO));
excepinfo->wCode = 1000;
excepinfo->bstrSource = TWideString::bstr_from_ansi("fragment");
excepinfo->bstrDescription = TWideString::bstr_from_ansi("Problem while parsing/compiling");
}
return NULL;
}
return frag;
}
static void free_code_fragment(code_frag *frag)
{
switch(frag->fragtype) {
case FRAG_PROCEDURE:
if (frag->ptr) {
ScriptProcedureDispatch *disp = (ScriptProcedureDispatch*)frag->ptr;
disp->Release();
GIT_revoke(disp->m_gitcookie, (IDispatch*)disp);
frag->ptr = NULL;
}
break;
}
if (frag->opcodes)
destroy_op_array(frag->opcodes);
if (frag->functionname)
CoTaskMemFree(frag->functionname);
CoTaskMemFree(frag->code);
CoTaskMemFree(frag);
}
static code_frag *clone_code_fragment(code_frag *frag, TPHPScriptingEngine *engine TSRMLS_DC)
{
zval pv;
code_frag *newfrag = (code_frag*)CoTaskMemAlloc(sizeof(code_frag));
memset(newfrag, 0, sizeof(code_frag));
newfrag->engine = engine;
trace("%08x: CLONED FRAG\n", newfrag);
newfrag->persistent = frag->persistent;
newfrag->codelen = frag->codelen;
newfrag->code = (char*)CoTaskMemAlloc(sizeof(char) * frag->codelen + 1);
memcpy(newfrag->code, frag->code, frag->codelen + 1);
if (frag->functionname) {
int namelen = strlen(frag->functionname);
newfrag->functionname = (char*)CoTaskMemAlloc(sizeof(char) * (namelen + 1));
memcpy(newfrag->functionname, frag->functionname, namelen+1);
} else {
newfrag->functionname = NULL;
}
newfrag->fragtype = frag->fragtype;
newfrag->starting_line = frag->starting_line;
pv.type = IS_STRING;
pv.value.str.val = newfrag->code;
pv.value.str.len = newfrag->codelen;
newfrag->opcodes = compile_string(&pv, "fragment" TSRMLS_CC);
if (newfrag->opcodes == NULL) {
free_code_fragment(newfrag);
/*
if (excepinfo) {
memset(excepinfo, 0, sizeof(EXCEPINFO));
excepinfo->wCode = 1000;
excepinfo->bstrSource = TWideString::bstr_from_ansi("fragment");
excepinfo->bstrDescription = TWideString::bstr_from_ansi("Problem while parsing/compiling");
}
*/
return NULL;
}
return newfrag;
}
static int execute_code_fragment(code_frag *frag,
VARIANT *varResult,
EXCEPINFO *excepinfo
TSRMLS_DC)
{
zval *retval_ptr = NULL;
jmp_buf *orig_jmpbuf;
jmp_buf err_trap;
if (frag->fragtype == FRAG_MAIN && frag->executed)
return 1;
orig_jmpbuf = frag->engine->m_err_trap;
frag->engine->m_err_trap = &err_trap;
if (setjmp(err_trap) == 0) {
trace("*** Executing code in thread %08x\n", tsrm_thread_id());
if (frag->functionname) {
zval fname;
fname.type = IS_STRING;
fname.value.str.val = frag->functionname;
fname.value.str.len = strlen(frag->functionname);
call_user_function_ex(CG(function_table), NULL, &fname, &retval_ptr, 0, NULL, 1, NULL TSRMLS_CC);
} else {
zend_op_array *active_op_array = EG(active_op_array);
zend_function_state *function_state_ptr = EG(function_state_ptr);
zval **return_value_ptr_ptr = EG(return_value_ptr_ptr);
zend_op **opline_ptr = EG(opline_ptr);
EG(return_value_ptr_ptr) = &retval_ptr;
EG(active_op_array) = frag->opcodes;
EG(no_extensions) = 1;
zend_execute(frag->opcodes TSRMLS_CC);
EG(no_extensions) = 0;
EG(opline_ptr) = opline_ptr;
EG(active_op_array) = active_op_array;
EG(function_state_ptr) = function_state_ptr;
EG(return_value_ptr_ptr) = return_value_ptr_ptr;
}
} else {
trace("*** --> caught error while executing\n");
if (frag->engine->m_in_main)
frag->engine->m_stop_main = 1;
}
frag->engine->m_err_trap = orig_jmpbuf;
if (frag->fragtype == FRAG_MAIN)
frag->executed = 1;
if (varResult)
VariantInit(varResult);
if (retval_ptr) {
if (varResult)
php_pval_to_variant(retval_ptr, varResult, CP_ACP TSRMLS_CC);
zval_ptr_dtor(&retval_ptr);
}
return 1;
}
static void frag_dtor(void *pDest)
{
code_frag *frag = *(code_frag**)pDest;
free_code_fragment(frag);
}
/* }}} */
/* glue for getting back into the OO land */
static DWORD WINAPI begin_engine_thread(LPVOID param)
{
TPHPScriptingEngine *engine = (TPHPScriptingEngine*)param;
engine->engine_thread_func();
trace("engine thread has really gone away!\n");
return 0;
}
TPHPScriptingEngine::TPHPScriptingEngine()
{
m_scriptstate = SCRIPTSTATE_UNINITIALIZED;
m_pass = NULL;
m_in_main = 0;
m_stop_main = 0;
m_err_trap = NULL;
m_lambda_count = 0;
m_pass_eng = NULL;
m_refcount = 1;
m_basethread = tsrm_thread_id();
m_mutex = tsrm_mutex_alloc();
m_sync_thread_msg = CreateEvent(NULL, TRUE, FALSE, NULL);
TPHPClassFactory::AddToObjectCount();
m_engine_thread_handle = CreateThread(NULL, 0, begin_engine_thread, this, 0, &m_enginethread);
CloseHandle(m_engine_thread_handle);
}
void activescript_run_ticks(int count)
{
MSG msg;
TSRMLS_FETCH();
TPHPScriptingEngine *engine;
trace("ticking %d\n", count);
engine = (TPHPScriptingEngine*)SG(server_context);
/* PostThreadMessage(engine->m_enginethread, PHPSE_DUMMY_TICK, 0, 0); */
while(PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
if (msg.hwnd) {
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
break;
}
}
}
/* Synchronize with the engine thread */
HRESULT TPHPScriptingEngine::SendThreadMessage(LONG msg, WPARAM wparam, LPARAM lparam)
{
HRESULT ret;
if (m_enginethread == 0)
return E_UNEXPECTED;
trace("I'm waiting for a mutex in SendThreadMessage\n this=%08x ethread=%08x msg=%08x\n",
this, m_enginethread, msg);
tsrm_mutex_lock(m_mutex);
ResetEvent(m_sync_thread_msg);
/* If we call PostThreadMessage before the thread has created the queue, the message
* posting fails. MSDN docs recommend the following course of action */
while (!PostThreadMessage(m_enginethread, msg, wparam, lparam)) {
Sleep(50);
if (m_enginethread == 0) {
tsrm_mutex_unlock(m_mutex);
trace("breaking out of dodgy busy wait\n");
return E_UNEXPECTED;
}
}
/* Wait for the event object to be signalled.
* This is a nice "blocking without blocking" wait; window messages are dispatched
* and everything works out quite nicely */
while(1) {
DWORD result = MsgWaitForMultipleObjects(1, &m_sync_thread_msg, FALSE, 4000, QS_ALLINPUT);
if (result == WAIT_OBJECT_0 + 1) {
/* Dispatch some messages */
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
//trace("dispatching message while waiting\n");
TranslateMessage(&msg);
DispatchMessage(&msg);
}
} else if (result == WAIT_TIMEOUT) {
trace("timeout while waiting for thread reply\n");
} else {
/* the event was signalled */
break;
}
}
ret = m_sync_thread_ret;
ResetEvent(m_sync_thread_msg);
tsrm_mutex_unlock(m_mutex);
return ret;
}
TPHPScriptingEngine::~TPHPScriptingEngine()
{
trace("\n\n *** Engine Destructor Called\n\n");
if (m_scriptstate != SCRIPTSTATE_UNINITIALIZED && m_scriptstate != SCRIPTSTATE_CLOSED && m_enginethread)
Close();
PostThreadMessage(m_enginethread, WM_QUIT, 0, 0);
TPHPClassFactory::RemoveFromObjectCount();
tsrm_mutex_free(m_mutex);
}
/* Set some executor globals and execute a zend_op_array.
* The declaration looks wierd because this can be invoked from
* zend_hash_apply_with_argument */
static int execute_main(void *pDest, void *arg TSRMLS_DC)
{
code_frag *frag = *(code_frag**)pDest;
if (frag->fragtype == FRAG_MAIN && !(frag->engine->m_in_main && frag->engine->m_stop_main))
execute_code_fragment(frag, NULL, NULL TSRMLS_CC);
return ZEND_HASH_APPLY_KEEP;
}
static int clone_frags(void *pDest, void *arg TSRMLS_DC)
{
code_frag *frag, *src = *(code_frag**)pDest;
TPHPScriptingEngine *engine = (TPHPScriptingEngine*)arg;
if (src->persistent) {
frag = clone_code_fragment(src, engine TSRMLS_CC);
if (frag)
zend_hash_next_index_insert(&engine->m_frags, &frag, sizeof(code_frag*), NULL);
else
trace("WARNING: clone failed!\n");
}
return ZEND_HASH_APPLY_KEEP;
}
HRESULT TPHPScriptingEngine::engine_thread_handler(LONG msg, WPARAM wparam, LPARAM lParam, int *handled TSRMLS_DC)
{
HRESULT ret = S_OK;
trace("engine_thread_handler: running in thread %08x, should be %08x msg=%08x this=%08x\n",
tsrm_thread_id(), m_enginethread, msg, this);
if (handled)
*handled = 1;
if (m_enginethread == 0)
return E_UNEXPECTED;
switch(msg) {
case PHPSE_ADD_TYPELIB:
{
struct php_active_script_add_tlb_info *info = (struct php_active_script_add_tlb_info*)lParam;
ITypeLib *TypeLib;
if (SUCCEEDED(LoadRegTypeLib(*info->rguidTypeLib, (USHORT)info->dwMajor,
(USHORT)info->dwMinor, LANG_NEUTRAL, &TypeLib))) {
php_COM_load_typelib(TypeLib, CONST_CS TSRMLS_CC);
TypeLib->Release();
}
}
break;
case PHPSE_STATE_CHANGE:
{
/* handle the state change here */
SCRIPTSTATE ss = (SCRIPTSTATE)lParam;
int start_running = 0;
trace("%08x: DoSetScriptState(current=%s, new=%s)\n",
this,
scriptstate_to_string(m_scriptstate),
scriptstate_to_string(ss));
if (m_scriptstate == SCRIPTSTATE_INITIALIZED && (ss == SCRIPTSTATE_STARTED || ss == SCRIPTSTATE_CONNECTED))
start_running = 1;
m_scriptstate = ss;
/* inform host/site of the change */
if (m_pass_eng)
m_pass_eng->OnStateChange(m_scriptstate);
if (start_running) {
/* run "main()", as described in the docs */
if (m_pass_eng)
m_pass_eng->OnEnterScript();
trace("%08x: apply execute main to m_frags\n", this);
m_in_main = 1;
m_stop_main = 0;
zend_hash_apply_with_argument(&m_frags, execute_main, this TSRMLS_CC);
m_in_main = 0;
trace("%08x: --- done execute main\n", this);
if (m_pass_eng)
m_pass_eng->OnLeaveScript();
/* docs are a bit ambiguous here, but it appears that we should
* inform the host that the main script execution has completed,
* and also what the return value is */
VARIANT varRes;
VariantInit(&varRes);
if (m_pass_eng)
m_pass_eng->OnScriptTerminate(&varRes, NULL);
/*
m_scriptstate = SCRIPTSTATE_INITIALIZED;
if (m_pass_eng)
m_pass_eng->OnStateChange(m_scriptstate);
*/
}
}
break;
case PHPSE_INIT_NEW:
{
/* Prepare PHP/ZE for use */
trace("%08x: m_frags : INIT NEW\n", this);
zend_hash_init(&m_frags, 0, NULL, frag_dtor, TRUE);
SG(options) |= SAPI_OPTION_NO_CHDIR;
SG(server_context) = this;
/* override the default PHP error callback */
zend_error_cb = activescript_error_handler;
zend_alter_ini_entry("register_argc_argv", 19, "1", 1, PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
zend_alter_ini_entry("html_errors", 12, "0", 1, PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
zend_alter_ini_entry("implicit_flush", 15, "1", 1, PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
zend_alter_ini_entry("max_execution_time", 19, "0", 1, PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
php_request_startup(TSRMLS_C);
PG(during_request_startup) = 0;
trace("\n\n *** ticks func at %08x %08x ***\n\n\n", activescript_run_ticks, &activescript_run_ticks);
// php_add_tick_function(activescript_run_ticks);
}
break;
case PHPSE_CLOSE:
{
/* Close things down */
trace("%08x: m_frags : CLOSE/DESTROY\n", this);
m_scriptstate = SCRIPTSTATE_CLOSED;
if (m_pass_eng) {
m_pass_eng->OnStateChange(m_scriptstate);
trace("%08x: release site from this side\n", this);
m_pass_eng->Release();
m_pass_eng = NULL;
}
zend_hash_destroy(&m_frags);
php_request_shutdown(NULL);
break;
}
break;
case PHPSE_CLONE:
{
/* Clone the engine state. This is semantically equal to serializing all
* the parsed code from the source and unserializing it in the dest (this).
* IE doesn't appear to use it, but Windows Script Host does. I'd expect
* ASP/ASP.NET to do so also.
*
* FIXME: Probably won't work with IActiveScriptParseProcedure scriplets
* */
TPHPScriptingEngine *src = (TPHPScriptingEngine*)lParam;
trace("%08x: m_frags : CLONE\n", this);
zend_hash_apply_with_argument(&src->m_frags, clone_frags, this TSRMLS_CC);
}
break;
case PHPSE_ADD_SCRIPTLET:
{
/* Parse/compile a chunk of script that will act as an event handler.
* If the host supports IActiveScriptParseProcedure, this code will
* not be called.
* The docs are (typically) vague: AFAICT, once the code has been
* compiled, we are supposed to arrange for an IConnectionPoint
* advisory connection to the item/subitem, once the script
* moves into SCRIPTSTATE_CONNECTED.
* That's a lot of work!
*
* FIXME: this is currently almost useless
* */
struct php_active_script_add_scriptlet_info *info = (struct php_active_script_add_scriptlet_info*)lParam;
TWideString
default_name(info->pstrDefaultName),
code(info->pstrCode),
item_name(info->pstrItemName),
sub_item_name(info->pstrSubItemName),
event_name(info->pstrEventName),
delimiter(info->pstrDelimiter);
/* lets invent a function name for the scriptlet */
char sname[256];
/* should check if the name is already used! */
if (info->pstrDefaultName)
strcpy(sname, default_name.ansi_string());
else {
sname[0] = 0;
strcat(sname, "__");
if (info->pstrItemName) {
strcat(sname, item_name.ansi_string());
strcat(sname, "_");
}
if (info->pstrSubItemName) {
strcat(sname, sub_item_name.ansi_string());
strcat(sname, "_");
}
if (info->pstrEventName)
strcat(sname, event_name.ansi_string());
}
trace("%08x: AddScriptlet:\n state=%s\n name=%s\n code=%s\n item=%s\n subitem=%s\n event=%s\n delim=%s\n line=%d\n",
this, scriptstate_to_string(m_scriptstate),
default_name.safe_ansi_string(), code.safe_ansi_string(), item_name.safe_ansi_string(),
sub_item_name.safe_ansi_string(), event_name.safe_ansi_string(), delimiter.safe_ansi_string(),
info->ulStartingLineNumber);
code_frag *frag = compile_code_fragment(
FRAG_SCRIPTLET,
sname,
info->pstrCode,
info->ulStartingLineNumber,
info->pexcepinfo,
this
TSRMLS_CC);
if (frag) {
frag->persistent = (info->dwFlags & SCRIPTTEXT_ISPERSISTENT);
zend_hash_next_index_insert(&m_frags, &frag, sizeof(code_frag*), NULL);
/*
ScriptProcedureDispatch *disp = new ScriptProcedureDispatch;
disp->AddRef();
disp->m_frag = frag;
disp->m_procflags = info->dwFlags;
disp->m_engine = this;
frag->ptr = disp;
*info->ppdisp = disp;
*/
ret = S_OK;
} else {
ret = DISP_E_EXCEPTION;
}
*info->pbstrName = TWideString::bstr_from_ansi(sname);
trace("%08x: done with scriptlet %s\n", this, sname);
}
break;
case PHPSE_GET_DISPATCH:
{
struct php_active_script_get_dispatch_info *info = (struct php_active_script_get_dispatch_info *)lParam;
IDispatch *disp = NULL;