summaryrefslogtreecommitdiffstats
path: root/src/modules/perlcore/libkviperlcore.cpp
blob: a7c9a282e3d5cb3f878c303fe940a976e8caa52f (plain)
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
//=============================================================================
//
//   File : libkviperlcore.cpp
//   Creation date : Tue Jul 13 13:03:31 2004 GMT by Szymon Stefanek
//
//   This file is part of the KVirc irc client distribution
//   Copyright (C) 2001 Szymon Stefanek (pragma at kvirc dot net)
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your opinion) any later version.
//
//   This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc. ,51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================

#include "kvi_module.h"
#include "kvi_settings.h"
#include "kvi_locale.h"
#include "kvi_out.h"
#include "kvi_window.h"
#include "kvi_app.h"

#include "kvi_kvs_script.h"
#include "kvi_kvs_variant.h"
#include "kvi_userinput.h"
#include "kvi_qcstring.h"
#include "kvi_pointerhashtable.h"

#ifdef DEBUG
	#undef DEBUG
#endif

// I MUST say that the perl embedding process is somewhat ugly :(
// First of all the man pages are somewhat unreadable even
// for a non-novice perl user. The writer of each page assumed
// that you have already read each other page...
// Also browsing the pages with "man" is obviously out of mind
// but this can be solved by looking up some html docs on the net.
// Embedding multiple interpreters isn't that hard (after you
// have read perlembed) but to start passing parameters
// around you have to read at least perlembed, perlguts, perlxs,..
// take a look at the perlinternals and have a good trip
// around the web to find some examples for the functions
// that aren't explained enough in the pages.
// It gets even more weird when you attempt to include
// some XS functions... (what the heck is boot_DynaLoader ?).

// ... and I'm still convinced that I'm leaking memory with
// the perl values, but well ...

// anyway, once you struggled for a couple of days with all that
// stuff then you start getting things done... and it rox :)

#ifdef COMPILE_PERL_SUPPORT
	#include <EXTERN.h>
	#include <perl.h>
	#include <XSUB.h>

	#include "ppport.h"
	
	#include "kvi_kvs_runtimecontext.h"

	static KviKvsRunTimeContext * g_pCurrentKvsContext = 0;
	static bool g_bExecuteQuiet = false;
	static KviStr g_szLastReturnValue("");
	static TQStringList g_lWarningList;

	#include "xs.inc"
#endif // COMPILE_PERL_SUPPORT

// perl redefines bool :///
#ifdef bool
	#undef bool
#endif

#ifdef COMPILE_PERL_SUPPORT

#include "perlcoreinterface.h"

// people ... are you mad ? ... what the heck is "my_perl" ?
#define my_perl m_pInterpreter

class KviPerlInterpreter
{
public:
	KviPerlInterpreter(const TQString &szContextName);
	~KviPerlInterpreter();
protected:
	TQString           m_szContextName;
	PerlInterpreter * m_pInterpreter;
public:
	bool init(); // if this fails then well.. :D
	void done();
	bool execute(const TQString &szCode,TQStringList &args,TQString &szRetVal,TQString &szError,TQStringList &lWarnings);
	const TQString & contextName(){ return m_szContextName; };
protected:
	TQString svToTQString(SV * sv);
};

KviPerlInterpreter::KviPerlInterpreter(const TQString &szContextName)
{
	m_szContextName = szContextName;
	m_pInterpreter = 0;
}

KviPerlInterpreter::~KviPerlInterpreter()
{
	done();
}

// this kinda sux :(
// It SHOULD be mentioned somewhere that
// this function is in DynaLoader.a in the perl
// distribution and you MUST link it statically.
extern "C" void boot_DynaLoader(pTHX_ CV* cv);

extern "C" void xs_init(pTHX)
{
	char *file = __FILE__;
	// boot up the DynaLoader
	newXS("DynaLoader::boot_DynaLoader",boot_DynaLoader,file);
	// now bootstrap the KVIrc module
	// This stuff is simply cutted and pasted from xs.inc
	// since I don't really know if it's safe to call
	// something like
	//   CV * dummy;
	//   boot_KVIrc(aTHX,dummy);
	// ...
	newXS("KVIrc::echo", XS_KVIrc_echo, file);
	newXS("KVIrc::say", XS_KVIrc_say, file);
	newXS("KVIrc::warning", XS_KVIrc_warning, file);
	newXS("KVIrc::getLocal", XS_KVIrc_getLocal, file);
	newXS("KVIrc::setLocal", XS_KVIrc_setLocal, file);
	newXS("KVIrc::getGlobal", XS_KVIrc_getGlobal, file);
	newXS("KVIrc::setGlobal", XS_KVIrc_setGlobal, file);
	newXS("KVIrc::eval", XS_KVIrc_eval, file);
	newXS("KVIrc::internalWarning", XS_KVIrc_internalWarning, file);
}

