summaryrefslogtreecommitdiffstats
path: root/pigeonhole/src/lib-sieve/sieve-interpreter.c
blob: 274e142d4616142cf6e0c8eda86c25e356919935 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
/* Copyright (c) 2002-2018 Pigeonhole authors, see the included COPYING file
 */

#include "lib.h"
#include "ostream.h"
#include "mempool.h"
#include "array.h"
#include "hash.h"
#include "cpu-limit.h"
#include "mail-storage.h"

#include "sieve-common.h"
#include "sieve-limits.h"
#include "sieve-script.h"
#include "sieve-error.h"
#include "sieve-extensions.h"
#include "sieve-message.h"
#include "sieve-commands.h"
#include "sieve-code.h"
#include "sieve-actions.h"
#include "sieve-generator.h"
#include "sieve-binary.h"
#include "sieve-result.h"
#include "sieve-comparators.h"
#include "sieve-runtime-trace.h"

#include "sieve-interpreter.h"

#include <string.h>

static struct event_category event_category_sieve_runtime = {
	.parent = &event_category_sieve,
	.name = "sieve-runtime",
};

/*
 * Interpreter extension
 */

struct sieve_interpreter_extension_reg {
	const struct sieve_interpreter_extension *intext;
	const struct sieve_extension *ext;

	void *context;

	bool deferred:1;
	bool started:1;
};

/*
 * Code loop
 */

struct sieve_interpreter_loop {
	unsigned int level;
	sieve_size_t begin, end;
	const struct sieve_extension_def *ext_def;
	pool_t pool;
	void *context;
};

/*
 * Interpreter
 */

struct sieve_interpreter {
	pool_t pool;
	struct sieve_interpreter *parent;

	/* Runtime data for extensions */
	ARRAY(struct sieve_interpreter_extension_reg) extensions;

	sieve_size_t reset_vector;

	/* Execution status */
	sieve_size_t pc;          /* Program counter */

	/* Loop stack */
	ARRAY(struct sieve_interpreter_loop) loop_stack;
	sieve_size_t loop_limit;
	unsigned int parent_loop_level;

	/* Runtime environment */
	struct sieve_runtime_env runenv;
	struct sieve_runtime_trace trace;
	struct sieve_resource_usage rusage;

	/* Current operation */
	struct sieve_operation oprtn;

	/* Location information */
	struct sieve_binary_debug_reader *dreader;
	unsigned int command_line;

	bool running:1;		    /* Interpreter is running
				       (may be interrupted) */
	bool interrupted:1;         /* Interpreter interrupt requested */
	bool test_result:1;         /* Result of previous test command */
};

static struct sieve_interpreter *
_sieve_interpreter_create(struct sieve_binary *sbin,
			  struct sieve_binary_block *sblock,
			  struct sieve_script *script,
			  struct sieve_interpreter *parent,
			  const struct sieve_execute_env *eenv,
			  struct sieve_error_handler *ehandler) ATTR_NULL(3, 4)
{
	const struct sieve_script_env *senv = eenv->scriptenv;
	unsigned int i, ext_count;
	struct sieve_interpreter *interp;
	pool_t pool;
	struct sieve_instance *svinst;
	const struct sieve_extension *const *ext_preloaded;
	unsigned int debug_block_id;
	sieve_size_t *address;
	bool success = TRUE;

	pool = pool_alloconly_create("sieve_interpreter", 4096);
	interp = p_new(pool, struct sieve_interpreter, 1);
	interp->parent = parent;
	interp->pool = pool;

	interp->runenv.ehandler = ehandler;
	sieve_error_handler_ref(ehandler);

	interp->runenv.exec_env = eenv;
	interp->runenv.interp = interp;
	interp->runenv.oprtn = &interp->oprtn;
	interp->runenv.sbin = sbin;
	interp->runenv.sblock = sblock;
	sieve_binary_ref(sbin);

	interp->runenv.event = event_create(eenv->event);
	event_add_category(interp->runenv.event, &event_category_sieve_runtime);
	event_add_str(interp->runenv.event, "script_name",
		      sieve_binary_script_name(sbin));
	event_add_str(interp->runenv.event, "script_location",
		      sieve_binary_script_location(sbin));
	event_add_str(interp->runenv.event, "binary_path",
		      sieve_binary_path(sbin));

	svinst = sieve_binary_svinst(sbin);

	if (senv->trace_log != NULL) {
		interp->trace.log = senv->trace_log;
		interp->trace.config = senv->trace_config;
		interp->trace.indent = 0;
		interp->runenv.trace = &interp->trace;
	}

