Skip to content
Tcl Source Code Changes To Channel System, Driver Perspective
Login

Changes To Channel System, Driver Perspective

Changes to "Channel System, Driver Perspective" between 2015-08-11 21:44:08 and 2015-08-11 21:55:08

︙
16
17
18
19
20
21
22
23

24
25
26
27
28
29
30
16
17
18
19
20
21
22

23
24
25
26
27
28
29
30







-
+







**Abstract**

!!!!!!
''This document describes the I/O system used in the Tcl core as it is seen from a driver implementing a channel type.''
!!!!!!

**Table of Contents**
===
```
   1.     '''Introduction''' . . . . . . . . . . . . . . . . . . . . . . .   2
   2.     '''Main facilities in the core'''  . . . . . . . . . . . . . . .   3
   3.     '''Writing a channel driver''' . . . . . . . . . . . . . . . . .   5
   3.1    '''InstanceData''' . . . . . . . . . . . . . . . . . . . . . . .   5
   3.2    '''Creation of channels''' . . . . . . . . . . . . . . . . . . .   6
   3.2.1  '''Creation of a base channel''' . . . . . . . . . . . . . . . .   6
   3.2.2  '''Creation of a transformation''' . . . . . . . . . . . . . . .   7
︙
42
43
44
45
46
47
48
49

50
51
52
53
54
55
56
42
43
44
45
46
47
48

49
50
51
52
53
54
55
56







-
+







   3.5.9  '''WatchProc'''  . . . . . . . . . . . . . . . . . . . . . . . .  20
   3.5.10 '''HandlerProc'''  . . . . . . . . . . . . . . . . . . . . . . .  24
   3.5.11 '''FlushProc'''  . . . . . . . . . . . . . . . . . . . . . . . .  25
          '''References''' . . . . . . . . . . . . . . . . . . . . . . . .  26
          '''Author's Address''' . . . . . . . . . . . . . . . . . . . . .  29
   A.     '''Glossary''' . . . . . . . . . . . . . . . . . . . . . . . . .  30
   B.     '''Acknowledgements''' . . . . . . . . . . . . . . . . . . . . .  31
===
```

**1. Introduction**

The main concept of the I/O system used by the Tcl core is the abstract notion
of channels unifying different paths for communication and the accompanying
split of this subsystem into two layers, one generic in nature, the other
handling the specialities of the various communication channels.
︙
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
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







-
+
















-
+







