aboutsummaryrefslogtreecommitdiff
path: root/lib/libcurses/director/testlang_parse.y
blob: 37c813fa6c27aeabf7bd85e8997339a447a28d8e (plain) (blame)
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
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
%{
/*	$NetBSD: testlang_parse.y,v 1.13 2012/09/19 11:51:56 blymn Exp $	*/

/*-
 * Copyright 2009 Brett Lymn <blymn@NetBSD.org>
 *
 * All rights reserved.
 *
 * This code has been donated to The NetBSD Foundation by the Author.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software withough specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 */
#include <assert.h>
#include <curses.h>
#include <errno.h>
#include <fcntl.h>
#include <err.h>
#include <unistd.h>
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <sys/syslimits.h>
#include <time.h>
#include <vis.h>
#include <stdint.h>
#include "returns.h"

#define YYDEBUG 1

extern int verbose;
extern int cmdpipe[2];
extern int slvpipe[2];
extern int master;
extern struct pollfd readfd;
extern char *check_path;
extern char *cur_file;		/* from director.c */

int yylex(void);

size_t line;

static int input_delay;

/* time delay between inputs chars - default to 0.1ms minimum to prevent
 * problems with input tests
 */
#define DELAY_MIN 0.1

/* time delay after a function call - allows the slave time to
 * run the function and output data before we do other actions.
 * Set this to 50ms.
 */
#define POST_CALL_DELAY 50

static struct timespec delay_spec = {0, 1000 * DELAY_MIN};
static struct timespec delay_post_call = {0, 1000 * POST_CALL_DELAY};

static char *input_str;	/* string to feed in as input */
static bool no_input;	/* don't need more input */

#define READ_PIPE  0
#define WRITE_PIPE 1

const char *returns_enum_names[] = {
	"unused", "numeric", "string", "byte", "ERR", "OK", "NULL", "not NULL",
	"variable", "reference", "returns count", "slave error"
};

typedef enum {
	arg_static,
	arg_byte,
	arg_var,
	arg_null
} args_state_t;

static const char *args_enum_names[] = {
	"static", "byte", "var", "NULL"
};

typedef struct {
	args_state_t	arg_type;
	size_t		arg_len;
	char		*arg_string;
	int		var_index;
} args_t;

typedef struct {
	char		*function;
	int		nrets;		/* number of returns */
	returns_t	*returns;	/* array of expected returns */
	int		nargs;		/* number of arguments */
	args_t		*args;		/* arguments for the call */
} cmd_line_t;

static cmd_line_t	command;

typedef struct {
	char *name;
	size_t len;
	returns_enum_t type;
	void *value;
} var_t;

static size_t nvars; 		/* Number of declared variables */
static var_t *vars; 		/* Variables defined during the test. */

static int	check_function_table(char *, const char *[], int);
static int	find_var_index(const char *);
static void 	assign_arg(args_state_t, void *);
static int	assign_var(char *);
void		init_parse_variables(int);
static void	validate(int, void *);
static void	validate_return(const char *, const char *, int);
static void	validate_variable(int, returns_enum_t, const void *, int, int);
static void	validate_byte(returns_t *, returns_t *, int);
static void	write_cmd_pipe(char *);
static void	write_cmd_pipe_args(args_state_t, void *);
static void	read_cmd_pipe(returns_t *);
static void	write_func_and_args(void);
static void	compare_streams(char *, bool);
static void	do_function_call(size_t);
static void	save_slave_output(bool);
static void	validate_type(returns_enum_t, returns_t *, int);
static void	set_var(returns_enum_t, char *, void *);
static void	validate_reference(int, void *);
static char	*numeric_or(char *, char *);
static char	*get_numeric_var(const char *);
static void	perform_delay(struct timespec *);

static const char *input_functions[] = {
	"getch", "getnstr", "getstr", "mvgetnstr", "mvgetstr", "mvgetnstr",
	"mvgetstr", "mvscanw", "mvwscanw", "scanw", "wgetch", "wgetnstr",
	"wgetstr"
};

static const unsigned ninput_functions =
	sizeof(input_functions) / sizeof(char *);

saved_data_t saved_output;

%}

%union {
	char *string;
	returns_t *retval;
}

%token <string> PATH
%token <string> STRING
%token <retval> BYTE
%token <string> VARNAME
%token <string> FILENAME
%token <string> VARIABLE
%token <string> REFERENCE
%token <string> NULL_RET
%token <string> NON_NULL
%token <string> ERR_RET
%token <string> OK_RET
%token <string> numeric
%token <string> DELAY
%token <string> INPUT
%token <string> COMPARE
%token <string> COMPAREND
%token <string> ASSIGN
%token EOL CALL CHECK NOINPUT OR LHB RHB
%token CALL2 CALL3 CALL4 DRAIN

%nonassoc OR

%%

statement	:	/* empty */
		| assign statement
		| call statement
		| call2 statement
		| call3 statement
		| call4 statement
		| check statement
		| delay statement
		| input statement
		| noinput statement
		| compare statement
		| comparend statement
		| eol statement
		;

assign		: ASSIGN VARNAME numeric {set_var(ret_number, $2, $3);} eol
		| ASSIGN VARNAME LHB expr RHB {set_var(ret_number, $2, $<string>4);} eol
		| ASSIGN VARNAME STRING {set_var(ret_string, $2, $3);} eol
		| ASSIGN VARNAME BYTE {set_var(ret_byte, $2, $3);} eol
		;

call		: CALL result fn_name args eol {
	do_function_call(1);
}
		;

call2		: CALL2 result result fn_name args eol {
	do_function_call(2);
}
		;