	if (script == NULL)
		interp->runenv.script = sieve_binary_script(sbin);
	else
		interp->runenv.script = script;

	interp->runenv.pc = 0;
	address = &(interp->runenv.pc);

	sieve_runtime_trace_begin(&(interp->runenv));

	p_array_init(&interp->extensions, pool,
		     sieve_extensions_get_count(svinst));

	interp->parent_loop_level = 0;
	if (parent != NULL && array_is_created(&parent->loop_stack)) {
		interp->parent_loop_level = parent->parent_loop_level +
			array_count(&parent->loop_stack);
	}

	/* Pre-load core language features implemented as 'extensions' */
	ext_preloaded = sieve_extensions_get_preloaded(svinst, &ext_count);
	for (i = 0; i < ext_count; i++) {
		const struct sieve_extension_def *ext_def =
			ext_preloaded[i]->def;

		if (ext_def != NULL && ext_def->interpreter_load != NULL) {
			(void)ext_def->interpreter_load(ext_preloaded[i],
							&interp->runenv,
							address);
		}
	}

	/* Load debug block */
	if (sieve_binary_read_unsigned(sblock, address, &debug_block_id)) {
		struct sieve_binary_block *debug_block =
			sieve_binary_block_get(sbin, debug_block_id);

		if (debug_block == NULL) {
			sieve_runtime_trace_error(&interp->runenv,
						  "invalid id for debug block");
			success = FALSE;
		} else {
			/* Initialize debug reader */
			interp->dreader =
				sieve_binary_debug_reader_init(debug_block);
		}
	}

	/* Load other extensions listed in code */
	if (success && sieve_binary_read_unsigned(sblock, address,
						  &ext_count)) {

		for (i = 0; i < ext_count; i++) {
			unsigned int code = 0, deferred;
			struct sieve_interpreter_extension_reg *reg;
			const struct sieve_extension *ext;

			if (!sieve_binary_read_extension(sblock, address,
							 &code, &ext) ||
			    !sieve_binary_read_byte(sblock, address,
						    &deferred)) {
				success = FALSE;
				break;
			}

			if (deferred > 0 && ext->id >= 0) {
				reg = array_idx_get_space(
					&interp->extensions,
					(unsigned int)ext->id);
				reg->deferred = TRUE;
			}

			if (ext->def != NULL) {
				if (ext->global &&
				    (eenv->flags & SIEVE_EXECUTE_FLAG_NOGLOBAL) != 0) {
					sieve_runtime_error(&interp->runenv, NULL,
						"failed to enable extension `%s': "
						"its use is restricted to global scripts",
						sieve_extension_name(ext));
					success = FALSE;
					break;
				}

				if (ext->def->interpreter_load != NULL &&
				    !ext->def->interpreter_load(ext, &interp->runenv,
								address)) {
					success = FALSE;
					break;
				}
			}
		}
	} else {
		success = FALSE;
	}

	if (!success) {
		sieve_interpreter_free(&interp);
		interp = NULL;
	} else {
		interp->reset_vector = *address;
	}

	return interp;
}

struct sieve_interpreter *
sieve_interpreter_create(struct sieve_binary *sbin,
			 struct sieve_interpreter *parent,
			 const struct sieve_execute_env *eenv,
			 struct sieve_error_handler *ehandler)
{
	struct sieve_binary_block *sblock;

	if ((sblock = sieve_binary_block_get(
		sbin, SBIN_SYSBLOCK_MAIN_PROGRAM)) == NULL)
		return NULL;

	return _sieve_interpreter_create(sbin, sblock, NULL, parent, eenv,
					 ehandler);
}

struct sieve_interpreter *
sieve_interpreter_create_for_block(struct sieve_binary_block *sblock,
				   struct sieve_script *script,
				   struct sieve_interpreter *parent,
				   const struct sieve_execute_env *eenv,
				   struct sieve_error_handler *ehandler)
{
	if (sblock == NULL) return NULL;

	return _sieve_interpreter_create(sieve_binary_block_get_binary(sblock),
					 sblock, script, parent, eenv,
					 ehandler);
}

