-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpect.c
3270 lines (2812 loc) · 82.4 KB
/
expect.c
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
/* expect.c - expect commands
Written by: Don Libes, NIST, 2/6/90
Design and implementation of this program was paid for by U.S. tax
dollars. Therefore it is public domain. However, the author and NIST
would appreciate credit if this program or parts of it are used.
*/
#include <sys/types.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <ctype.h> /* for isspace */
#include <time.h> /* for time(3) */
#include "expect_cf.h"
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include "tclInt.h"
#include "string.h"
#include "exp_rename.h"
#include "exp_prog.h"
#include "exp_command.h"
#include "exp_log.h"
#include "exp_event.h"
#include "exp_tty_in.h"
#include "exp_tstamp.h" /* this should disappear when interact */
/* loses ref's to it */
#ifdef TCL_DEBUGGER
#include "tcldbg.h"
#endif
#include "retoglob.c" /* RE 2 GLOB translator C variant */
/* initial length of strings that we can guarantee patterns can match */
int exp_default_match_max = 2000;
#define INIT_EXPECT_TIMEOUT_LIT "10" /* seconds */
#define INIT_EXPECT_TIMEOUT 10 /* seconds */
int exp_default_parity = TRUE;
int exp_default_rm_nulls = TRUE;
int exp_default_close_on_eof = TRUE;
/* user variable names */
#define EXPECT_TIMEOUT "timeout"
#define EXPECT_OUT "expect_out"
extern int Exp_StringCaseMatch _ANSI_ARGS_((Tcl_UniChar *string, int strlen,
Tcl_UniChar *pattern,int plen,
int nocase,int *offset));
typedef struct ThreadSpecificData {
int timeout;
} ThreadSpecificData;
static Tcl_ThreadDataKey dataKey;
/*
* addr of these placeholders appear as clientData in ExpectCmd * when called
* as expect_user and expect_tty. It would be nicer * to invoked
* expDevttyGet() but C doesn't allow this in an array initialization, sigh.
*/
static ExpState StdinoutPlaceholder;
static ExpState DevttyPlaceholder;
/* 1 ecase struct is reserved for each case in the expect command. Note that
* eof/timeout don't use any of theirs, but the algorithm is simpler this way.
*/
struct ecase { /* case for expect command */
struct exp_i *i_list;
Tcl_Obj *pat; /* original pattern spec */
Tcl_Obj *body; /* ptr to body to be executed upon match */
Tcl_Obj *gate; /* For PAT_RE, a gate-keeper glob pattern
* which is quicker to match and reduces
* the number of calls into expensive RE
* matching. Optional.
*/
#define PAT_EOF 1
#define PAT_TIMEOUT 2
#define PAT_DEFAULT 3
#define PAT_FULLBUFFER 4
#define PAT_GLOB 5 /* glob-style pattern list */
#define PAT_RE 6 /* regular expression */
#define PAT_EXACT 7 /* exact string */
#define PAT_NULL 8 /* ASCII 0 */
#define PAT_TYPES 9 /* used to size array of pattern type descriptions */
int use; /* PAT_XXX */
int simple_start; /* offset (chars) from start of buffer denoting where a
* glob or exact match begins */
int transfer; /* if false, leave matched chars in input stream */
int indices; /* if true, write indices */
int iread; /* if true, reread indirects */
int timestamp; /* if true, write timestamps */
#define CASE_UNKNOWN 0
#define CASE_NORM 1
#define CASE_LOWER 2
int Case; /* convert case before doing match? */
};
/* descriptions of the pattern types, used for debugging */
char *pattern_style[PAT_TYPES];
struct exp_cases_descriptor {
int count;
struct ecase **cases;
};
/* This describes an Expect command */
static
struct exp_cmd_descriptor {
int cmdtype; /* bg, before, after */
int duration; /* permanent or temporary */
int timeout_specified_by_flag; /* if -timeout flag used */
int timeout; /* timeout period if flag used */
struct exp_cases_descriptor ecd;
struct exp_i *i_list;
} exp_cmds[4];
/* note that exp_cmds[FG] is just a fake, the real contents is stored in some
* dynamically-allocated variable. We use exp_cmds[FG] mostly as a well-known
* address and also as a convenience and so we allocate just a few of its
* fields that we need.
*/
static void
exp_cmd_init(
struct exp_cmd_descriptor *cmd,
int cmdtype,
int duration)
{
cmd->duration = duration;
cmd->cmdtype = cmdtype;
cmd->ecd.cases = 0;
cmd->ecd.count = 0;
cmd->i_list = 0;
}
static int i_read_errno;/* place to save errno, if i_read() == -1, so it
doesn't get overwritten before we get to read it */
#ifdef SIMPLE_EVENT
static int alarm_fired; /* if alarm occurs */
#endif
void exp_background_channelhandlers_run_all();
/* exp_indirect_updateX is called by Tcl when an indirect variable is set */
static char *exp_indirect_update1( /* 1-part Tcl variable names */
Tcl_Interp *interp,
struct exp_cmd_descriptor *ecmd,
struct exp_i *exp_i);
static char *exp_indirect_update2( /* 2-part Tcl variable names */
ClientData clientData,
Tcl_Interp *interp, /* Interpreter containing variable. */
char *name1, /* Name of variable. */
char *name2, /* Second part of variable name. */
int flags); /* Information about what happened. */
#ifdef SIMPLE_EVENT
/*ARGSUSED*/
static RETSIGTYPE
sigalarm_handler(int n) /* unused, for compatibility with STDC */
{
alarm_fired = TRUE;
}
#endif /*SIMPLE_EVENT*/
/* free up everything in ecase */
static void
free_ecase(
Tcl_Interp *interp,
struct ecase *ec,
int free_ilist) /* if we should free ilist */
{
if (ec->i_list->duration == EXP_PERMANENT) {
if (ec->pat) { Tcl_DecrRefCount(ec->pat); }
if (ec->gate) { Tcl_DecrRefCount(ec->gate); }
if (ec->body) { Tcl_DecrRefCount(ec->body); }
}
if (free_ilist) {
ec->i_list->ecount--;
if (ec->i_list->ecount == 0) {
exp_free_i(interp,ec->i_list,exp_indirect_update2);
}
}
ckfree((char *)ec); /* NEW */
}
/* free up any argv structures in the ecases */
static void
free_ecases(
Tcl_Interp *interp,
struct exp_cmd_descriptor *eg,
int free_ilist) /* if true, free ilists */
{
int i;
if (!eg->ecd.cases) return;
for (i=0;i<eg->ecd.count;i++) {
free_ecase(interp,eg->ecd.cases[i],free_ilist);
}
ckfree((char *)eg->ecd.cases);
eg->ecd.cases = 0;
eg->ecd.count = 0;
}
#if 0
/* no standard defn for this, and some systems don't even have it, so avoid */
/* the whole quagmire by calling it something else */
static char *exp_strdup(char *s)
{
char *news = ckalloc(strlen(s) + 1);
strcpy(news,s);
return(news);
}
#endif
/* return TRUE if string appears to be a set of arguments
The intent of this test is to support the ability of commands to have
all their args braced as one. This conflicts with the possibility of
actually intending to have a single argument.
The bad case is in expect which can have a single argument with embedded
\n's although it's rare. Examples that this code should handle:
\n FALSE (pattern)
\n\n FALSE
\n \n \n FALSE
foo FALSE
foo\n FALSE
\nfoo\n TRUE (set of args)
\nfoo\nbar TRUE
Current test is very cheap and almost always right :-)
*/
int
exp_one_arg_braced(Tcl_Obj *objPtr) /* INTL */
{
int seen_nl = FALSE;
char *p = Tcl_GetString(objPtr);
for (;*p;p++) {
if (*p == '\n') {
seen_nl = TRUE;
continue;
}
if (!isspace(*p)) { /* INTL: ISO space */
return(seen_nl);
}
}
return FALSE;
}
/* called to execute a command of only one argument - a hack to commands */
/* to be called with all args surrounded by an outer set of braces */
/* Returns a list object containing the new set of arguments */
/* Caller then has to either reinvoke itself, or better, simply replace
* its current argumnts */
/*ARGSUSED*/
Tcl_Obj*
exp_eval_with_one_arg(
ClientData clientData,
Tcl_Interp *interp,
Tcl_Obj *CONST objv[]) /* Argument objects. */
{
Tcl_Obj* res = Tcl_NewListObj (1,objv);
#define NUM_STATIC_OBJS 20
Tcl_Token *tokenPtr;
CONST char *p;
CONST char *next;
int rc;
int bytesLeft, numWords;
Tcl_Parse parse;
/*
* Prepend the command name and the -nobrace switch so we can
* reinvoke without recursing.
*/
Tcl_ListObjAppendElement (interp, res, Tcl_NewStringObj("-nobrace", -1));
p = Tcl_GetStringFromObj(objv[1], &bytesLeft);
/*
* Treat the pattern/action block like a series of Tcl commands.
* For each command, parse the command words, perform substititions
* on each word, and add the words to an array of values. We don't
* actually evaluate the individual commands, just the substitutions.
*/
do {
if (Tcl_ParseCommand(interp, p, bytesLeft, 0, &parse)
!= TCL_OK) {
rc = TCL_ERROR;
goto done;
}
numWords = parse.numWords;
if (numWords > 0) {
/*
* Generate an array of objects for the words of the command.
*/
/*
* For each word, perform substitutions then store the
* result in the objs array.
*/
for (tokenPtr = parse.tokenPtr; numWords > 0;
numWords--, tokenPtr += (tokenPtr->numComponents + 1)) {
/* FUTURE: Save token information, do substitution later */
Tcl_Obj* w = Tcl_EvalTokens(interp, tokenPtr+1,
tokenPtr->numComponents);
/* w has refCount 1 here, if not NULL */
if (w == NULL) {
Tcl_DecrRefCount (res);
res = NULL;
goto done;
}
Tcl_ListObjAppendElement (interp, res, w);
Tcl_DecrRefCount (w); /* Local reference goes away */
}
}
/*
* Advance to the next command in the script.
*/
next = parse.commandStart + parse.commandSize;
bytesLeft -= next - p;
p = next;
Tcl_FreeParse(&parse);
} while (bytesLeft > 0);
done:
return res;
}
static void
ecase_clear(struct ecase *ec)
{
ec->i_list = 0;
ec->pat = 0;
ec->body = 0;
ec->transfer = TRUE;
ec->simple_start = 0;
ec->indices = FALSE;
ec->iread = FALSE;
ec->timestamp = FALSE;
ec->Case = CASE_NORM;
ec->use = PAT_GLOB;
ec->gate = NULL;
}
static struct ecase *
ecase_new(void)
{
struct ecase *ec = (struct ecase *)ckalloc(sizeof(struct ecase));
ecase_clear(ec);
return ec;
}
/*
parse_expect_args parses the arguments to expect or its variants.
It normally returns TCL_OK, and returns TCL_ERROR for failure.
(It can't return i_list directly because there is no way to differentiate
between clearing, say, expect_before and signalling an error.)
eg (expect_global) is initialized to reflect the arguments parsed
eg->ecd.cases is an array of ecases
eg->ecd.count is the # of ecases
eg->i_list is a linked list of exp_i's which represent the -i info
Each exp_i is chained to the next so that they can be easily free'd if
necessary. Each exp_i has a reference count. If the -i is not used
(e.g., has no following patterns), the ref count will be 0.
Each ecase points to an exp_i. Several ecases may point to the same exp_i.
Variables named by indirect exp_i's are read for the direct values.
If called from a foreground expect and no patterns or -i are given, a
default exp_i is forced so that the command "expect" works right.
The exp_i chain can be broken by the caller if desired.
*/
static int
parse_expect_args(
Tcl_Interp *interp,
struct exp_cmd_descriptor *eg,
ExpState *default_esPtr, /* suggested ExpState if called as expect_user or _tty */
int objc,
Tcl_Obj *CONST objv[]) /* Argument objects. */
{
int i;
char *string;
struct ecase ec; /* temporary to collect args */
eg->timeout_specified_by_flag = FALSE;
ecase_clear(&ec);
/* Allocate an array to store the ecases. Force array even if 0 */
/* cases. This will often be too large (i.e., if there are flags) */
/* but won't affect anything. */
eg->ecd.cases = (struct ecase **)ckalloc(sizeof(struct ecase *) * (1+(objc/2)));
eg->ecd.count = 0;
for (i = 1;i<objc;i++) {
int index;
string = Tcl_GetString(objv[i]);
if (string[0] == '-') {
static char *flags[] = {
"-glob", "-regexp", "-exact", "-notransfer", "-nocase",
"-i", "-indices", "-iread", "-timestamp", "-timeout",
"-nobrace", "--", (char *)0
};
enum flags {
EXP_ARG_GLOB, EXP_ARG_REGEXP, EXP_ARG_EXACT,
EXP_ARG_NOTRANSFER, EXP_ARG_NOCASE, EXP_ARG_SPAWN_ID,
EXP_ARG_INDICES, EXP_ARG_IREAD, EXP_ARG_TIMESTAMP,
EXP_ARG_DASH_TIMEOUT, EXP_ARG_NOBRACE, EXP_ARG_DASH
};
/*
* Allow abbreviations of switches and report an error if we
* get an invalid switch.
*/
if (Tcl_GetIndexFromObj(interp, objv[i], flags, "flag", 0,
&index) != TCL_OK) {
return TCL_ERROR;
}
switch ((enum flags) index) {
case EXP_ARG_GLOB:
case EXP_ARG_DASH:
i++;
/* assignment here is not actually necessary */
/* since cases are initialized this way above */
/* ec.use = PAT_GLOB; */
if (i >= objc) {
Tcl_WrongNumArgs(interp, 1, objv,"-glob pattern");
return TCL_ERROR;
}
goto pattern;
case EXP_ARG_REGEXP:
i++;
if (i >= objc) {
Tcl_WrongNumArgs(interp, 1, objv,"-regexp regexp");
return TCL_ERROR;
}
ec.use = PAT_RE;
/*
* Try compiling the expression so we can report
* any errors now rather then when we first try to
* use it.
*/
if (!(Tcl_GetRegExpFromObj(interp, objv[i],
TCL_REG_ADVANCED))) {
goto error;
}
/* Derive a gate keeper glob pattern which reduces the amount
* of RE matching.
*/
{
Tcl_Obj* g;
Tcl_UniChar* str;
int strlen;
str = Tcl_GetUnicodeFromObj (objv[i], &strlen);
g = exp_retoglob (str, strlen);
if (g) {
ec.gate = g;
expDiagLog("Gate keeper glob pattern for '%s'",Tcl_GetString(objv[i]));
expDiagLog(" is '%s'. Activating booster.\n",Tcl_GetString(g));
} else {
/* Ignore errors, fall back to regular RE matching */
expDiagLog("Gate keeper glob pattern for '%s'",Tcl_GetString(objv[i]));
expDiagLog(" is '%s'. Not usable, disabling the",Tcl_GetString(Tcl_GetObjResult (interp)));
expDiagLog(" performance booster.\n");
}
}
goto pattern;
case EXP_ARG_EXACT:
i++;
if (i >= objc) {
Tcl_WrongNumArgs(interp, 1, objv, "-exact string");
return TCL_ERROR;
}
ec.use = PAT_EXACT;
goto pattern;
case EXP_ARG_NOTRANSFER:
ec.transfer = 0;
break;
case EXP_ARG_NOCASE:
ec.Case = CASE_LOWER;
break;
case EXP_ARG_SPAWN_ID:
i++;
if (i>=objc) {
Tcl_WrongNumArgs(interp, 1, objv, "-i spawn_id");
goto error;
}
ec.i_list = exp_new_i_complex(interp,
Tcl_GetString(objv[i]),
eg->duration, exp_indirect_update2);
if (!ec.i_list) goto error;
ec.i_list->cmdtype = eg->cmdtype;
/* link new i_list to head of list */
ec.i_list->next = eg->i_list;
eg->i_list = ec.i_list;
break;
case EXP_ARG_INDICES:
ec.indices = TRUE;
break;
case EXP_ARG_IREAD:
ec.iread = TRUE;
break;
case EXP_ARG_TIMESTAMP:
ec.timestamp = TRUE;
break;
case EXP_ARG_DASH_TIMEOUT:
i++;
if (i>=objc) {
Tcl_WrongNumArgs(interp, 1, objv, "-timeout seconds");
goto error;
}
if (Tcl_GetIntFromObj(interp, objv[i],
&eg->timeout) != TCL_OK) {
goto error;
}
eg->timeout_specified_by_flag = TRUE;
break;
case EXP_ARG_NOBRACE:
/* nobrace does nothing but take up space */
/* on the command line which prevents */
/* us from re-expanding any command lines */
/* of one argument that looks like it should */
/* be expanded to multiple arguments. */
break;
}
/*
* Keep processing arguments, we aren't ready for the
* pattern yet.
*/
continue;
} else {
/*
* We have a pattern or keyword.
*/
static char *keywords[] = {
"timeout", "eof", "full_buffer", "default", "null",
(char *)NULL
};
enum keywords {
EXP_ARG_TIMEOUT, EXP_ARG_EOF, EXP_ARG_FULL_BUFFER,
EXP_ARG_DEFAULT, EXP_ARG_NULL
};
/*
* Match keywords exactly, otherwise they are patterns.
*/
if (Tcl_GetIndexFromObj(interp, objv[i], keywords, "keyword",
1 /* exact */, &index) != TCL_OK) {
Tcl_ResetResult(interp);
goto pattern;
}
switch ((enum keywords) index) {
case EXP_ARG_TIMEOUT:
ec.use = PAT_TIMEOUT;
break;
case EXP_ARG_EOF:
ec.use = PAT_EOF;
break;
case EXP_ARG_FULL_BUFFER:
ec.use = PAT_FULLBUFFER;
break;
case EXP_ARG_DEFAULT:
ec.use = PAT_DEFAULT;
break;
case EXP_ARG_NULL:
ec.use = PAT_NULL;
break;
}
pattern:
/* if no -i, use previous one */
if (!ec.i_list) {
/* if no -i flag has occurred yet, use default */
if (!eg->i_list) {
if (default_esPtr != EXP_SPAWN_ID_BAD) {
eg->i_list = exp_new_i_simple(default_esPtr,eg->duration);
} else {
default_esPtr = expStateCurrent(interp,0,0,1);
if (!default_esPtr) goto error;
eg->i_list = exp_new_i_simple(default_esPtr,eg->duration);
}
}
ec.i_list = eg->i_list;
}
ec.i_list->ecount++;
/* save original pattern spec */
/* keywords such as "-timeout" are saved as patterns here */
/* useful for debugging but not otherwise used */
ec.pat = objv[i];
if (eg->duration == EXP_PERMANENT) {
Tcl_IncrRefCount(ec.pat);
if (ec.gate) {
Tcl_IncrRefCount(ec.gate);
}
}
i++;
if (i < objc) {
ec.body = objv[i];
if (eg->duration == EXP_PERMANENT) Tcl_IncrRefCount(ec.body);
} else {
ec.body = NULL;
}
*(eg->ecd.cases[eg->ecd.count] = ecase_new()) = ec;
/* clear out for next set */
ecase_clear(&ec);
eg->ecd.count++;
}
}
/* if no patterns at all have appeared force the current */
/* spawn id to be added to list anyway */
if (eg->i_list == 0) {
if (default_esPtr != EXP_SPAWN_ID_BAD) {
eg->i_list = exp_new_i_simple(default_esPtr,eg->duration);
} else {
default_esPtr = expStateCurrent(interp,0,0,1);
if (!default_esPtr) goto error;
eg->i_list = exp_new_i_simple(default_esPtr,eg->duration);
}
}
return(TCL_OK);
error:
/* very hard to free case_master_list here if it hasn't already */
/* been attached to a case, ugh */
/* note that i_list must be avail to free ecases! */
free_ecases(interp,eg,0);
if (eg->i_list)
exp_free_i(interp,eg->i_list,exp_indirect_update2);
return(TCL_ERROR);
}
#define EXP_IS_DEFAULT(x) ((x) == EXP_TIMEOUT || (x) == EXP_EOF)
static char yes[] = "yes\r\n";
static char no[] = "no\r\n";
/* this describes status of a successful match */
struct eval_out {
struct ecase *e; /* ecase that matched */
ExpState *esPtr; /* ExpState that matched */
Tcl_UniChar* matchbuf; /* Buffer that matched, */
int matchlen; /* and #chars that matched, or
* #chars in buffer at EOF */
/* This points into the esPtr->input.buffer ! */
};
/*
*----------------------------------------------------------------------
*
* string_case_first --
*
* Find the first instance of a pattern in a string.
*
* Results:
* Returns the pointer to the first instance of the pattern
* in the given string, or NULL if no match was found.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
Tcl_UniChar *
string_case_first( /* INTL */
register Tcl_UniChar *string, /* String (unicode). */
int length, /* length of above string */
register char *pattern) /* Pattern, which may contain
* special characters (utf8). */
{
Tcl_UniChar *s;
char *p;
int offset;
register int consumed = 0;
Tcl_UniChar ch1, ch2;
Tcl_UniChar *bufend = string + length;
while ((*string != 0) && (string < bufend)) {
s = string;
p = pattern;
while ((*s) && (s < bufend)) {
ch1 = *s++;
consumed++;
offset = TclUtfToUniChar(p, &ch2);
if (Tcl_UniCharToLower(ch1) != Tcl_UniCharToLower(ch2)) {
break;
}
p += offset;
}
if (*p == '\0') {
return string;
}
string++;
consumed++;
}
return NULL;
}
Tcl_UniChar *
string_first( /* INTL */
register Tcl_UniChar *string, /* String (unicode). */
int length, /* length of above string */
register char *pattern) /* Pattern, which may contain
* special characters (utf8). */
{
Tcl_UniChar *s;
char *p;
int offset;
register int consumed = 0;
Tcl_UniChar ch1, ch2;
Tcl_UniChar *bufend = string + length;
while ((*string != 0) && (string < bufend)) {
s = string;
p = pattern;
while ((*s) && (s < bufend)) {
ch1 = *s++;
consumed++;
offset = TclUtfToUniChar(p, &ch2);
if (ch1 != ch2) {
break;
}
p += offset;
}
if (*p == '\0') {
return string;
}
string++;
consumed++;
}
return NULL;
}
Tcl_UniChar *
string_first_char( /* INTL */
register Tcl_UniChar *string, /* String. */
register Tcl_UniChar pattern)
{
/* unicode based Tcl_UtfFindFirst */
Tcl_UniChar find;
while (1) {
find = *string;
if (find == pattern) {
return string;
}
if (*string == '\0') {
return NULL;
}
string ++;
}
return NULL;
}
/* like eval_cases, but handles only a single cases that needs a real */
/* string match */
/* returns EXP_X where X is MATCH, NOMATCH, FULLBUFFER, TCLERRROR */
static int
eval_case_string(
Tcl_Interp *interp,
struct ecase *e,
ExpState *esPtr,
struct eval_out *o, /* 'output' - i.e., final case of interest */
/* next two args are for debugging, when they change, reprint buffer */
ExpState **last_esPtr,
int *last_case,
char *suffix)
{
Tcl_RegExp re;
Tcl_RegExpInfo info;
Tcl_Obj* buf;
Tcl_UniChar *str;
int numchars, flags, dummy, globmatch;
int result;
str = esPtr->input.buffer;
numchars = esPtr->input.use;
/* if ExpState or case changed, redisplay debug-buffer */
if ((esPtr != *last_esPtr) || e->Case != *last_case) {
expDiagLog("\r\nexpect%s: does \"",suffix);
expDiagLogU(expPrintifyUni(str,numchars));
expDiagLog("\" (spawn_id %s) match %s ",esPtr->name,pattern_style[e->use]);
*last_esPtr = esPtr;
*last_case = e->Case;
}
if (e->use == PAT_RE) {
expDiagLog("\"");
expDiagLogU(expPrintify(Tcl_GetString(e->pat)));
expDiagLog("\"? ");
if (e->gate) {
int plen;
Tcl_UniChar* pat = Tcl_GetUnicodeFromObj(e->gate,&plen);
expDiagLog("Gate \"");
expDiagLogU(expPrintify(Tcl_GetString(e->gate)));
expDiagLog("\"? gate=");
globmatch = Exp_StringCaseMatch(str, numchars, pat, plen,
(e->Case == CASE_NORM) ? 0 : 1,
&dummy);
} else {
expDiagLog("(No Gate, RE only) gate=");
/* No gate => RE matching always */
globmatch = 1;
}
if (globmatch < 0) {
expDiagLogU(no);
/* i.e. no match */
} else {
expDiagLog("yes re=");
if (e->Case == CASE_NORM) {
flags = TCL_REG_ADVANCED;
} else {
flags = TCL_REG_ADVANCED | TCL_REG_NOCASE;
}
re = Tcl_GetRegExpFromObj(interp, e->pat, flags);
/* ZZZ: Future optimization: Avoid copying */
buf = Tcl_NewUnicodeObj (str, numchars);
Tcl_IncrRefCount (buf);
result = Tcl_RegExpExecObj(interp, re, buf, 0 /* offset */,
-1 /* nmatches */, 0 /* eflags */);
Tcl_DecrRefCount (buf);
if (result > 0) {
o->e = e;
/*
* Retrieve the byte offset of the end of the
* matched string.
*/
Tcl_RegExpGetInfo(re, &info);
o->matchlen = info.matches[0].end;
o->matchbuf = str;
o->esPtr = esPtr;
expDiagLogU(yes);
return(EXP_MATCH);
} else if (result == 0) {
expDiagLogU(no);
} else { /* result < 0 */
return(EXP_TCLERROR);
}
}
} else if (e->use == PAT_GLOB) {
int match; /* # of chars that matched */
expDiagLog("\"");
expDiagLogU(expPrintify(Tcl_GetString(e->pat)));
expDiagLog("\"? ");
if (str) {
int plen;
Tcl_UniChar* pat = Tcl_GetUnicodeFromObj(e->pat,&plen);
match = Exp_StringCaseMatch(str,numchars, pat, plen,
(e->Case == CASE_NORM) ? 0 : 1,
&e->simple_start);
if (match != -1) {
o->e = e;
o->matchlen = match;
o->matchbuf = str;
o->esPtr = esPtr;
expDiagLogU(yes);
return(EXP_MATCH);
}
}
expDiagLogU(no);
} else if (e->use == PAT_EXACT) {
int patLength;
char *pat = Tcl_GetStringFromObj(e->pat, &patLength);
Tcl_UniChar *p;
if (e->Case == CASE_NORM) {
p = string_first(str, numchars, pat); /* NEW function in this file, see above */
} else {
p = string_case_first(str, numchars, pat);
}
expDiagLog("\"");
expDiagLogU(expPrintify(Tcl_GetString(e->pat)));
expDiagLog("\"? ");
if (p) {
/* Bug 3095935. Go from #bytes to #chars */
patLength = Tcl_NumUtfChars (pat, patLength);
e->simple_start = p - str;
o->e = e;
o->matchlen = patLength;
o->matchbuf = str;
o->esPtr = esPtr;
expDiagLogU(yes);
return(EXP_MATCH);
} else expDiagLogU(no);
} else if (e->use == PAT_NULL) {
CONST Tcl_UniChar *p;
expDiagLogU("null? ");
p = string_first_char (str, 0); /* NEW function in this file, see above */
if (p) {
o->e = e;
o->matchlen = p-str; /* #chars */
o->matchbuf = str;
o->esPtr = esPtr;
expDiagLogU(yes);
return EXP_MATCH;
}
expDiagLogU(no);
} else if (e->use == PAT_FULLBUFFER) {
expDiagLogU(Tcl_GetString(e->pat));
expDiagLogU("? ");
/* this must be the same test as in expIRead */
/* We drop one third when are at least 2/3 full */
/* condition is (size >= max*2/3) <=> (size*3 >= max*2) */
if (((expSizeGet(esPtr)*3) >= (esPtr->input.max*2)) && (numchars > 0)) {
o->e = e;
o->matchlen = numchars/3;
o->matchbuf = str;
o->esPtr = esPtr;
expDiagLogU(yes);
return(EXP_FULLBUFFER);
} else {
expDiagLogU(no);
}
}
return(EXP_NOMATCH);
}
/* sets o.e if successfully finds a matching pattern, eof, timeout or deflt */
/* returns original status arg or EXP_TCLERROR */
static int
eval_cases(
Tcl_Interp *interp,
struct exp_cmd_descriptor *eg,
ExpState *esPtr,