call3		: CALL3 result result result fn_name args eol {
	do_function_call(3);
}
		;

call4		: CALL4 result result result result fn_name args eol {
	do_function_call(4);
 }
		;

check		: CHECK var returns eol {
	returns_t retvar;
	var_t *vptr;
	if (command.returns[0].return_index == -1)
		err(1, "Undefined variable in check statement, line %zu"
		    " of file %s", line, cur_file);

	if (verbose) {
		fprintf(stderr, "Checking contents of variable %s for %s\n",
		    vars[command.returns[0].return_index].name,
		    returns_enum_names[command.returns[1].return_type]);
	}

	if (((command.returns[1].return_type == ret_byte) &&
	     (vars[command.returns[0].return_index].type != ret_byte)) ||
	    vars[command.returns[0].return_index].type != ret_string)
		err(1, "Var type %s (%d) does not match return type %s (%d)",
		    returns_enum_names[
		    vars[command.returns[0].return_index].type],
		    vars[command.returns[0].return_index].type,
		    returns_enum_names[command.returns[1].return_type],
		    command.returns[1].return_type);

	switch (command.returns[1].return_type) {
	case ret_err:
		validate_variable(0, ret_string, "ERR",
				  command.returns[0].return_index, 0);
		break;

	case ret_ok:
		validate_variable(0, ret_string, "OK",
				  command.returns[0].return_index, 0);
		break;

	case ret_null:
		validate_variable(0, ret_string, "NULL",
				  command.returns[0].return_index, 0);
		break;

	case ret_nonnull:
		validate_variable(0, ret_string, "NULL",
				  command.returns[0].return_index, 1);
		break;

	case ret_string:
	case ret_number:
		if (verbose) {
			fprintf(stderr, " %s == returned %s\n",
			    (const char *)command.returns[1].return_value,
			    (const char *)
			    vars[command.returns[0].return_index].value);
		}
		validate_variable(0, ret_string,
		    command.returns[1].return_value,
		    command.returns[0].return_index, 0);
		break;

	case ret_byte:
		vptr = &vars[command.returns[0].return_index];
		retvar.return_len = vptr->len;
		retvar.return_type = vptr->type;
		retvar.return_value = vptr->value;
		validate_byte(&retvar, &command.returns[1], 0);
		break;

	default:
		err(1, "Malformed check statement at line %zu "
		    "of file %s", line, cur_file);
		break;
	}

	init_parse_variables(0);
 }
		;

delay		: DELAY numeric eol {
	/* set the inter-character delay */
	if (sscanf($2, "%d", &input_delay) == 0)
		err(1, "delay specification %s could not be converted to "
		    "numeric at line %zu of file %s", $2, line, cur_file);
	if (verbose) {
		fprintf(stderr, "Set input delay to %d ms\n", input_delay);
	}

	if (input_delay < DELAY_MIN)
		input_delay = DELAY_MIN;
	/*
	 * Fill in the timespec structure now ready for use later.
	 * The delay is specified in milliseconds so convert to timespec
	 * values
	 */
	delay_spec.tv_sec = input_delay / 1000;
	delay_spec.tv_nsec = (input_delay - 1000 * delay_spec.tv_sec) * 1000;
	if (verbose) {
		fprintf(stderr, "set delay to %jd.%jd\n",
		    (intmax_t)delay_spec.tv_sec,
		    (intmax_t)delay_spec.tv_nsec);
	}

	init_parse_variables(0);
 }
	;

input		: INPUT STRING eol {
	if (input_str != NULL) {
		warnx("%s, %zu: Discarding unused input string",
		    cur_file, line);
		free(input_str);
	}

	if ((input_str = malloc(strlen($2) + 1)) == NULL)
		err(2, "Cannot allocate memory for input string");

	strlcpy(input_str, $2, strlen($2) + 1);
}
	;


noinput		: NOINPUT eol {
	if (input_str != NULL) {
		warnx("%s, %zu: Discarding unused input string",
		    cur_file, line);
		free(input_str);
	}

	no_input = true;
 }

compare		: COMPARE PATH eol
		| COMPARE FILENAME eol
{
	compare_streams($2, true);
}
	;


comparend	: COMPAREND PATH eol
		| COMPAREND FILENAME eol
{
	compare_streams($2, false);
}
	;


result		: returns
		| var
		| reference
		;

returns		: numeric { assign_rets(ret_number, $1); }
		| LHB expr RHB { assign_rets(ret_number, $<string>2); }
		| STRING { assign_rets(ret_string, $1); }
		| BYTE { assign_rets(ret_byte, (void *) $1); }
		| ERR_RET { assign_rets(ret_err, NULL); }
		| OK_RET { assign_rets(ret_ok, NULL); }
		| NULL_RET { assign_rets(ret_null, NULL); }
		| NON_NULL { assign_rets(ret_nonnull, NULL); }
		;

var		: VARNAME {
	assign_rets(ret_var, $1);
 }
		;

reference	: VARIABLE {
	assign_rets(ret_ref, $1);
 }

fn_name		: VARNAME {
	if (command.function != NULL)
		free(command.function);

	command.function = malloc(strlen($1) + 1);
	if (command.function == NULL)
		err(1, "Could not allocate memory for function name");
	strcpy(command.function, $1);
 }
		;

expr		: numeric
		| VARIABLE
			{ $<string>$ = get_numeric_var($1); }
		| expr OR expr
			{ $<string>$ = numeric_or($<string>1, $<string>3); }
		;