void sieve_interpreter_free(struct sieve_interpreter **_interp)
{
	struct sieve_interpreter *interp = *_interp;
	struct sieve_runtime_env *renv = &interp->runenv;
	const struct sieve_interpreter_extension_reg *eregs;
	struct sieve_interpreter_loop *loops;
	unsigned int count, i;

	if (interp->running) {
		struct event_passthrough *e =
			event_create_passthrough(interp->runenv.event)->
			set_name("sieve_runtime_script_finished")->
			add_str("error", "Aborted");
		e_debug(e->event(), "Aborted running script `%s'",
			sieve_binary_source(interp->runenv.sbin));

		interp->running = FALSE;
	}

	if (array_is_created(&interp->loop_stack)) {
		loops = array_get_modifiable(&interp->loop_stack, &count);
		for (i = 0; i < count; i++)
			pool_unref(&loops[i].pool);
	}

	interp->trace.indent = 0;
	sieve_runtime_trace_end(renv);

	/* Signal registered extensions that the interpreter is being destroyed */
	eregs = array_get(&interp->extensions, &count);
	for (i = 0; i < count; i++) {
		if (eregs[i].intext != NULL && eregs[i].intext->free != NULL) {
			eregs[i].intext->free(eregs[i].ext, interp,
					      eregs[i].context);
		}
	}

	sieve_binary_debug_reader_deinit(&interp->dreader);
	sieve_binary_unref(&renv->sbin);
	sieve_error_handler_unref(&renv->ehandler);
	event_unref(&renv->event);

	pool_unref(&interp->pool);
	*_interp = NULL;
}

/*
 * Accessors
 */

pool_t sieve_interpreter_pool(struct sieve_interpreter *interp)
{
	return interp->pool;
}

struct sieve_interpreter *
sieve_interpreter_get_parent(struct sieve_interpreter *interp)
{
	return interp->parent;
}

struct sieve_script *sieve_interpreter_script(struct sieve_interpreter *interp)
{
	return interp->runenv.script;
}

struct sieve_error_handler *
sieve_interpreter_get_error_handler(struct sieve_interpreter *interp)
{
	return interp->runenv.ehandler;
}

struct sieve_instance *
sieve_interpreter_svinst(struct sieve_interpreter *interp)
{
	return interp->runenv.exec_env->svinst;
}

/* Do not use this function for normal sieve extensions. This is intended for
 * the testsuite only.
 */
void sieve_interpreter_set_result(struct sieve_interpreter *interp,
				  struct sieve_result *result)
{
	sieve_result_unref(&interp->runenv.result);
	interp->runenv.result = result;
	interp->runenv.msgctx = sieve_result_get_message_context(result);
	sieve_result_ref(result);
}

/*
 * Source location
 */

unsigned int
sieve_runtime_get_source_location(const struct sieve_runtime_env *renv,
				  sieve_size_t code_address)
{
	struct sieve_interpreter *interp = renv->interp;

	if (interp->dreader == NULL)
		return 0;

	if (interp->command_line == 0) {
		interp->command_line =
			sieve_binary_debug_read_line(interp->dreader,
						     renv->oprtn->address);
	}

	return sieve_binary_debug_read_line(interp->dreader, code_address);
}

unsigned int
sieve_runtime_get_command_location(const struct sieve_runtime_env *renv)
{
	struct sieve_interpreter *interp = renv->interp;

	if (interp->dreader == NULL)
		return 0;

	if (interp->command_line == 0) {
		interp->command_line =
			sieve_binary_debug_read_line(interp->dreader,
						     renv->oprtn->address);
	}

	return interp->command_line;
}

const char *
sieve_runtime_get_full_command_location(const struct sieve_runtime_env *renv)
{
	return sieve_error_script_location(
		renv->script, sieve_runtime_get_command_location(renv));
}

/*
 * Extension support
 */

void sieve_interpreter_extension_register(
	struct sieve_interpreter *interp, const struct sieve_extension *ext,
	const struct sieve_interpreter_extension *intext, void *context)
{
	struct sieve_interpreter_extension_reg *reg;

	if (ext->id < 0)
		return;

	reg = array_idx_get_space(&interp->extensions, (unsigned int) ext->id);
	reg->intext = intext;
	reg->ext = ext;
	reg->context = context;
}

void sieve_interpreter_extension_set_context(struct sieve_interpreter *interp,
					     const struct sieve_extension *ext,
					     void *context)
{
	struct sieve_interpreter_extension_reg *reg;

	if (ext->id < 0)
		return;

	reg = array_idx_get_space(&interp->extensions, (unsigned int) ext->id);
	reg->context = context;
}

void *sieve_interpreter_extension_get_context(struct sieve_interpreter *interp,
					      const struct sieve_extension *ext)
{
	const struct sieve_interpreter_extension_reg *reg;

	if (ext->id < 0 || ext->id >= (int) array_count(&interp->extensions))
		return NULL;

	reg = array_idx(&interp->extensions, (unsigned int) ext->id);

	return reg->context;
}