bool KviPerlInterpreter::init()
{
	if(m_pInterpreter)done();
	m_pInterpreter = perl_alloc();
	if(!m_pInterpreter)return false;
	PERL_SET_CONTEXT(m_pInterpreter);
	PL_perl_destruct_level = 1;
	perl_construct(m_pInterpreter);
	char * daArgs[] = { "yo", "-e", "0", "-w" };
	perl_parse(m_pInterpreter,xs_init,4,daArgs,NULL);
	TQString szInitCode;

	// this part of the code seems to be unnecessary
	// even if it is created by the perl make process...
	//	"our %EXPORT_TAGS = ('all' => [qw(echo)]);\n"
	//	"our @EXPORT_OK = (qw(echo));\n"
	//	"our @EXPORT = qw();\n"
	// This is probably needed only if perl has to load
	// the XS through XSLoader ?
	// Maybe also the remaining part of the package
	// declaration could be dropped as well...
	// I just haven't tried :D

	KviTQString::sprintf(
		szInitCode,
		"{\n" \
			"package KVIrc;\n" \
			"require Exporter;\n" \
			"our @ISA = qw(Exporter);\n" \
			"1;\n" \
		"}\n" \
		"$g_szContext = \"%Q\";\n" \
		"$g_bExecuteQuiet = 0;\n" \
		"$SIG{__WARN__} = sub\n" \
		"{\n" \
		"	my($p,$f,$l,$x);\n" \
		"	($p,$f,$l) = caller;\n" \
		"	KVIrc::internalWarning(\"At line \".$l.\" of perl code: \");\n" \
		"	KVIrc::internalWarning(join(' ',@_));\n" \
		"}\n",
		&m_szContextName);

	eval_pv(szInitCode.utf8().data(),false);
	return true;
}

void KviPerlInterpreter::done()
{
	if(!m_pInterpreter)return;
	PERL_SET_CONTEXT(m_pInterpreter);
	PL_perl_destruct_level = 1;
	perl_destruct(m_pInterpreter);
	perl_free(m_pInterpreter);
	m_pInterpreter = 0;
}

TQString KviPerlInterpreter::svToTQString(SV * sv)
{
	TQString ret = "";
	if(!sv)return ret;
	STRLEN len;
	char * ptr = SvPV(sv,len);
	if(ptr)ret = ptr;
	return ret;
}

bool KviPerlInterpreter::execute(
		const TQString &szCode,
		TQStringList &args,
		TQString &szRetVal,
		TQString &szError,
		TQStringList &lWarnings)
{
	if(!m_pInterpreter)
	{
		szError = __tr2qs_ctx("Internal error: perl interpreter not initialized","perlcore");
		return false;
	}
	
	g_lWarningList.clear();

	KviTQCString szUtf8 = szCode.utf8();
	PERL_SET_CONTEXT(m_pInterpreter);
	
	// clear the _ array
	AV * pArgs = get_av("_",1);
	SV * pArg = av_shift(pArgs);
	while(SvOK(pArg))
	{
		SvREFCNT_dec(pArg);
		pArg = av_shift(pArgs);
	}

	if(args.count() > 0)
	{
		// set the args in the _ arry
		av_unshift(pArgs,(I32)args.count());
		int idx = 0;
		for(TQStringList::Iterator it = args.begin();it != args.end();++it)
		{
			TQString tmp = *it;
			const char * val = tmp.utf8().data();
			if(val)
			{
				pArg = newSVpv(val,tmp.length());
				if(!av_store(pArgs,idx,pArg))
					SvREFCNT_dec(pArg);
			}
			idx++;
		}
	}

	// call the code
	SV * pRet = eval_pv(szUtf8.data(),false);

	// clear the _ array again
	pArgs = get_av("_",1);
	pArg = av_shift(pArgs);
	while(SvOK(pArg))
	{
		SvREFCNT_dec(pArg);
		pArg = av_shift(pArgs);
	}
	av_undef(pArgs);

	// get the ret value
	if(pRet)
	{
		if(SvOK(pRet))
			szRetVal = svToTQString(pRet);
	}

	if(!g_lWarningList.isEmpty())
		lWarnings = g_lWarningList;

	// and the eventual error string
	pRet = get_sv("@",false);
	if(pRet)
	{
		if(SvOK(pRet))
		{
			szError = svToTQString(pRet);
			if(!szError.isEmpty())return false;
		}
	}

	return true;
}