args		: /* empty */
		| LHB expr RHB { assign_arg(arg_static, $<string>2); } args
		| numeric { assign_arg(arg_static, $1); } args
		| STRING { assign_arg(arg_static, $1); } args
		| BYTE { assign_arg(arg_byte, $1); } args
		| PATH { assign_arg(arg_static, $1); } args
		| FILENAME { assign_arg(arg_static, $1); } args
		| VARNAME { assign_arg(arg_static, $1); } args
		| VARIABLE  { assign_arg(arg_var, $1); } args
		| NULL_RET { assign_arg(arg_null, $1); } args
		;

eol		: EOL
		;

%%

static void
excess(const char *fname, size_t lineno, const char *func, const char *comment,
    const void *data, size_t datalen)
{
	size_t dstlen = datalen * 4 + 1;
	char *dst = malloc(dstlen);

	if (dst == NULL)
		err(1, "malloc");

	if (strnvisx(dst, dstlen, data, datalen, VIS_WHITE | VIS_OCTAL) == -1)
		err(1, "strnvisx");

	warnx("%s, %zu: [%s] Excess %zu bytes%s [%s]",
	    fname, lineno, func, datalen, comment, dst);
	free(dst);
}

/*
 * Get the value of a variable, error if the variable has not been set or
 * is not a numeric type.
 */
static char *
get_numeric_var(const char *var)
{
	int i;

	if ((i = find_var_index(var)) < 0)
		err(1, "Variable %s is undefined", var);

	if (vars[i].type != ret_number)
		err(1, "Variable %s is not a numeric type", var);

	return vars[i].value;
}

/*
 * Perform a bitwise OR on two numbers and return the result.
 */
static char *
numeric_or(char *n1, char *n2)
{
	unsigned long i1, i2, result;
	char *ret;

	i1 = strtoul(n1, NULL, 10);
	i2 = strtoul(n2, NULL, 10);

	result = i1 | i2;
	asprintf(&ret, "%lu", result);

	if (verbose) {
		fprintf(stderr, "numeric or of 0x%lx (%s) and 0x%lx (%s)"
		    " results in 0x%lx (%s)\n",
		    i1, n1, i2, n2, result, ret);
	}

	return ret;
}

/*
 * Sleep for the specified time, handle the sleep getting interrupted
 * by a signal.
 */
static void
perform_delay(struct timespec *ts)
{
	struct timespec delay_copy, delay_remainder;

	delay_copy = *ts;
	while (nanosleep(&delay_copy, &delay_remainder) < 0) {
		if (errno != EINTR)
			err(2, "nanosleep returned error");
		delay_copy = delay_remainder;
	}
}

/*
 * Assign the value given to the named variable.
 */
static void
set_var(returns_enum_t type, char *name, void *value)
{
	int i;
	char *number;
	returns_t *ret;

	i = find_var_index(name);
	if (i < 0)
		i = assign_var(name);

	vars[i].type = type;
	if ((type == ret_number) || (type == ret_string)) {
		number = value;
		vars[i].len = strlen(number) + 1;
		vars[i].value = malloc(vars[i].len + 1);
		if (vars[i].value == NULL)
			err(1, "Could not malloc memory for assign string");
		strcpy(vars[i].value, number);
	} else {
		/* can only be a byte value */
		ret = value;
		vars[i].len = ret->return_len;
		vars[i].value = malloc(vars[i].len);
		if (vars[i].value == NULL)
			err(1, "Could not malloc memory to assign byte string");
		memcpy(vars[i].value, ret->return_value, vars[i].len);
	}
}

/*
 * Add a new variable to the vars array, the value will be assigned later,
 * when a test function call returns.
 */
static int
assign_var(char *varname)
{
	var_t *temp;
	char *name;

	if ((name = malloc(strlen(varname) + 1)) == NULL)
		err(1, "Alloc of varname failed");

	if ((temp = realloc(vars, sizeof(*temp) * (nvars + 1))) == NULL) {
		free(name);
		err(1, "Realloc of vars array failed");
	}

	strcpy(name, varname);
	vars = temp;
	vars[nvars].name = name;
	vars[nvars].len = 0;
	vars[nvars].value = NULL;
	nvars++;

	return (nvars - 1);
}

/*
 * Allocate and assign a new argument of the given type.
 */
static void
assign_arg(args_state_t arg_type, void *arg)
{
	args_t *temp, cur;
	char *str = arg;
	returns_t *ret;

	if (verbose) {
		fprintf(stderr, "function is >%s<, adding arg >%s< type %s\n",
		       command.function, str, args_enum_names[arg_type]);
	}

	cur.arg_type = arg_type;
	switch (arg_type) {
	case arg_var:
		cur.var_index = find_var_index(arg);
		if (cur.var_index < 0)
			err(1, "Invalid variable %s at line %zu of file %s",
			    str, line, cur_file);
		cur.arg_type = ret_string;
		break;

	case arg_byte:
		ret = arg;
		cur.arg_len = ret->return_len;
		cur.arg_string = malloc(cur.arg_len);
		if (cur.arg_string == NULL)
			err(1, "Could not malloc memory for arg bytes");
		memcpy(cur.arg_string, ret->return_value, cur.arg_len);
		break;

	case arg_null:
		cur.arg_len = 0;
		cur.arg_string = NULL;
		break;

	default:
		cur.arg_len = strlen(str);
		cur.arg_string = malloc(cur.arg_len + 1);
		if (cur.arg_string == NULL)
			err(1, "Could not malloc memory for arg string");
		strcpy(cur.arg_string, arg);
	}

	temp = realloc(command.args, sizeof(*temp) * (command.nargs + 1));
	if (temp == NULL)
		err(1, "Failed to reallocate args");
	command.args = temp;
	memcpy(&command.args[command.nargs], &cur, sizeof(args_t));
	command.nargs++;
}