int sieve_interpreter_extension_start(struct sieve_interpreter *interp,
				      const struct sieve_extension *ext)
{
	struct sieve_interpreter_extension_reg *reg;
	int ret;

	i_assert(ext->id >= 0);

	if (ext->id >= (int) array_count(&interp->extensions))
		return SIEVE_EXEC_OK;

	reg = array_idx_modifiable(&interp->extensions, (unsigned int)ext->id);

	if (!reg->deferred)
		return SIEVE_EXEC_OK;
	reg->deferred = FALSE;
	reg->started = TRUE;

	if (reg->intext != NULL && reg->intext->run != NULL &&
	    (ret = reg->intext->run(ext, &interp->runenv,
				    reg->context, TRUE)) <= 0)
		return ret;
	return SIEVE_EXEC_OK;
}

/*
 * Loop handling
 */

int sieve_interpreter_loop_start(struct sieve_interpreter *interp,
				 sieve_size_t loop_end,
				 const struct sieve_extension_def *ext_def,
				 struct sieve_interpreter_loop **loop_r)
{
	const struct sieve_runtime_env *renv = &interp->runenv;
	struct sieve_interpreter_loop *loop;

	i_assert(loop_end > interp->runenv.pc);

	/* Check supplied end offset */
	if (loop_end > sieve_binary_block_get_size(renv->sblock)) {
		sieve_runtime_trace_error(renv, "loop end offset out of range");
		return SIEVE_EXEC_BIN_CORRUPT;
	}

	/* Trace */
	if (sieve_runtime_trace_active(renv, SIEVE_TRLVL_COMMANDS)) {
		unsigned int line =
			sieve_runtime_get_source_location(renv, loop_end);

		if (sieve_runtime_trace_hasflag(renv, SIEVE_TRFLG_ADDRESSES)) {
			sieve_runtime_trace(renv, 0,
					    "loop ends at line %d [%08llx]",
					    line,
					    (long long unsigned int) loop_end);
		} else {
			sieve_runtime_trace(renv, 0,
					    "loop ends at line %d", line);
		}
	}

	/* Check loop nesting limit */
	if (!array_is_created(&interp->loop_stack))
		p_array_init(&interp->loop_stack, interp->pool, 8);
	if ((interp->parent_loop_level +
	     array_count(&interp->loop_stack)) >= SIEVE_MAX_LOOP_DEPTH) {
		/* Should normally be caught at compile time */
		sieve_runtime_error(renv, NULL,
				    "new program loop exceeds "
				    "the nesting limit (<= %u levels)",
				    SIEVE_MAX_LOOP_DEPTH);
		return SIEVE_EXEC_FAILURE;
	}

	/* Create new loop */
	loop = array_append_space(&interp->loop_stack);
	loop->level = array_count(&interp->loop_stack)-1;
	loop->ext_def = ext_def;
	loop->begin = interp->runenv.pc;
	loop->end = loop_end;
	loop->pool =  pool_alloconly_create("sieve_interpreter", 128);

	/* Set new loop limit */
	interp->loop_limit = loop_end;

	*loop_r = loop;
	return SIEVE_EXEC_OK;
}

struct sieve_interpreter_loop *
sieve_interpreter_loop_get(struct sieve_interpreter *interp,
			   sieve_size_t loop_end,
			   const struct sieve_extension_def *ext_def)
{
	struct sieve_interpreter_loop *loops;
	unsigned int count, i;

	if (!array_is_created(&interp->loop_stack))
		return NULL;

	loops = array_get_modifiable(&interp->loop_stack, &count);
	for (i = count; i > 0; i--) {
		/* We're really making sure our loop matches */
		if (loops[i-1].end == loop_end &&
		    loops[i-1].ext_def == ext_def)
			return &loops[i-1];
	}
	return NULL;
}

int sieve_interpreter_loop_next(struct sieve_interpreter *interp,
				struct sieve_interpreter_loop *loop,
				sieve_size_t loop_begin)
{
	const struct sieve_runtime_env *renv = &interp->runenv;
	struct sieve_interpreter_loop *loops;
	unsigned int count;

	/* Trace */
	if (sieve_runtime_trace_active(renv, SIEVE_TRLVL_COMMANDS)) {
		unsigned int line =
			sieve_runtime_get_source_location(renv, loop_begin);

		if (sieve_runtime_trace_hasflag(renv, SIEVE_TRFLG_ADDRESSES)) {
			sieve_runtime_trace(renv, 0,
					    "looping back to line %d [%08llx]",
					    line,
					    (long long unsigned int) loop_begin);
		} else {
			sieve_runtime_trace(renv, 0,
					    "looping back to line %d", line);
		}
	}

	/* Check the code for corruption */
	if (loop->begin != loop_begin) {
		sieve_runtime_trace_error(renv, "loop begin offset invalid");
		return SIEVE_EXEC_BIN_CORRUPT;
	}

	/* Check invariants */
	i_assert(array_is_created(&interp->loop_stack));
	loops = array_get_modifiable(&interp->loop_stack, &count);
	i_assert(&loops[count-1] == loop);

	/* Return to beginning */
	interp->runenv.pc = loop_begin;
	return SIEVE_EXEC_OK;
}