static KviPointerHashTable<TQString,KviPerlInterpreter> * g_pInterpreters = 0;

static KviPerlInterpreter * perlcore_get_interpreter(const TQString &szContextName)
{
	KviPerlInterpreter * i = g_pInterpreters->find(szContextName);
	if(i)return i;
	i = new KviPerlInterpreter(szContextName);
	if(!i->init())
	{
		delete i;
		return 0;
	}
	g_pInterpreters->replace(szContextName,i);
	return i;
}

static void perlcore_destroy_interpreter(const TQString &szContextName)
{
	KviPerlInterpreter * i = g_pInterpreters->find(szContextName);
	if(!i)return;
	g_pInterpreters->remove(szContextName);
	i->done();
	delete i;
}

static void perlcore_destroy_all_interpreters()
{
	KviPointerHashTableIterator<TQString,KviPerlInterpreter> it(*g_pInterpreters);
	
	while(it.current())
	{
		KviPerlInterpreter * i = it.current();
		i->done();
		delete i;
		++it;
	}
	g_pInterpreters->clear();
}

#endif // COMPILE_PERL_SUPPORT

static bool perlcore_module_ctrl(KviModule * m,const char * cmd,void * param)
{
#ifdef COMPILE_PERL_SUPPORT
	if(kvi_strEqualCS(cmd,KVI_PERLCORECTRLCOMMAND_EXECUTE))
	{
		KviPerlCoreCtrlCommand_execute * ex = (KviPerlCoreCtrlCommand_execute *)param;
		if(ex->uSize != sizeof(KviPerlCoreCtrlCommand_execute))return false;
		g_pCurrentKvsContext = ex->pKvsContext;
		g_bExecuteQuiet = ex->bQuiet;
		if(ex->szContext.isEmpty())
		{
			KviPerlInterpreter * m = new KviPerlInterpreter("temporary");
			if(!m->init())
			{
				delete m;
				return false;
			}
			ex->bExitOk = m->execute(ex->szCode,ex->lArgs,ex->szRetVal,ex->szError,ex->lWarnings);
			m->done();
			delete m;
		} else {
			KviPerlInterpreter * m = perlcore_get_interpreter(ex->szContext);
			ex->bExitOk = m->execute(ex->szCode,ex->lArgs,ex->szRetVal,ex->szError,ex->lWarnings);
		}
		return true;
	}
	if(kvi_strEqualCS(cmd,KVI_PERLCORECTRLCOMMAND_DESTROY))
	{
		KviPerlCoreCtrlCommand_destroy * de = (KviPerlCoreCtrlCommand_destroy *)param;
		if(de->uSize != sizeof(KviPerlCoreCtrlCommand_destroy))return false;
		perlcore_destroy_interpreter(de->szContext);
		return true;
	}
#endif // COMPILE_PERL_SUPPORT
	return false;
}

static bool perlcore_module_init(KviModule * m)
{
#ifdef COMPILE_PERL_SUPPORT
	g_pInterpreters = new KviPointerHashTable<TQString,KviPerlInterpreter>(17,false);
	g_pInterpreters->setAutoDelete(false);
	return true;
#else // !COMPILE_PERL_SUPPORT
	return false;
#endif // !COMPILE_PERL_SUPPORT
}

static bool perlcore_module_cleanup(KviModule *m)
{
#ifdef COMPILE_PERL_SUPPORT
	perlcore_destroy_all_interpreters();
	delete g_pInterpreters;
    g_pInterpreters = 0;
#endif // COMPILE_PERL_SUPPORT
	return true;
}

static bool perlcore_module_can_unload(KviModule *m)
{
#ifdef COMPILE_PERL_SUPPORT
	return (g_pInterpreters->count() == 0);
#endif // COMPILE_PERL_SUPPORT
	return true;
}

KVIRC_MODULE(
	"Perl",                                                 // module name
	"1.0.0",                                                // module version
	"Copyright (C) 2004 Szymon Stefanek (pragma at kvirc dot net)", // author & (C)
	"Perl scripting engine core",
	perlcore_module_init,
	perlcore_module_can_unload,
	perlcore_module_ctrl,
	perlcore_module_cleanup
)