/*
 * Allocate and assign a new return.
 */
static void
assign_rets(returns_enum_t ret_type, void *ret)
{
	returns_t *temp, cur;
	char *ret_str;
	returns_t *ret_ret;

	cur.return_type = ret_type;
	if (ret_type != ret_var) {
		if ((ret_type == ret_number) || (ret_type == ret_string)) {
			ret_str = ret;
			cur.return_len = strlen(ret_str) + 1;
			cur.return_value = malloc(cur.return_len + 1);
			if (cur.return_value == NULL)
				err(1,
				    "Could not malloc memory for arg string");
			strcpy(cur.return_value, ret_str);
		} else if (ret_type == ret_byte) {
			ret_ret = ret;
			cur.return_len = ret_ret->return_len;
			cur.return_value = malloc(cur.return_len);
			if (cur.return_value == NULL)
				err(1,
				    "Could not malloc memory for byte string");
			memcpy(cur.return_value, ret_ret->return_value,
			       cur.return_len);
		} else if (ret_type == ret_ref) {
			if ((cur.return_index = find_var_index(ret)) < 0)
				err(1, "Undefined variable reference");
		}
	} else {
		cur.return_index = find_var_index(ret);
		if (cur.return_index < 0)
			cur.return_index = assign_var(ret);
	}

	temp = realloc(command.returns, sizeof(*temp) * (command.nrets + 1));
	if (temp == NULL)
		err(1, "Failed to reallocate returns");
	command.returns = temp;
	memcpy(&command.returns[command.nrets], &cur, sizeof(returns_t));
	command.nrets++;
}

/*
 * Find the given variable name in the var array and return the i
 * return -1 if var is not found.
 */
static int
find_var_index(const char *var_name)
{
	int result;
	size_t i;

	result = -1;

	for (i = 0; i < nvars; i++) {
		if (strcmp(var_name, vars[i].name) == 0) {
			result = i;
			break;
		}
	}

	return result;
}

/*
 * Check the given function name in the given table of names, return 1 if
 * there is a match.
 */
static int check_function_table(char *function, const char *table[],
				int nfunctions)
{
	int i;

	for (i = 0; i < nfunctions; i++) {
		if ((strlen(function) == strlen(table[i])) &&
		    (strcmp(function, table[i]) == 0))
			return 1;
	}

	return 0;
}

/*
 * Compare the output from the slave against the given file and report
 * any differences.
 */
static void
compare_streams(char *filename, bool discard)
{
	char check_file[PATH_MAX], drain[100], ref, data;
	struct pollfd fds[2];
	int nfd, check_fd;
	ssize_t result;
	size_t offs;

	/*
	 * Don't prepend check path iff check file has an absolute
	 * path.
	 */
	if (filename[0] != '/') {
		if (strlcpy(check_file, check_path, sizeof(check_file))
		    >= sizeof(check_file))
			err(2, "CHECK_PATH too long");

		if (strlcat(check_file, "/", sizeof(check_file))
		    >= sizeof(check_file))
			err(2, "Could not append / to check file path");
	} else {
		check_file[0] = '\0';
	}

	if (strlcat(check_file, filename, sizeof(check_file))
	    >= sizeof(check_file))
		err(2, "Path to check file path overflowed");

	if ((check_fd = open(check_file, O_RDONLY, 0)) < 0)
		err(2, "failed to open file %s line %zu of file %s",
		    check_file, line, cur_file);

	fds[0].fd = check_fd;
	fds[0].events = POLLIN;
	fds[1].fd = master;
	fds[1].events = POLLIN;

	nfd = 2;
	/*
	 * if we have saved output then only check for data in the
	 * reference file since the slave data may already be drained.
	 */
	if (saved_output.count > 0)
		nfd = 1;

	offs = 0;
	while (poll(fds, nfd, 500) == nfd) {
		if (fds[0].revents & POLLIN) {
			if ((result = read(check_fd, &ref, 1)) < 1) {
				if (result != 0) {
					err(2,
					    "Bad read on file %s", check_file);
				} else {
					break;
				}
			}
		}

		if (saved_output.count > 0) {
			data = saved_output.data[saved_output.readp];
			saved_output.count--;
			saved_output.readp++;
			/* run out of saved data, switch to file */
			if (saved_output.count == 0)
				nfd = 2;
		} else {
			if (fds[0].revents & POLLIN) {
				if (read(master, &data, 1) < 1)
					err(2, "Bad read on slave pty");
			} else
				continue;
		}

		if (verbose) {
			fprintf(stderr, "Comparing reference byte 0x%x (%c)"
				" against slave byte 0x%x (%c)\n",
				ref, (ref >= ' ') ? ref : '-',
				data, (data >= ' ' )? data : '-');
		}

		if (ref != data) {
			errx(2, "%s, %zu: refresh data from slave does "
			    "not match expected from file %s offs %zu "
			    "[reference 0x%x (%c) != slave 0x%x (%c)]",
			    cur_file, line, check_file, offs,
			    ref, (ref >= ' ') ? ref : '-',
			    data, (data >= ' ') ? data : '-');
		}

		offs++;
	}


	if (saved_output.count > 0)
		excess(cur_file, line, __func__, " from slave",
		    &saved_output.data[saved_output.readp], saved_output.count);

	/* discard any excess saved output if required */
	if (discard) {
		saved_output.count = 0;
		saved_output.readp = 0;
	}

	if ((result = poll(&fds[0], 2, 0)) != 0) {
		if (result == -1)
			err(2, "poll of file descriptors failed");

		if ((fds[1].revents & POLLIN) == POLLIN) {
			save_slave_output(true);
		} else if ((fds[0].revents & POLLIN) == POLLIN) {
			/*
			 * handle excess in file if it exists.  Poll
			 * says there is data until EOF is read.
			 * Check next read is EOF, if it is not then
			 * the file really has more data than the
			 * slave produced so flag this as a warning.
			 */
			result = read(check_fd, drain, sizeof(drain));
			if (result == -1)
				err(1, "read of data file failed");

			if (result > 0) {
				excess(check_file, 0, __func__, "", drain,
				    result);
			}
		}
	}

	close(check_fd);
}