int sieve_interpreter_loop_break(struct sieve_interpreter *interp,
				 struct sieve_interpreter_loop *loop)
{
	const struct sieve_runtime_env *renv = &interp->runenv;
	struct sieve_interpreter_loop *loops;
	sieve_size_t loop_end = loop->end;
	unsigned int count, i;

	/* Find the loop */
	i_assert(array_is_created(&interp->loop_stack));
	loops = array_get_modifiable(&interp->loop_stack, &count);
	i_assert(count > 0);

	i = count;
	do {
		pool_unref(&loops[i-1].pool);
		i--;
	} while (i > 0 && &loops[i] != loop);
	i_assert(&loops[i] == loop);

	/* Set new loop limit */
	if (i > 0)
		interp->loop_limit = loops[i].end;
	else
		interp->loop_limit = 0;

	/* Delete it and all deeper loops */
	array_delete(&interp->loop_stack, i, count - i);

	/* Trace */
	if (sieve_runtime_trace_active(renv, SIEVE_TRLVL_COMMANDS)) {
		unsigned int jmp_line =
			sieve_runtime_get_source_location(renv, loop_end);

		if (sieve_runtime_trace_hasflag(renv, SIEVE_TRFLG_ADDRESSES)) {
			sieve_runtime_trace(renv, 0,
					    "exiting loops at line %d [%08llx]",
					    jmp_line,
					    (long long unsigned int) loop_end);
		} else {
			sieve_runtime_trace(renv, 0,
					    "exiting loops at line %d",
					    jmp_line);
		}
	}

	/* Exit loop */
	interp->runenv.pc = loop->end;
	return SIEVE_EXEC_OK;
}

static int
sieve_interpreter_loop_break_out(struct sieve_interpreter *interp,
				 sieve_size_t target)
{
	struct sieve_interpreter_loop *loops;
	unsigned int count, i;

	if (!array_is_created(&interp->loop_stack))
		return SIEVE_EXEC_OK;

	loops = array_get_modifiable(&interp->loop_stack, &count);
	for (i = count; i > 0; i--) {
		/* We're really making sure our loop matches */
		if (loops[i-1].end > target)
			break;
	}
	if (i == count)
		return SIEVE_EXEC_OK;

	return sieve_interpreter_loop_break(interp, &loops[i]);
}

struct sieve_interpreter_loop *
sieve_interpreter_loop_get_local(struct sieve_interpreter *interp,
				 struct sieve_interpreter_loop *loop,
				 const struct sieve_extension_def *ext_def)
{
	struct sieve_interpreter_loop *loops;
	unsigned int count, i;

	if (!array_is_created(&interp->loop_stack))
		return NULL;

	loops = array_get_modifiable(&interp->loop_stack, &count);
	i_assert(loop == NULL || loop->level < count);

	for (i = (loop == NULL ? count : loop->level); i > 0; i--) {
		if (ext_def == NULL || loops[i-1].ext_def == ext_def)
			return &loops[i-1];
	}
	return NULL;
}

struct sieve_interpreter_loop *
sieve_interpreter_loop_get_global(struct sieve_interpreter *interp,
				  struct sieve_interpreter_loop *loop,
				  const struct sieve_extension_def *ext_def)
{
	struct sieve_interpreter_loop *result;

	while (interp != NULL) {
		result = sieve_interpreter_loop_get_local(interp, loop,
							  ext_def);
		if (result != NULL)
			return result;
		interp = interp->parent;
	}
	return NULL;
}

pool_t sieve_interpreter_loop_get_pool(struct sieve_interpreter_loop *loop)
{
	return loop->pool;
}

void *sieve_interpreter_loop_get_context(struct sieve_interpreter_loop *loop)
{
	return loop->context;
}

void sieve_interpreter_loop_set_context(struct sieve_interpreter_loop *loop,
					void *context)
{
	loop->context = context;
}

/*
 * Program flow
 */

void sieve_interpreter_reset(struct sieve_interpreter *interp)
{
	interp->runenv.pc = interp->reset_vector;
	interp->interrupted = FALSE;
	interp->test_result = FALSE;
	interp->runenv.result = NULL;
}