After the creation of the channel it might be necessary to configure to
configure it. For example it might be non-blocking by default.  Note that the
backlink to the channel has to be initialized with the result of the call to
Tcl_CreateChannel[http://www.tcl.tk/man/tcl8.4/TclLib/CrtChannel.htm].

Creation procedure skeleton for a base channel

===
```
int XX_CreateChannel(interp, objc, objv, cd) {
        ''process arguments'' /* objc, objv */

        name = ''generate_name_for_new_channel()'';

        clientData  = Tcl_Alloc(...);

        ''initialize clientData''... /* name, state, config ... */

        clientData->channel = Tcl_CreateChannel(interp, &chan_type, clientData);

        ''configure the channel according to arguments, if necessary''

        Tcl_SetResult(interp, name);
        return TCL_OK;
}
===
```

The ''chan_type'' in the code above is the structure containing the
references to the driver procedures for the base channel.

****3.2.2 Creation of a transformation****

In contrast to base channel types the creation procedure must not use
︙
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
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







-
+












-
+








The backlink to the channel of the transformation has to be initialized with
the result of the call to
Tcl_StackChannel[http://www.tcl.tk/man/tcl8.4/TclLib/ChnlStack.htm].

Creation procedure skeleton for a transformation

===
```
int XX_CreateTransformation(interp, objc, objv, cd) {
        old_channel = find(handle(objv[[1]));

        clientData = Tcl_Alloc (...);

        ''initialize clientData...''

        clientData->channel = Tcl_StackChannel(interp, &trans_type, clientData, old_channel);

        Tcl_SetResult(interp, old_channel->name);
        return TCL_OK;
}
===
```

The ''trans_type'' in the code above is the structure containing the
references to the driver procedures for the transformation.

***3.3 Destruction of channels***

Destruction of channels is done with either
︙
316
317
318
319
320
321
322
323

324
325
326
327
328
329
330
316
317
318
319
320
321
322

323
324
325
326
327
328
329
330







-
+







question as the older structures simply don't have them, i.e. we would get
random information and most likely crash later oon.

The structure for a channel type looks like this:

'''Tcl_ChannelType definition'''

======
```
   typedef struct Tcl_ChannelType {
       char *typeName;                  /* The name of the channel type in Tcl
                                         * commands. This storage is owned by
                                         * the channel type. */
       Tcl_ChannelTypeVersion version;  /* Version of the channel type. */
       Tcl_DriverCloseProc *closeProc;  /* Procedure to call to close the
                                         * channel, or TCL_CLOSE2PROC if the
︙
357
358
359
360
361
362
363
364

365
366
367
368
369
370
371
357
358
359
360
361
362
363

364
365
366
367
368
369
370
371







-
+







        */
       Tcl_DriverFlushProc *flushProc;  /* Procedure to call to flush a
                                         * channel. May be NULL. */
       Tcl_DriverHandlerProc *handlerProc;      /* Procedure to call to handle a
                                         * channel event.  This will be passed
                                         * up the stacked channel chain. */
   } Tcl_ChannelType;
======
```

For this discussion are only the four fields 'version', 'blockModeProc',
'flushProc' and 'handlerProc' of relevance.

All possible values are acceptable for 'version', but 'TCL_CHANNEL_VERSION_1'
and 'TCL_CHANNEL_VERSION_2' are special as they explictly spell out the
version of the driver. Any other value will cause the system to assume that
︙
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
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







-
+
















-
+







They have the additional option to delegate the call to the channel
downstream. I personally recommend to delegate the call.  Because of this I
also recommend to implement this function even if the transformation has no
options by itself.

'''SetOptionProc skeleton for a transformation'''

===
```
static int SetOptionProc(clientData, interp, optionName, value) {
        ''... handle your own options''

        /* delegate unknown options downstream */

        Tcl_Channel parent = Tcl_GetStackedChannel(clientData->channel);

        Tcl_DriverSetOptionProc *setOptionProc =
                Tcl_ChannelSetOptionProc(Tcl_GetChannelType(parent));

        if (setOptionProc == NULL) {
                return TCL_ERROR;
        }
        return setOptionProc(Tcl_GetChannelInstanceData(parent),
                interp, optionName, value);
}
===
```

****3.5.3 GetOptionProc****

This procedure is called by the generic I/O layer whenever
Tcl_GetChannelOption[http://www.tcl.tk/man/tcl8.4/TclLib/OpenFileChnl.htm#M20]
is used (f.e. by 'fconfigure') to query the value of a non-standard (or all)
option(s).
︙
505
506
507
508
509
510
511
512

513
514
515
516
517
518
519
505
506
507
508
509
510
511

512
513
514
515
516
517
518
519







-
+







delegation will generate a mighty long result.  Pruning the unnecessary
options values from the result of the underlying channel (-encoding,
-buffering, -translation) is possible, but tedious (We are working with
DStrings, not Tcl_Obj'ects, and especially no ListObj'ects).

'''GetOptionProc skeleton for a transformation'''

===
```
static int GetOptionProc(clientData, interp, optionName, dsPtr) {
        if (query for all options) {
                ''... add our own options to the result''

                ''/* add the options of the channel downstream''
                '' * to the result''
                '' */''
︙
541
542
543
544
545
546
547
548

549
550
551
552
553
554
555
541
542
543
544
545
546
547

548
549
550
551
552
553
554
555







-
+







                if (getOptionProc == NULL) {
                        return TCL_ERROR;
                }
                return getOptionProc(Tcl_GetChannelInstanceData(parent),
                        interp, optionName, dsPtr);
        }
}
===
```

P.S. Given the similarities in the way the delegation is handled by the two
branches of the if statement above it makes sense to factor this code into a
separate procedure.

****3.5.4 SeekProc****

︙
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
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







-
+









-
+



-
+












-
+







don't implement it, the other types either forward the call to the OS or
simply manipulate their internal state. See
memchan[http://www.purl.org/NET/akupries/soft/memchan/] for an example of the
latter.

'''SeekProc skeleton for OS associated channels'''

===
```
static int SeekProc(clientdata, offset, mode, errorCodePtr) {
        ''... flush possibly waiting output''
        ''... discard possibly waiting input''

        ''... compute some value from offset, mode and current location, then forward this to the OS.''

        *errorCodePtr = (result == -1) ? Tcl_GetErrno () : 0;
        return result;
}
===
```

'''SeekProc skeleton for non-OS channels'''

===
```
static int SeekProc(clientdata, offset, mode, errorCodePtr) {
        ''... compute the new location X from offset, mode and current location''

        if (''X out of bounds'') {
                *errorCodePtr = EINVALID;
                return -1;
        }

        clientdata->state = ''X'';
        *errorCodePtr = 0;
        return ''X'';
}
===
```

For transformations seeking is a hard problem. Should they seek using their
own notion of access point? Or should they use the notion of the underlying
channel and then try to adapt their own state for fine-positioning? Should
they allow seeking at all?

Depending on the transformation both the first two can be impossible. Nice
︙
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
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







-
+



















-
+







all read/write calls and maintaining an exact image of the information
read/written so far, but this is, ah, memory-extensive, to understate this a
little. Also note that the notion of channels with non-reversible state is
equivalent to the notion of forward seekable channels.

'''SeekProc skeleton with 1:1 pass'''

===
```
static int SeekProc(clientdata, offset, mode, errorCodePtr) {
        ''... flush waiting output''
        ''... flush waiting input, if possible (f.e. into a configured variable!)''

        /* Chain the call */

        Tcl_Channel parent = Tcl_GetStackedChannel(clientData->channel);

        Tcl_ChannelType *parentType = Tcl_GetChannelType(parent);
        Tcl_DriverSeekProc *parentSeekProc = Tcl_ChannelSeekProc(parentType);
        int errorCode;

        if (parentSeekProc == NULL) {
                return -1;
        }

        return parentSeekProc(Tcl_GetChannelInstanceData(parent),
                offset, mode, &errorCode);
}
===
```

As a last note, Trf[http://www.purl.org/NET/akupries/soft/trf/] implements a
much more complex seeking model for transformations, but describing it is
beyond the scope of this document. Go to its documentation instead.

****3.5.5 BlockModeProc****

︙
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
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







-
+







-
+

















-
+













-
+







A transformation channel however just has to remember this information in its
instance data so that InputProc (Section 3.5.7) is able to deal correctly with
empty reads on the downstream channel. The generic layer takes care of
notifying all channels in a stack so that all have the same information.

'''BlockModeProc skeleton'''

===
```
static int BlockModeProc(clientdata, mode) {
        if (mode == TCL_MODE_NONBLOCKING) {
                clientdata->flags |= ASYNC;
        } else {
                clientdata->flags &= ~ASYNC;
        }
}
===
```

****3.5.6 CloseProc****

This procedure is called by generic the I/O layer to tell a channel that it is
about to be destroyed. See Section 3.3 for the procedures which can invoke it.

It is the responsibility of the procedure to clean up any data structures held
by the channel. Another task is the removal of all event related things, like
ChannelHandlers and Timers, although this could be billeted under 'clean up of
any data structures held by the channel' too.

Transformations have the additional responsibility to complete the conversion
of all incomplete information sitting in its internal write buffers and to
write the result into the downstream channel to ensure a clean closure.

'''CloseProc skeleton'''

===
```
int CloseProc(clientdata, interp) {
        ''... delete timer, if any. See 'WatchProc' too.''

        '''|'''...      do last minute conversions on r/w buffers and try to
        '''|''' flush their results to the underlying channel.
        '''|''' See below
        '''|'''
        '''|''' parent = Tcl_GetStackedChannel (clientdata->channel);
        '''|''' Tcl_WriteRaw (parent, buffer, bufsize);

        ''... free data structures on the heap.''
        return TCL_OK
}
===
```

The part marked with '''|''' is specific to transformations and not required
for a base channel.

****3.5.7 InputProc****

This procedure is called by the generic I/O layer whenever some input is
︙
878
879
880
881
882
883
884
885

886
887
888
889
890
891
892
878
879
880
881
882
883
884

885
886
887
888
889
890
891
892







-
+







Two things have to be done.

   1. Propagation of the mask information to the channel downstream. All transformations have to cooperate in this or else the base channel at the bottom won't register with the notifier for events. The contrasting example to this is Section 3.5.5 where the generic layer automatically notifies all channels in the tsack itself. Here we decided against such an automatism because the way it is now allows the various transformations to modify the mask before passing it down, i.e. to add the events they are interested in beyond the interest of the script level without any changes to the structure of Tcl_ChannelType[http://www.tcl.tk/man/tcl8.4/TclLib/CrtChannel.htm#M6] or the sematics of this vector. This would have been the case if we had changed this to an automatic chaining in the generic part of the I/O system.
   1. Setting up and destroying the timer used to flush out the internal read buffers. This needs a bit more explanation, which will be given after the skeleton code for a WatchProc.

'''WatchProc skeleton'''

===
```
static void WatchProc(clientdata, mask) {
        ''/* Pass the mask to the channel downstream, possibly''
        '' * modified. Remember the mask internally.''
        '' */''

        Tcl_Channel parent = Tcl_GetStackedChannel(clientdata->channel);
        Tcl_DriverWatchProc *watchProc = Tcl_ChannelWatchProc(Tcl_GetChannelType(parent));
︙
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
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







-
+









-
+




-
+







                '' * actually have data waiting, so generate a''
                '' * timer to flush that if it does not exist.''
                '' */''

                ''... create the timer.''
        }
}
===
```

The handler procedure for the timer handled above looks like below.  It
basically proclaims that the transformation channel is readable.  There is no
need to recreate the timer here, because the generic layer will call Section
3.5.9 after it has handled the event and that vector will then do the right
thing (see above).

'''Timer handler skeleton'''

===
```
static void ChannelHandlerTimer(clientData) {
        clientdata->timer = NULL;
        Tcl_NotifyChannel(clientdata->channel, TCL_READABLE);
}
===
```

Now the promised explanation about the necessity of the timer.

Consider this scenario:

   1. A transformation is stacked upon a socket and its internal read buffer is empty. The transformation does not merge lines.
   1. A [fileevent] script is set up and waiting for calls.
︙
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
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







-
+

















-
+







the channel (or script) above being aware of them and the associated
processing. The TLS transformation[http://www.sensus.org/tcl/] for example
uses this facility to handle the whole negotiation phase. Only after the
encryption is setup events are passed unchanged to the higher layers.

'''HandleProc skeleton'''

===
```
static int HandleProc(clientdata, mask) {
        ''/*''
        '' * An event occured in the underlying channel.  This''
        '' * transformation doesn't process such events thus''
        '' * returns the incoming mask unchanged.''
        '' *''
        '' * We do delete an existing timer. It was not fired,''
        '' * yet we are here, so the channel below generated''
        '' * such an event and we don't have to. The renewal of''
        '' * the interest after the execution of channel''
        '' * handlers will eventually cause us to recreate the''
        '' * timer''
        '' */''

        ''... kill timer''
        return interestMask;
}
===
```

****3.5.11 FlushProc****

This vector is currently not used by the generic layer of the I/O system. In
the future it might be used to separate the actions of flushing and writing
data.

︙