/*
 * Pass a function call and arguments to the slave and wait for the
 * results.  The variable nresults determines how many returns we expect
 * back from the slave.  These results will be validated against the
 * expected returns or assigned to variables.
 */
static void
do_function_call(size_t nresults)
{
#define MAX_RESULTS 4
	char *p;
	int do_input;
	size_t i;
	struct pollfd fds[3];
	returns_t response[MAX_RESULTS], returns_count;
	assert(nresults <= MAX_RESULTS);

	do_input = check_function_table(command.function, input_functions,
	    ninput_functions);

	write_func_and_args();

	/*
	 * We should get the number of returns back here, grab it before
	 * doing input otherwise it will confuse the input poll
	 */
	read_cmd_pipe(&returns_count);
	if (returns_count.return_type != ret_count)
		err(2, "expected return type of ret_count but received %s",
		    returns_enum_names[returns_count.return_type]);

	perform_delay(&delay_post_call); /* let slave catch up */

	if (verbose) {
		fprintf(stderr, "Expect %zu results from slave, slave "
		    "reported %zu\n", nresults, returns_count.return_len);
	}

	if ((no_input == false) && (do_input == 1)) {
		if (verbose) {
			fprintf(stderr, "doing input with inputstr >%s<\n",
			    input_str);
		}

		if (input_str == NULL)
			errx(2, "%s, %zu: Call to input function "
			    "but no input defined", cur_file, line);

		fds[0].fd = slvpipe[READ_PIPE];
		fds[0].events = POLLIN;
		fds[1].fd = master;
		fds[1].events = POLLOUT;
 		p = input_str;
		save_slave_output(false);
		while(*p != '\0') {
			perform_delay(&delay_spec);

			if (poll(fds, 2, 0) < 0)
				err(2, "poll failed");
			if (fds[0].revents & POLLIN) {
				warnx("%s, %zu: Slave function "
				    "returned before end of input string",
				    cur_file, line);
				break;
			}
			if ((fds[1].revents & POLLOUT) == 0)
				continue;
			if (verbose) {
				fprintf(stderr, "Writing char >%c< to slave\n",
				    *p);
			}
			if (write(master, p, 1) != 1) {
				warn("%s, %zu: Slave function write error",
				    cur_file, line);
				break;
			}
			p++;

		}
		save_slave_output(false);

		if (verbose) {
			fprintf(stderr, "Input done.\n");
		}

		/* done with the input string, free the resources */
		free(input_str);
		input_str = NULL;
	}

	if (verbose) {
		fds[0].fd = slvpipe[READ_PIPE];
		fds[0].events = POLLIN;

		fds[1].fd = slvpipe[WRITE_PIPE];
		fds[1].events = POLLOUT;

		fds[2].fd = master;
		fds[2].events = POLLIN | POLLOUT;

		i = poll(&fds[0], 3, 1000);
		fprintf(stderr, "Poll returned %zu\n", i);
		for (i = 0; i < 3; i++) {
			fprintf(stderr, "revents for fd[%zu] = 0x%x\n",
				i, fds[i].revents);
		}
	}

	/* drain any trailing output */
	save_slave_output(false);

	for (i = 0; i < returns_count.return_len; i++) {
		read_cmd_pipe(&response[i]);
	}

	/*
	 * Check for a slave error in the first return slot, if the
	 * slave errored then we may not have the number of returns we
	 * expect but in this case we should report the slave error
	 * instead of a return count mismatch.
	 */
	if ((returns_count.return_len > 0) &&
	    (response[0].return_type == ret_slave_error))
		err(2, "Slave returned error: %s",
		    (const char *)response[0].return_value);

	if (returns_count.return_len != nresults)
		err(2, "Incorrect number of returns from slave, expected %zu "
		    "but received %zu", nresults, returns_count.return_len);

	if (verbose) {
		for (i = 0; i < nresults; i++) {
			if ((response[i].return_type != ret_byte) &&
			    (response[i].return_type != ret_err) &&
			    (response[i].return_type != ret_ok))
				fprintf(stderr,
					"received response >%s< "
					"expected",
					(const char *)response[i].return_value);
			else
				fprintf(stderr, "received");

			fprintf(stderr, " return_type %s\n",
			    returns_enum_names[command.returns[i].return_type]);
		}
	}

	for (i = 0; i < nresults; i++) {
		if (command.returns[i].return_type != ret_var) {
			validate(i, &response[i]);
		} else {
			vars[command.returns[i].return_index].len =
				response[i].return_len;
			vars[command.returns[i].return_index].value =
				response[i].return_value;
			vars[command.returns[i].return_index].type =
				response[i].return_type;
		}
	}

	if (verbose && (saved_output.count > 0))
		excess(cur_file, line, __func__, " from slave",
		    &saved_output.data[saved_output.readp], saved_output.count);

	init_parse_variables(0);
}