void sieve_interpreter_interrupt(struct sieve_interpreter *interp)
{
	interp->interrupted = TRUE;
}

sieve_size_t sieve_interpreter_program_counter(struct sieve_interpreter *interp)
{
	return interp->runenv.pc;
}

static int
sieve_interpreter_check_program_jump(struct sieve_interpreter *interp,
				     sieve_size_t jmp_target, bool break_loops)
{
	const struct sieve_runtime_env *renv = &interp->runenv;
	sieve_size_t loop_limit = (break_loops ? 0 : interp->loop_limit);

	if (jmp_target == 0 ||
	    jmp_target > sieve_binary_block_get_size(renv->sblock) ||
	    (loop_limit > 0 && jmp_target >= loop_limit)) {
		if (interp->loop_limit != 0) {
			sieve_runtime_trace_error(
				renv, "jump target crosses loop boundary");
		} else {
			sieve_runtime_trace_error(
				renv, "jump target out of range");
		}
		return SIEVE_EXEC_BIN_CORRUPT;
	}
	return SIEVE_EXEC_OK;
}

static int
sieve_interpreter_do_program_jump(struct sieve_interpreter *interp,
				  sieve_size_t jmp_target, bool break_loops)
{
	const struct sieve_runtime_env *renv = &interp->runenv;
	sieve_size_t *address = &(interp->runenv.pc);
	int ret;

	if (sieve_runtime_trace_active(renv, SIEVE_TRLVL_COMMANDS)) {
		unsigned int jmp_line =
			sieve_runtime_get_source_location(renv, jmp_target);

		if (sieve_runtime_trace_hasflag(renv, SIEVE_TRFLG_ADDRESSES)) {
			sieve_runtime_trace(renv, 0, "jumping to line %d [%08llx]",
					    jmp_line,
					    (long long unsigned int)jmp_target);
		} else {
			sieve_runtime_trace(renv, 0, "jumping to line %d",
					    jmp_line);
		}
	}

	if (break_loops &&
	    (ret = sieve_interpreter_loop_break_out(interp,
						    jmp_target)) <= 0)
		return ret;

	*address = jmp_target;
	return SIEVE_EXEC_OK;
}

int sieve_interpreter_program_jump_to(struct sieve_interpreter *interp,
				      sieve_size_t jmp_target,
				      bool break_loops)
{
	int ret;

	ret = sieve_interpreter_check_program_jump(interp, jmp_target,
						   break_loops);
	if (ret <= 0)
		return ret;

	return sieve_interpreter_do_program_jump(
		interp, jmp_target, break_loops);
}

int sieve_interpreter_program_jump(struct sieve_interpreter *interp,
				   bool jump, bool break_loops)
{
	const struct sieve_runtime_env *renv = &interp->runenv;
	sieve_size_t *address = &(interp->runenv.pc);
	sieve_size_t jmp_start = *address, jmp_target;
	sieve_offset_t jmp_offset;
	int ret;

	if (!sieve_binary_read_offset(renv->sblock, address, &jmp_offset)) {
		sieve_runtime_trace_error(renv, "invalid jump offset");
		return SIEVE_EXEC_BIN_CORRUPT;
	}
	jmp_target = jmp_start + jmp_offset;

	ret = sieve_interpreter_check_program_jump(interp, jmp_target,
						   break_loops);
	if (ret <= 0)
		return ret;

	if (!jump) {
		sieve_runtime_trace(renv, 0, "not jumping");
		return SIEVE_EXEC_OK;
	}

	return sieve_interpreter_do_program_jump(
		interp, jmp_target, break_loops);
}

/*
 * Test results
 */

void sieve_interpreter_set_test_result(struct sieve_interpreter *interp,
				       bool result)
{
	interp->test_result = result;
}

bool sieve_interpreter_get_test_result(struct sieve_interpreter *interp)
{
	return interp->test_result;
}

/*
 * Code execute
 */

static int sieve_interpreter_operation_execute(struct sieve_interpreter *interp)
{
	struct sieve_operation *oprtn = &(interp->oprtn);
	sieve_size_t *address = &(interp->runenv.pc);

	sieve_runtime_trace_toplevel(&interp->runenv);

	/* Read the operation */
	if (sieve_operation_read(interp->runenv.sblock, address, oprtn)) {
		const struct sieve_operation_def *op = oprtn->def;
		int result = SIEVE_EXEC_OK;

		/* Reset cached command location */
		interp->command_line = 0;

		/* Execute the operation */
		if (op->execute != NULL) { /* Noop ? */
			T_BEGIN {
				result = op->execute(&(interp->runenv),
						     address);
			} T_END;
		} else {
			sieve_runtime_trace(&interp->runenv,
					    SIEVE_TRLVL_COMMANDS,
					    "OP: %s (NOOP)",
					    sieve_operation_mnemonic(oprtn));
		}

		return result;
	}

	/* Binary corrupt */
	sieve_runtime_trace_error(&interp->runenv,
				  "Encountered invalid operation");
	return SIEVE_EXEC_BIN_CORRUPT;
}

int sieve_interpreter_continue(struct sieve_interpreter *interp,
			       bool *interrupted)
{
	const struct sieve_runtime_env *renv = &interp->runenv;
	const struct sieve_execute_env *eenv = renv->exec_env;
	struct cpu_limit *climit = NULL;
	sieve_size_t *address = &(interp->runenv.pc);
	struct sieve_instance *svinst = eenv->svinst;
	struct sieve_exec_status *exec_status = eenv->exec_status;
	struct sieve_resource_usage rusage;
	int ret = SIEVE_EXEC_OK;

	sieve_result_ref(renv->result);
	interp->interrupted = FALSE;

	if (interrupted != NULL)
		*interrupted = FALSE;

	if (svinst->max_cpu_time_secs > 0) {
		climit = cpu_limit_init(svinst->max_cpu_time_secs,
					CPU_LIMIT_TYPE_USER);
	}

	while (ret == SIEVE_EXEC_OK && !interp->interrupted &&
	       *address < sieve_binary_block_get_size(renv->sblock)) {
		if (climit != NULL && cpu_limit_exceeded(climit)) {
			sieve_runtime_error(
				renv, NULL,
				"execution exceeded CPU time limit");
			ret = SIEVE_EXEC_RESOURCE_LIMIT;
			break;
		}
		if (interp->loop_limit != 0 && *address > interp->loop_limit) {
			sieve_runtime_trace_error(
				renv, "program crossed loop boundary");
			ret = SIEVE_EXEC_BIN_CORRUPT;
			break;
		}

		ret = sieve_interpreter_operation_execute(interp);
	}

	if (climit != NULL) {
		sieve_resource_usage_init(&rusage);
		rusage.cpu_time_msecs =
			cpu_limit_get_usage_msecs(climit, CPU_LIMIT_TYPE_USER);
		sieve_resource_usage_add(&interp->rusage, &rusage);

		cpu_limit_deinit(&climit);
	}

	if (ret != SIEVE_EXEC_OK) {
		sieve_runtime_trace(&interp->runenv, SIEVE_TRLVL_NONE,
				    "[[EXECUTION ABORTED]]");
	}

	if (interrupted != NULL)
		*interrupted = interp->interrupted;

	if (!interp->interrupted) {
		exec_status->resource_usage = interp->rusage;

		struct event_passthrough *e =
			event_create_passthrough(interp->runenv.event)->
			set_name("sieve_runtime_script_finished");
		switch (ret) {
		case SIEVE_EXEC_OK:
			break;
		case SIEVE_EXEC_FAILURE:
			e->add_str("error", "Failed");
			break;
		case SIEVE_EXEC_TEMP_FAILURE:
			e->add_str("error", "Failed temporarily");
			break;
		case SIEVE_EXEC_BIN_CORRUPT:
			e->add_str("error", "Binary corrupt");
			break;
		case SIEVE_EXEC_RESOURCE_LIMIT:
			e->add_str("error", "Resource limit exceeded");
			break;
		case SIEVE_EXEC_KEEP_FAILED:
			/* Not supposed to occur at runtime */
			i_unreached();
		}
		e_debug(e->event(), "Finished running script `%s' "
			"(status=%s, resource usage: %s)",
			sieve_binary_source(interp->runenv.sbin),
			sieve_execution_exitcode_to_str(ret),
			sieve_resource_usage_get_summary(&interp->rusage));
		interp->running = FALSE;
	}

	sieve_result_unref(&interp->runenv.result);
	return ret;
}

int sieve_interpreter_start(struct sieve_interpreter *interp,
			    struct sieve_result *result, bool *interrupted)
{
	struct sieve_interpreter_extension_reg *eregs;
	unsigned int ext_count, i;
	int ret;

	struct event_passthrough *e =
		event_create_passthrough(interp->runenv.event)->
		set_name("sieve_runtime_script_started");
	e_debug(e->event(), "Started running script `%s'",
		sieve_binary_source(interp->runenv.sbin));

	interp->running = TRUE;
	interp->runenv.result = result;
	interp->runenv.msgctx = sieve_result_get_message_context(result);

	sieve_resource_usage_init(&interp->rusage);