/*
 * Write the function and command arguments to the command pipe.
 */
static void
write_func_and_args(void)
{
	int i;

	if (verbose) {
		fprintf(stderr, "calling function >%s<\n", command.function);
	}

	write_cmd_pipe(command.function);
	for (i = 0; i < command.nargs; i++) {
		if (command.args[i].arg_type == arg_var)
			write_cmd_pipe_args(command.args[i].arg_type,
					    &vars[command.args[i].var_index]);
		else
			write_cmd_pipe_args(command.args[i].arg_type,
					    &command.args[i]);
	}

	write_cmd_pipe(NULL); /* signal end of arguments */
}

/*
 * Initialise the command structure - if initial is non-zero then just set
 * everything to sane values otherwise free any memory that was allocated
 * when building the structure.
 */
void
init_parse_variables(int initial)
{
	int i, result;
	struct pollfd slave_pty;

	if (initial == 0) {
		free(command.function);
		for (i = 0; i < command.nrets; i++) {
			if (command.returns[i].return_type == ret_number)
				free(command.returns[i].return_value);
		}
		free(command.returns);

		for (i = 0; i < command.nargs; i++) {
			if (command.args[i].arg_type != arg_var)
				free(command.args[i].arg_string);
		}
		free(command.args);
	} else {
		line = 0;
		input_delay = 0;
		vars = NULL;
		nvars = 0;
		input_str = NULL;
		saved_output.allocated = 0;
		saved_output.count = 0;
		saved_output.readp = 0;
		saved_output.data = NULL;
	}

	no_input = false;
	command.function = NULL;
	command.nargs = 0;
	command.args = NULL;
	command.nrets = 0;
	command.returns = NULL;

	/*
	 * Check the slave pty for stray output from the slave, at this
	 * point we should not see any data as it should have been
	 * consumed by the test functions.  If we see data then we have
	 * either a bug or are not handling an output generating function
	 * correctly.
	 */
	slave_pty.fd = master;
	slave_pty.events = POLLIN;
	result = poll(&slave_pty, 1, 0);

	if (result < 0)
		err(2, "Poll of slave pty failed");
	else if (result > 0)
		warnx("%s, %zu: Unexpected data from slave", cur_file, line);
}

/*
 * Validate the response against the expected return.  The variable
 * i is the i into the rets array in command.
 */
static void
validate(int i, void *data)
{
	char *response;
	returns_t *byte_response;

	byte_response = data;
	if ((command.returns[i].return_type != ret_byte) &&
	    (command.returns[i].return_type != ret_err) &&
	    (command.returns[i].return_type != ret_ok)) {
		if ((byte_response->return_type == ret_byte) ||
		    (byte_response->return_type == ret_err) ||
		    (byte_response->return_type == ret_ok))
			err(1, "%s: expecting type %s, received type %s"
			    " at line %zu of file %s", __func__,
			    returns_enum_names[command.returns[i].return_type],
			    returns_enum_names[byte_response->return_type],
			    line, cur_file);

		response = byte_response->return_value;
	}

	switch (command.returns[i].return_type) {
	case ret_err:
		validate_type(ret_err, byte_response, 0);
		break;

	case ret_ok:
		validate_type(ret_ok, byte_response, 0);
		break;

	case ret_null:
		validate_return("NULL", response, 0);
		break;

	case ret_nonnull:
		validate_return("NULL", response, 1);
		break;

	case ret_string:
	case ret_number:
		validate_return(command.returns[i].return_value,
				response, 0);
		break;

	case ret_ref:
		validate_reference(i, response);
		break;

	case ret_byte:
		validate_byte(&command.returns[i], byte_response, 0);
		break;

	default:
		err(1, "Malformed statement at line %zu of file %s",
		    line, cur_file);
		break;
	}
}

/*
 * Validate the return against the contents of a variable.
 */
static void
validate_reference(int i, void *data)
{
	char *response;
	returns_t *byte_response;
	var_t *varp;

	varp = &vars[command.returns[i].return_index];

	byte_response = data;
	if (command.returns[i].return_type != ret_byte)
		response = data;

	if (verbose) {
		fprintf(stderr,
		    "%s: return type of %s, value %s \n", __func__,
		    returns_enum_names[varp->type],
		    (const char *)varp->value);
	}

	switch (varp->type) {
	case ret_string:
	case ret_number:
		validate_return(varp->value, response, 0);
		break;

	case ret_byte:
		validate_byte(varp->value, byte_response, 0);
		break;

	default:
		err(1,
		    "Invalid return type for reference at line %zu of file %s",
		    line, cur_file);
		break;
	}
}

/*
 * Validate the return type against the expected type, throw an error
 * if they don't match.
 */
static void
validate_type(returns_enum_t expected, returns_t *value, int check)
{
	if (((check == 0) && (expected != value->return_type)) ||
	    ((check == 1) && (expected == value->return_type)))
		err(1, "Validate expected type %s %s %s line %zu of file %s",
		    returns_enum_names[expected],
		    (check == 0)? "matching" : "not matching",
		    returns_enum_names[value->return_type], line, cur_file);

	if (verbose) {
		fprintf(stderr, "Validate expected type %s %s %s line %zu"
		    " of file %s\n",
		    returns_enum_names[expected],
		    (check == 0)? "matching" : "not matching",
		    returns_enum_names[value->return_type], line, cur_file);
	}
}

/*
 * Validate the return value against the expected value, throw an error
 * if they don't match.
 */
static void
validate_return(const char *expected, const char *value, int check)
{
	if (((check == 0) && strcmp(expected, value) != 0) ||
	    ((check == 1) && strcmp(expected, value) == 0))
		errx(1, "Validate expected %s %s %s line %zu of file %s",
		    expected,
		    (check == 0)? "matching" : "not matching", value,
		    line, cur_file);
	if (verbose) {
		fprintf(stderr, "Validated expected value %s %s %s "
		    "at line %zu of file %s\n", expected,
		    (check == 0)? "matches" : "does not match",
		    value, line, cur_file);
	}
}

/*
 * Validate the return value against the expected value, throw an error
 * if they don't match expectations.
 */
static void
validate_byte(returns_t *expected, returns_t *value, int check)
{
	char *ch;
	size_t i;

	if (verbose) {
		ch = value->return_value;
		fprintf(stderr, "checking returned byte stream: ");
		for (i = 0; i < value->return_len; i++)
			fprintf(stderr, "%s0x%x", (i != 0)? ", " : "", ch[i]);
		fprintf(stderr, "\n");

		fprintf(stderr, "%s byte stream: ",
			(check == 0)? "matches" : "does not match");
		ch = (char *) expected->return_value;
		for (i = 0; i < expected->return_len; i++)
			fprintf(stderr, "%s0x%x", (i != 0)? ", " : "", ch[i]);
		fprintf(stderr, "\n");
	}

	/*
	 * No chance of a match if lengths differ...
	 */
	if ((check == 0) && (expected->return_len != value->return_len))
	    errx(1, "Byte validation failed, length mismatch, expected %zu,"
		"received %zu", expected->return_len, value->return_len);

	/*
	 * If check is 0 then we want to throw an error IFF the byte streams
	 * do not match, if check is 1 then throw an error if the byte
	 * streams match.
	 */
	if (((check == 0) && memcmp(expected->return_value, value->return_value,
				    value->return_len) != 0) ||
	    ((check == 1) && (expected->return_len == value->return_len) &&
	     memcmp(expected->return_value, value->return_value,
		    value->return_len) == 0))
		errx(1, "Validate expected %s byte stream at line %zu"
		    "of file %s",
		    (check == 0)? "matching" : "not matching", line, cur_file);
	if (verbose) {
		fprintf(stderr, "Validated expected %s byte stream "
		    "at line %zu of file %s\n",
		    (check == 0)? "matching" : "not matching",
		    line, cur_file);
	}
}

/*
 * Validate the variable at i against the expected value, throw an
 * error if they don't match, if check is non-zero then the match is
 * negated.
 */
static void
validate_variable(int ret, returns_enum_t type, const void *value, int i,
    int check)
{
	returns_t *retval;
	var_t *varptr;

	retval = &command.returns[ret];
	varptr = &vars[command.returns[ret].return_index];

	if (varptr->value == NULL)
		err(1, "Variable %s has no value assigned to it", varptr->name);


	if (varptr->type != type)
		err(1, "Variable %s is not the expected type", varptr->name);

	if (type != ret_byte) {
		if ((((check == 0) && strcmp(value, varptr->value) != 0))
		    || ((check == 1) && strcmp(value, varptr->value) == 0))
			err(1, "Variable %s contains %s instead of %s"
			    " value %s at line %zu of file %s",
			    varptr->name, (const char *)varptr->value,
			    (check == 0)? "expected" : "not matching",
			    (const char *)value,
			    line, cur_file);
		if (verbose) {
			fprintf(stderr, "Variable %s contains %s value "
			    "%s at line %zu of file %s\n",
			    varptr->name,
			    (check == 0)? "expected" : "not matching",
			    (const char *)varptr->value, line, cur_file);
		}
	} else {
		if ((check == 0) && (retval->return_len != varptr->len))
			err(1, "Byte validation failed, length mismatch");

		/*
		 * If check is 0 then we want to throw an error IFF
		 * the byte streams do not match, if check is 1 then
		 * throw an error if the byte streams match.
		 */
		if (((check == 0) && memcmp(retval->return_value, varptr->value,
					    varptr->len) != 0) ||
		    ((check == 1) && (retval->return_len == varptr->len) &&
		     memcmp(retval->return_value, varptr->value,
			    varptr->len) == 0))
			err(1, "Validate expected %s byte stream at line %zu"
			    " of file %s",
			    (check == 0)? "matching" : "not matching",
			    line, cur_file);
		if (verbose) {
			fprintf(stderr, "Validated expected %s byte stream "
			    "at line %zu of file %s\n",
			    (check == 0)? "matching" : "not matching",
			    line, cur_file);
		}
	}
}

/*
 * Write a string to the command pipe - we feed the number of bytes coming
 * down first to allow storage allocation and then follow up with the data.
 * If cmd is NULL then feed a -1 down the pipe to say the end of the args.
 */
static void
write_cmd_pipe(char *cmd)
{
	args_t arg;
	size_t len;

	if (cmd == NULL)
		len = 0;
	else
		len = strlen(cmd);

	arg.arg_type = arg_static;
	arg.arg_len = len;
	arg.arg_string = cmd;
	write_cmd_pipe_args(arg.arg_type, &arg);

}