	/* Signal registered extensions that the interpreter is being run */
	eregs = array_get_modifiable(&interp->extensions, &ext_count);
	for (i = 0; i < ext_count; i++) {
		if (!eregs[i].deferred) {
			eregs[i].started = TRUE;
			if (eregs[i].intext != NULL &&
			    eregs[i].intext->run != NULL &&
			    (ret = eregs[i].intext->run(
				eregs[i].ext, &interp->runenv,
				eregs[i].context, FALSE)) <= 0)
				return ret;
		}
	}

	return sieve_interpreter_continue(interp, interrupted);
}

int sieve_interpreter_run(struct sieve_interpreter *interp,
			  struct sieve_result *result)
{
	sieve_interpreter_reset(interp);

	return sieve_interpreter_start(interp, result, NULL);
}

/*
 * Error handling
 */

static inline void ATTR_FORMAT(3, 0)
sieve_runtime_logv(const struct sieve_runtime_env *renv,
		   const struct sieve_error_params *params,
		   const char *fmt, va_list args)
{
	struct sieve_error_params new_params = *params;

	new_params.event = renv->event;
	T_BEGIN {
		if (new_params.location == NULL) {
			new_params.location =
				sieve_runtime_get_full_command_location(renv);
		}

		sieve_logv(renv->ehandler, params, fmt, args);
	} T_END;
}

#undef sieve_runtime_error
void sieve_runtime_error(const struct sieve_runtime_env *renv,
			 const char *csrc_filename, unsigned int csrc_linenum,
			 const char *location, const char *fmt, ...)
{
	struct sieve_error_params params = {
		.log_type = LOG_TYPE_ERROR,
		.csrc = {
			.filename = csrc_filename,
			.linenum = csrc_linenum,
		},
		.location = location,
	};
	va_list args;

	va_start(args, fmt);
	sieve_runtime_logv(renv, &params, fmt, args);
	va_end(args);
}

#undef sieve_runtime_warning
void sieve_runtime_warning(const struct sieve_runtime_env *renv,
			   const char *csrc_filename, unsigned int csrc_linenum,
			   const char *location, const char *fmt, ...)
{
	struct sieve_error_params params = {
		.log_type = LOG_TYPE_WARNING,
		.csrc = {
			.filename = csrc_filename,
			.linenum = csrc_linenum,
		},
		.location = location,
	};
	va_list args;

	va_start(args, fmt);
	sieve_runtime_logv(renv, &params, fmt, args);
	va_end(args);
}

#undef sieve_runtime_log
void sieve_runtime_log(const struct sieve_runtime_env *renv,
		       const char *csrc_filename, unsigned int csrc_linenum,
		       const char *location, const char *fmt, ...)
{
	struct sieve_error_params params = {
		.log_type = LOG_TYPE_INFO,
		.csrc = {
			.filename = csrc_filename,
			.linenum = csrc_linenum,
		},
		.location = location,
	};
	va_list args;

	va_start(args, fmt);
	sieve_runtime_logv(renv, &params, fmt, args);
	va_end(args);
}

#undef sieve_runtime_critical
void sieve_runtime_critical(const struct sieve_runtime_env *renv,
			    const char *csrc_filename,
			    unsigned int csrc_linenum,
			    const char *location, const char *user_prefix,
			    const char *fmt, ...)
{
	const struct sieve_execute_env *eenv = renv->exec_env;
	struct sieve_error_params params = {
		.log_type = LOG_TYPE_ERROR,
		.csrc = {
			.filename = csrc_filename,
			.linenum = csrc_linenum,
		},
		.location = location,
	};
	va_list args;

	va_start(args, fmt);

	params.event = renv->event;
	T_BEGIN {
		if (params.location == NULL) {
			params.location =
				sieve_runtime_get_full_command_location(renv);
		}

		sieve_criticalv(eenv->svinst, renv->ehandler, &params,
				user_prefix, fmt, args);
	} T_END;

	va_end(args);
}

#undef sieve_runtime_mail_error
int sieve_runtime_mail_error(const struct sieve_runtime_env *renv,
			     struct mail *mail,
			     const char *csrc_filename,
			     unsigned int csrc_linenum,
			     const char *fmt, ...)
{
	const char *error_msg, *user_prefix;
	va_list args;

	error_msg = mailbox_get_last_internal_error(mail->box, NULL);

	va_start(args, fmt);
	user_prefix = t_strdup_vprintf(fmt, args);
	sieve_runtime_critical(renv, csrc_filename, csrc_linenum,
			       NULL, user_prefix, "%s: %s",
			       user_prefix, error_msg);
	va_end(args);

	return 	SIEVE_EXEC_TEMP_FAILURE;
}