static void
write_cmd_pipe_args(args_state_t type, void *data)
{
	var_t *var_data;
	args_t *arg_data;
	int len, send_type;
	void *cmd;

	arg_data = data;
	switch (type) {
	case arg_var:
		var_data = data;
		len = var_data->len;
		cmd = var_data->value;
		if (type == arg_byte)
			send_type = ret_byte;
		else
			send_type = ret_string;
		break;

	case arg_null:
		send_type = ret_null;
		len = 0;
		break;

	default:
		if ((arg_data->arg_len == 0) && (arg_data->arg_string == NULL))
			len = -1;
		else
			len = arg_data->arg_len;
		cmd = arg_data->arg_string;
		if (type == arg_byte)
			send_type = ret_byte;
		else
			send_type = ret_string;
	}

	if (verbose) {
		fprintf(stderr, "Writing type %s to command pipe\n",
		    returns_enum_names[send_type]);
	}

	if (write(cmdpipe[WRITE_PIPE], &send_type, sizeof(int)) < 0)
		err(1, "command pipe write for type failed");

	if (verbose) {
		fprintf(stderr, "Writing length %d to command pipe\n", len);
	}

	if (write(cmdpipe[WRITE_PIPE], &len, sizeof(int)) < 0)
		err(1, "command pipe write for length failed");

	if (len > 0) {
		if (verbose) {
			fprintf(stderr, "Writing data >%s< to command pipe\n",
			    (const char *)cmd);
		}
		if (write(cmdpipe[WRITE_PIPE], cmd, len) < 0)
			err(1, "command pipe write of data failed");
	}
}

/*
 * Read a response from the command pipe, first we will receive the
 * length of the response then the actual data.
 */
static void
read_cmd_pipe(returns_t *response)
{
	int len, type;
	struct pollfd rfd[2];
	char *str;

	/*
	 * Check if there is data to read - just in case slave has died, we
	 * don't want to block on the read and just hang.  We also check
	 * output from the slave because the slave may be blocked waiting
	 * for a flush on its stdout.
	 */
	rfd[0].fd = slvpipe[READ_PIPE];
	rfd[0].events = POLLIN;
	rfd[1].fd = master;
	rfd[1].events = POLLIN;

	do {
		if (poll(rfd, 2, 4000) == 0)
			errx(2, "%s, %zu: Command pipe read timeout",
			    cur_file, line);

		if ((rfd[1].revents & POLLIN) == POLLIN) {
			if (verbose) {
				fprintf(stderr,
				    "draining output from slave\n");
			}
			save_slave_output(false);
		}
	}
	while((rfd[1].revents & POLLIN) == POLLIN);

	if (read(slvpipe[READ_PIPE], &type, sizeof(int)) < 0)
		err(1, "command pipe read for type failed");
	response->return_type = type;

	if ((type != ret_ok) && (type != ret_err) && (type != ret_count)) {
		if (read(slvpipe[READ_PIPE], &len, sizeof(int)) < 0)
			err(1, "command pipe read for length failed");
		response->return_len = len;

		if (verbose) {
			fprintf(stderr,
			    "Reading %d bytes from command pipe\n", len);
		}

		if ((response->return_value = malloc(len + 1)) == NULL)
			err(1, "Failed to alloc memory for cmd pipe read");

		if (read(slvpipe[READ_PIPE], response->return_value, len) < 0)
			err(1, "command pipe read of data failed");

		if (response->return_type != ret_byte) {
			str = response->return_value;
			str[len] = '\0';

			if (verbose) {
				fprintf(stderr, "Read data >%s< from pipe\n",
				    (const char *)response->return_value);
			}
		}
	} else {
		response->return_value = NULL;
		if (type == ret_count) {
			if (read(slvpipe[READ_PIPE], &len, sizeof(int)) < 0)
				err(1, "command pipe read for number of "
				       "returns failed");
			response->return_len = len;
		}

		if (verbose) {
			fprintf(stderr, "Read type %s from pipe\n",
			    returns_enum_names[type]);
		}
	}
}

/*
 * Check for writes from the slave on the pty, save the output into a
 * buffer for later checking if discard is false.
 */
#define MAX_DRAIN 256

static void
save_slave_output(bool discard)
{
	char *new_data, drain[MAX_DRAIN];
	size_t to_allocate;
	ssize_t result;
	size_t i;

	result = 0;
	for (;;) {
		if (result == -1)
			err(2, "poll of slave pty failed");
		result = MAX_DRAIN;
		if ((result = read(master, drain, result)) < 0) {
			if (errno == EAGAIN)
				break;
			else
				err(2, "draining slave pty failed");
		}
		if (result == 0)
			abort();

		if (!discard) {
			if ((size_t)result >
			    (saved_output.allocated - saved_output.count)) {
				to_allocate = 1024 * ((result / 1024) + 1);

				if ((new_data = realloc(saved_output.data,
					saved_output.allocated + to_allocate))
				    == NULL)
					err(2, "Realloc of saved_output failed");
				saved_output.data = new_data;
				saved_output.allocated += to_allocate;
			}

			if (verbose) {
				fprintf(stderr, "count = %zu, "
				    "allocated = %zu\n", saved_output.count,
				    saved_output.allocated);
				for (i = 0; i < (size_t)result; i++) {
					fprintf(stderr, "Saving slave output "
					    "at %zu: 0x%x (%c)\n",
					    saved_output.count + i, drain[i],
					    (drain[i] >= ' ')? drain[i] : '-');
				}
			}

			memcpy(&saved_output.data[saved_output.count], drain,
			       result);
			saved_output.count += result;

			if (verbose) {
				fprintf(stderr, "count = %zu, "
				    "allocated = %zu\n", saved_output.count,
				    saved_output.allocated);
			}
		} else {
			if (verbose) {
				for (i = 0; i < (size_t)result; i++) {
					fprintf(stderr, "Discarding slave "
					    "output 0x%x (%c)\n",
					    drain[i],
					    (drain[i] >= ' ')? drain[i] : '-');
				}
			}
		}
	}
}

static void
yyerror(const char *msg)
{
	warnx("%s in line %zu of file %s", msg, line, cur_file);
}