summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--generic/tclIO.c729
-rw-r--r--generic/tclIORChan.c57
-rw-r--r--generic/tclIOUtil.c51
-rw-r--r--generic/tclTimer.c12
-rw-r--r--unix/tclUnixSock.c48
-rw-r--r--win/tclWinSock.c150
6 files changed, 572 insertions, 475 deletions
diff --git a/generic/tclIO.c b/generic/tclIO.c
index a509ebf..32fbd59 100644
--- a/generic/tclIO.c
+++ b/generic/tclIO.c
@@ -321,7 +321,7 @@ static int WillRead(Channel *chanPtr);
typedef struct ResolvedChanName {
ChannelState *statePtr; /* The saved lookup result */
Tcl_Interp *interp; /* The interp in which the lookup was done. */
- size_t epoch; /* The epoch of the channel when the lookup
+ size_t epoch; /* The epoch of the channel when the lookup
* was done. Use to verify validity. */
size_t refCount; /* Share this struct among many Tcl_Obj. */
} ResolvedChanName;
@@ -381,20 +381,20 @@ ChanCloseHalf(
*
* ChanRead --
*
- * Read up to dstSize bytes using the inputProc of chanPtr, store
- * them at dst, and return the number of bytes stored.
+ * Read up to dstSize bytes using the inputProc of chanPtr, store them at
+ * dst, and return the number of bytes stored.
*
* Results:
* The return value of the driver inputProc,
* - number of bytes stored at dst, ot
- * - -1 on error, with a Posix error code available to the
- * caller by calling Tcl_GetErrno().
+ * - -1 on error, with a Posix error code available to the caller by
+ * calling Tcl_GetErrno().
*
* Side effects:
- * The CHANNEL_BLOCKED and CHANNEL_EOF flags of the channel state are
- * set as appropriate.
- * On EOF, the inputEncodingFlags are set to perform ending operations
- * on decoding.
+ * The CHANNEL_BLOCKED and CHANNEL_EOF flags of the channel state are set
+ * as appropriate. On EOF, the inputEncodingFlags are set to perform
+ * ending operations on decoding.
+ *
* TODO - Is this really the right place for that?
*
*---------------------------------------------------------------------------
@@ -408,15 +408,17 @@ ChanRead(
int bytesRead, result;
/*
- * If the caller asked for zero bytes, we'd force the inputProc
- * to return zero bytes, and then misinterpret that as EOF.
+ * If the caller asked for zero bytes, we'd force the inputProc to return
+ * zero bytes, and then misinterpret that as EOF.
*/
+
assert(dstSize > 0);
/*
* Each read op must set the blocked and eof states anew, not let
* the effect of prior reads leak through.
*/
+
if (GotFlag(chanPtr->state, CHANNEL_EOF)) {
chanPtr->state->inputEncodingFlags |= TCL_ENCODING_START;
}
@@ -429,7 +431,10 @@ ChanRead(
bytesRead = chanPtr->typePtr->inputProc(chanPtr->instanceData,
dst, dstSize, &result);
- /* Stop any flag leakage through stacked channel levels */
+ /*
+ * Stop any flag leakage through stacked channel levels.
+ */
+
if (GotFlag(chanPtr->state, CHANNEL_EOF)) {
chanPtr->state->inputEncodingFlags |= TCL_ENCODING_START;
}
@@ -437,10 +442,10 @@ ChanRead(
chanPtr->state->inputEncodingFlags &= ~TCL_ENCODING_END;
if (bytesRead > 0) {
/*
- * If we get a short read, signal up that we may be BLOCKED.
- * We should avoid calling the driver because on some
- * platforms we will block in the low level reading code even
- * though the channel is set into nonblocking mode.
+ * If we get a short read, signal up that we may be BLOCKED. We should
+ * avoid calling the driver because on some platforms we will block in
+ * the low level reading code even though the channel is set into
+ * nonblocking mode.
*/
if (bytesRead < dstSize) {
@@ -574,7 +579,10 @@ TclFinalizeIOSubsystem(void)
int active = 1; /* Flag == 1 while there's still work to do */
int doflushnb;
- /* Fetch the pre-TIP#398 compatibility flag */
+ /*
+ * Fetch the pre-TIP#398 compatibility flag.
+ */
+
{
const char *s;
Tcl_DString ds;
@@ -619,18 +627,20 @@ TclFinalizeIOSubsystem(void)
*/
if (active) {
-
TclChannelPreserve((Tcl_Channel)chanPtr);
+
/*
- * TIP #398: by default, we no longer set the channel back into
- * blocking mode. To restore the old blocking behavior, the
- * environment variable TCL_FLUSH_NONBLOCKING_ON_EXIT must be set
+ * TIP #398: by default, we no longer set the channel back into
+ * blocking mode. To restore the old blocking behavior, the
+ * environment variable TCL_FLUSH_NONBLOCKING_ON_EXIT must be set
* and not be "0".
*/
+
if (doflushnb) {
- /* Set the channel back into blocking mode to ensure that we wait
- * for all data to flush out.
- */
+ /*
+ * Set the channel back into blocking mode to ensure that we
+ * wait for all data to flush out.
+ */
(void) Tcl_SetChannelOption(NULL, (Tcl_Channel) chanPtr,
"-blocking", "on");
@@ -1511,8 +1521,10 @@ TclGetChannelFromObj(
if ((resPtr->interp == interp) /* Same interp context */
/* No epoch change in channel since lookup */
&& (resPtr->epoch == statePtr->epoch)) {
+ /*
+ * Have a valid saved lookup. Jump to end to return it.
+ */
- /* Have a valid saved lookup. Jump to end to return it. */
goto valid;
}
}
@@ -1527,7 +1539,10 @@ TclGetChannelFromObj(
}
if (resPtr && resPtr->refCount == 1) {
- /* Re-use the ResolvedCmdName struct */
+ /*
+ * Re-use the ResolvedCmdName struct.
+ */
+
Tcl_Release((ClientData) resPtr->statePtr);
} else {
@@ -1671,7 +1686,7 @@ Tcl_CreateChannel(
* Set the channel up initially in AUTO input translation mode to accept
* "\n", "\r" and "\r\n". Output translation mode is set to a platform
* specific default value. The eofChar is set to 0 for both input and
- * output, so that Tcl does not look for an in-file EOF indicator (e.g.
+ * output, so that Tcl does not look for an in-file EOF indicator (e.g.,
* ^Z) and does not append an EOF indicator to files.
*/
@@ -1899,7 +1914,6 @@ Tcl_StackChannel(
*/
if (((mask & TCL_READABLE) != 0) && (statePtr->inQueueHead != NULL)) {
-
/*
* When statePtr->inQueueHead is not NULL, we know
* prevChanPtr->inQueueHead must be NULL.
@@ -2031,9 +2045,7 @@ Tcl_UnstackChannel(
* of registered channels we wind down the state of the
* transformation, and then restore the state of underlying channel
* into the old structure.
- */
-
- /*
+ *
* TODO: Figure out how to handle the situation where the chan
* operations called below by this unstacking operation cause
* another unstacking recursively. In that case the downChanPtr
@@ -2511,6 +2523,7 @@ RecycleBuffer(
/*
* Do we have to free the buffer to the OS?
*/
+
if (IsShared(bufPtr)) {
mustDiscard = 1;
}
@@ -2521,9 +2534,8 @@ RecycleBuffer(
}
/*
- * Only save buffers which have the requested buffersize for the
- * channel. This is to honor dynamic changes of the buffersize
- * made by the user.
+ * Only save buffers which have the requested buffersize for the channel.
+ * This is to honor dynamic changes of the buffersize made by the user.
*/
if ((bufPtr->bufLength - BUFFER_PADDING) != statePtr->bufSize) {
@@ -2693,14 +2705,18 @@ FlushChannel(
/*
* Should we shift the current output buffer over to the output queue?
* First check that there are bytes in it. If so then...
- * If the output queue is empty, then yes, trusting the caller called
- * us only when written bytes ought to be flushed.
- * If the current output buffer is full, then yes, so we can meet
- * the post-condition that on a successful return to caller we've
- * left space in the current output buffer for more writing (the flush
- * call was to make new room).
- * If the channel is blocking, then yes, so we guarantee that
- * blocking flushes actually flush all pending data.
+ *
+ * If the output queue is empty, then yes, trusting the caller called us
+ * only when written bytes ought to be flushed.
+ *
+ * If the current output buffer is full, then yes, so we can meet the
+ * post-condition that on a successful return to caller we've left space
+ * in the current output buffer for more writing (the flush call was to
+ * make new room).
+ *
+ * If the channel is blocking, then yes, so we guarantee that blocking
+ * flushes actually flush all pending data.
+ *
* Otherwise, no. Keep the current output buffer where it is so more
* can be written to it, possibly filling it, to promote more efficient
* buffer usage.
@@ -2794,8 +2810,8 @@ FlushChannel(
/*
* TIP #219, Tcl Channel Reflection API.
* When defering the error copy a message from the bypass into
- * the unreported area. Or discard it if the new error is to be
- * ignored in favor of an earlier defered error.
+ * the unreported area. Or discard it if the new error is to
+ * be ignored in favor of an earlier defered error.
*/
Tcl_Obj *msg = statePtr->chanMsg;
@@ -2847,8 +2863,11 @@ FlushChannel(
ReleaseChannelBuffer(bufPtr);
break;
} else {
- /* TODO: Consider detecting and reacting to short writes
- * on blocking channels. Ought not happen. See iocmd-24.2. */
+ /*
+ * TODO: Consider detecting and reacting to short writes on
+ * blocking channels. Ought not happen. See iocmd-24.2.
+ */
+
wroteSome = 1;
}
@@ -2882,7 +2901,6 @@ FlushChannel(
ResetFlag(statePtr, BG_FLUSH_SCHEDULED);
ChanWatch(chanPtr, statePtr->interestMask);
} else {
-
/*
* When we are calledFromAsyncFlush, that means a writable
* state on the channel triggered the call, so we should be
@@ -2927,7 +2945,8 @@ FlushChannel(
(statePtr->outQueueHead == NULL) &&
((statePtr->curOutPtr == NULL) ||
IsBufferEmpty(statePtr->curOutPtr))) {
- errorCode = CloseChannelPart(interp, chanPtr, errorCode, TCL_CLOSE_WRITE);
+ errorCode = CloseChannelPart(interp, chanPtr, errorCode,
+ TCL_CLOSE_WRITE);
goto done;
}
@@ -3398,7 +3417,6 @@ Tcl_Close(
if (GotFlag(statePtr, TCL_WRITABLE) && (statePtr->encoding != NULL)
&& !(statePtr->outputEncodingFlags & TCL_ENCODING_START)) {
-
int code = CheckChannelErrors(statePtr, TCL_WRITABLE);
if (code == 0) {
@@ -3488,12 +3506,14 @@ Tcl_Close(
}
return TCL_ERROR;
}
+
/*
* Bug 97069ea11a: set error message if a flush code is set and no error
* message set up to now.
*/
+
if (flushcode != 0 && interp != NULL
- && 0 == Tcl_GetCharLength(Tcl_GetObjResult(interp)) ) {
+ && 0 == Tcl_GetCharLength(Tcl_GetObjResult(interp))) {
Tcl_SetErrno(flushcode);
Tcl_SetObjResult(interp,
Tcl_NewStringObj(Tcl_PosixError(interp), -1));
@@ -3588,8 +3608,8 @@ Tcl_CloseEx(
}
/*
- * A user may try to call half-close from within a channel close
- * handler. That won't do.
+ * A user may try to call half-close from within a channel close handler.
+ * That won't do.
*/
if (statePtr->flags & CHANNEL_INCLOSE) {
@@ -3660,9 +3680,12 @@ CloseWrite(
* closed. May still be used by some
* interpreter */
{
- /* Notes: clear-channel-handlers - write side only ? or keep around, just
- * not called. */
- /* No close cllbacks are run - channel is still open (read side) */
+ /*
+ * Notes: clear-channel-handlers - write side only ? or keep around, just
+ * not called.
+ *
+ * No close callbacks are run - channel is still open (read side)
+ */
ChannelState *statePtr = chanPtr->state;
/* State of real IO channel. */
@@ -3687,9 +3710,9 @@ CloseWrite(
* Notes: Due to the assertion of CHANNEL_CLOSEDWRITE in the flags
* FlushChannel() has called CloseChannelPart(). While we can still access
* "chan" (no structures were freed), the only place which may still
- * contain a message is the interpreter itself, and "CloseChannelPart" made
- * sure to lift any channel message it generated into it. Hence the NULL
- * argument in the call below.
+ * contain a message is the interpreter itself, and "CloseChannelPart"
+ * made sure to lift any channel message it generated into it. Hence the
+ * NULL argument in the call below.
*/
if (TclChanCaughtErrorBypass(interp, NULL)) {
@@ -3913,10 +3936,10 @@ Tcl_ClearChannelHandlers(
StopCopy(statePtr->csPtrW);
/*
- * Must set the interest mask now to 0, otherwise infinite loops
- * will occur if Tcl_DoOneEvent is called before the channel is
- * finally deleted in FlushChannel. This can happen if the channel
- * has a background flush active.
+ * Must set the interest mask now to 0, otherwise infinite loops will
+ * occur if Tcl_DoOneEvent is called before the channel is finally deleted
+ * in FlushChannel. This can happen if the channel has a background flush
+ * active.
*/
statePtr->interestMask = 0;
@@ -4185,22 +4208,24 @@ WillRead(
Channel *chanPtr)
{
if (chanPtr->typePtr == NULL) {
- /* Prevent read attempts on a closed channel */
+ /*
+ * Prevent read attempts on a closed channel.
+ */
+
DiscardInputQueued(chanPtr->state, 0);
Tcl_SetErrno(EINVAL);
return -1;
}
if ((chanPtr->typePtr->seekProc != NULL)
&& (Tcl_OutputBuffered((Tcl_Channel) chanPtr) > 0)) {
-
/*
- * CAVEAT - The assumption here is that FlushChannel() will
- * push out the bytes of any writes that are in progress.
- * Since this is a seekable channel, we assume it is not one
- * that can block and force bg flushing. Channels we know that
- * can do that -- sockets, pipes -- are not seekable. If the
- * assumption is wrong, more drastic measures may be required here
- * like temporarily setting the channel into blocking mode.
+ * CAVEAT - The assumption here is that FlushChannel() will push out
+ * the bytes of any writes that are in progress. Since this is a
+ * seekable channel, we assume it is not one that can block and force
+ * bg flushing. Channels we know that can do that - sockets, pipes -
+ * are not seekable. If the assumption is wrong, more drastic measures
+ * may be required here like temporarily setting the channel into
+ * blocking mode.
*/
if (FlushChannel(NULL, chanPtr, 0) != 0) {
@@ -4292,11 +4317,17 @@ Write(
&statePtr->outputEncodingState, dst,
dstLen + BUFFER_PADDING, &srcRead, &dstWrote, NULL);
- /* See chan-io-1.[89]. Tcl Bug 506297. */
+ /*
+ * See chan-io-1.[89]. Tcl Bug 506297.
+ */
+
statePtr->outputEncodingFlags &= ~TCL_ENCODING_START;
if ((result != TCL_OK) && (srcRead + dstWrote == 0)) {
- /* We're reading from invalid/incomplete UTF-8 */
+ /*
+ * We're reading from invalid/incomplete UTF-8.
+ */
+
ReleaseChannelBuffer(bufPtr);
if (total == 0) {
Tcl_SetErrno(EINVAL);
@@ -4336,11 +4367,10 @@ Write(
}
result |= Tcl_UtfToExternal(NULL, encoding, nl, nlLen,
- statePtr->outputEncodingFlags,
- &statePtr->outputEncodingState, dst,
- dstLen + BUFFER_PADDING, &srcRead, &dstWrote, NULL);
-
- assert (srcRead == nlLen);
+ statePtr->outputEncodingFlags,
+ &statePtr->outputEncodingState, dst,
+ dstLen + BUFFER_PADDING, &srcRead, &dstWrote, NULL);
+ assert(srcRead == nlLen);
bufPtr->nextAdded += dstWrote;
src++;
@@ -4354,11 +4384,11 @@ Write(
if (IsBufferOverflowing(bufPtr)) {
/*
- * When translating from UTF-8 to external encoding, we
- * allowed the translation to produce a character that crossed
- * the end of the output buffer, so that we would get a
- * completely full buffer before flushing it. The extra bytes
- * will be moved to the beginning of the next buffer.
+ * When translating from UTF-8 to external encoding, we allowed
+ * the translation to produce a character that crossed the end of
+ * the output buffer, so that we would get a completely full
+ * buffer before flushing it. The extra bytes will be moved to the
+ * beginning of the next buffer.
*/
saved = -SpaceLeft(bufPtr);
@@ -4378,15 +4408,16 @@ Write(
flushed += statePtr->bufSize;
/*
- * We just flushed. So if we have needNlFlush set to record
- * that we need to flush because theres a (translated) newline
- * in the buffer, that's likely not true any more. But there
- * is a tricky exception. If we have saved bytes that did not
- * really get flushed and those bytes came from a translation
- * of a newline as the last thing taken from the src array,
- * then needNlFlush needs to remain set to flag that the
- * next buffer still needs a newline flush.
+ * We just flushed. So if we have needNlFlush set to record that
+ * we need to flush because theres a (translated) newline in the
+ * buffer, that's likely not true any more. But there is a tricky
+ * exception. If we have saved bytes that did not really get
+ * flushed and those bytes came from a translation of a newline as
+ * the last thing taken from the src array, then needNlFlush needs
+ * to remain set to flag that the next buffer still needs a
+ * newline flush.
*/
+
if (needNlFlush && (saved == 0 || src[-1] != '\n')) {
needNlFlush = 0;
}
@@ -4492,8 +4523,8 @@ Tcl_GetsObj(
if (GotFlag(statePtr, CHANNEL_STICKY_EOF)) {
SetFlag(statePtr, CHANNEL_EOF);
- assert( statePtr->inputEncodingFlags & TCL_ENCODING_END );
- assert( !GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR) );
+ assert(statePtr->inputEncodingFlags & TCL_ENCODING_END);
+ assert(!GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR));
/* TODO: Do we need this? */
UpdateInterest(chanPtr);
@@ -4833,17 +4864,17 @@ Tcl_GetsObj(
*/
done:
- assert(!GotFlag(statePtr, CHANNEL_EOF)
- || GotFlag(statePtr, CHANNEL_STICKY_EOF)
- || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
-
- assert( !(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
- == (CHANNEL_EOF|CHANNEL_BLOCKED)) );
+ assert(!GotFlag(statePtr, CHANNEL_EOF)
+ || GotFlag(statePtr, CHANNEL_STICKY_EOF)
+ || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
+ assert(!(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
+ == (CHANNEL_EOF|CHANNEL_BLOCKED)));
/*
* Regenerate the top channel, in case it was changed due to
* self-modifying reflected transforms.
*/
+
if (chanPtr != statePtr->topChanPtr) {
TclChannelRelease((Tcl_Channel)chanPtr);
chanPtr = statePtr->topChanPtr;
@@ -4863,10 +4894,9 @@ Tcl_GetsObj(
* end-of-line or end-of-file has been seen. Bytes read from the input
* channel return as a ByteArray obj.
*
- * WARNING! The notion of "binary" used here is different from
- * notions of "binary" used in other places. In particular, this
- * "binary" routine may be called when an -eofchar is set on the
- * channel.
+ * WARNING! The notion of "binary" used here is different from notions
+ * of "binary" used in other places. In particular, this "binary" routine
+ * may be called when an -eofchar is set on the channel.
*
* Results:
* Number of characters accumulated in the object or -1 if error,
@@ -4932,8 +4962,8 @@ TclGetsObjBinary(
ResetFlag(statePtr, CHANNEL_BLOCKED);
while (1) {
/*
- * Subtract the number of bytes that were removed from channel
- * buffer during last call.
+ * Subtract the number of bytes that were removed from channel buffer
+ * during last call.
*/
if (bufPtr != NULL) {
@@ -4945,10 +4975,11 @@ TclGetsObjBinary(
if ((bufPtr == NULL) || (bufPtr->nextAdded == BUFFER_PADDING)) {
/*
- * All channel buffers were exhausted and the caller still
- * hasn't seen EOL. Need to read more bytes from the channel
- * device. Side effect is to allocate another channel buffer.
+ * All channel buffers were exhausted and the caller still hasn't
+ * seen EOL. Need to read more bytes from the channel device. Side
+ * effect is to allocate another channel buffer.
*/
+
if (GetInput(chanPtr) != 0) {
goto restore;
}
@@ -4958,15 +4989,15 @@ TclGetsObjBinary(
}
} else {
/*
- * Incoming CHANNEL_STICKY_EOF is filtered out on entry.
- * A new CHANNEL_STICKY_EOF set in this routine leads to
- * return before coming back here. When we are not dealing
- * with CHANNEL_STICKY_EOF, a CHANNEL_EOF implies an
- * empty buffer. Here the buffer is non-empty so we know
- * we're a non-EOF */
+ * Incoming CHANNEL_STICKY_EOF is filtered out on entry. A new
+ * CHANNEL_STICKY_EOF set in this routine leads to return before
+ * coming back here. When we are not dealing with
+ * CHANNEL_STICKY_EOF, a CHANNEL_EOF implies an empty buffer.
+ * Here the buffer is non-empty so we know we're a non-EOF.
+ */
- assert ( !GotFlag(statePtr, CHANNEL_STICKY_EOF) );
- assert ( !GotFlag(statePtr, CHANNEL_EOF) );
+ assert(!GotFlag(statePtr, CHANNEL_STICKY_EOF));
+ assert(!GotFlag(statePtr, CHANNEL_EOF));
}
dst = (unsigned char *) RemovePoint(bufPtr);
@@ -5033,8 +5064,8 @@ TclGetsObjBinary(
}
/*
- * Copy bytes from the channel buffer to the ByteArray.
- * This may realloc space, so keep track of result.
+ * Copy bytes from the channel buffer to the ByteArray. This may
+ * realloc space, so keep track of result.
*/
rawLen = dstEnd - dst;
@@ -5118,11 +5149,11 @@ TclGetsObjBinary(
*/
done:
- assert(!GotFlag(statePtr, CHANNEL_EOF)
- || GotFlag(statePtr, CHANNEL_STICKY_EOF)
- || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
- assert( !(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
- == (CHANNEL_EOF|CHANNEL_BLOCKED)) );
+ assert(!GotFlag(statePtr, CHANNEL_EOF)
+ || GotFlag(statePtr, CHANNEL_STICKY_EOF)
+ || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
+ assert(!(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
+ == (CHANNEL_EOF|CHANNEL_BLOCKED)));
UpdateInterest(chanPtr);
TclChannelRelease((Tcl_Channel)chanPtr);
return copiedTotal;
@@ -5255,15 +5286,15 @@ FilterInputBytes(
}
} else {
/*
- * Incoming CHANNEL_STICKY_EOF is filtered out on entry.
- * A new CHANNEL_STICKY_EOF set in this routine leads to
- * return before coming back here. When we are not dealing
- * with CHANNEL_STICKY_EOF, a CHANNEL_EOF implies an
- * empty buffer. Here the buffer is non-empty so we know
- * we're a non-EOF */
+ * Incoming CHANNEL_STICKY_EOF is filtered out on entry. A new
+ * CHANNEL_STICKY_EOF set in this routine leads to return before
+ * coming back here. When we are not dealing with CHANNEL_STICKY_EOF,
+ * a CHANNEL_EOF implies an empty buffer. Here the buffer is
+ * non-empty so we know we're a non-EOF.
+ */
- assert ( !GotFlag(statePtr, CHANNEL_STICKY_EOF) );
- assert ( !GotFlag(statePtr, CHANNEL_EOF) );
+ assert(!GotFlag(statePtr, CHANNEL_STICKY_EOF));
+ assert(!GotFlag(statePtr, CHANNEL_EOF));
}
/*
@@ -5593,7 +5624,9 @@ Tcl_ReadRaw(
return -1;
}
- /* First read bytes from the push-back buffers. */
+ /*
+ * First read bytes from the push-back buffers.
+ */
while (chanPtr->inQueueHead && bytesToRead > 0) {
ChannelBuffer *bufPtr = chanPtr->inQueueHead;
@@ -5601,7 +5634,9 @@ Tcl_ReadRaw(
int toCopy = (bytesInBuffer < bytesToRead) ? bytesInBuffer
: bytesToRead;
- /* Copy the current chunk into the read buffer. */
+ /*
+ * Copy the current chunk into the read buffer.
+ */
memcpy(readBuf, RemovePoint(bufPtr), (size_t) toCopy);
bufPtr->nextRemoved += toCopy;
@@ -5609,7 +5644,9 @@ Tcl_ReadRaw(
readBuf += toCopy;
bytesToRead -= toCopy;
- /* If the current buffer is empty recycle it. */
+ /*
+ * If the current buffer is empty recycle it.
+ */
if (IsBufferEmpty(bufPtr)) {
chanPtr->inQueueHead = bufPtr->nextPtr;
@@ -5621,37 +5658,40 @@ Tcl_ReadRaw(
}
/*
- * Go to the driver only if we got nothing from pushback.
- * Have to do it this way to avoid EOF mis-timings when we
- * consider the ability that EOF may not be a permanent
- * condition in the driver, and in that case we have to
- * synchronize.
+ * Go to the driver only if we got nothing from pushback. Have to do it
+ * this way to avoid EOF mis-timings when we consider the ability that EOF
+ * may not be a permanent condition in the driver, and in that case we
+ * have to synchronize.
*/
if (copied) {
return copied;
}
- /* This test not needed. */
- if (bytesToRead > 0) {
+ /*
+ * This test not needed.
+ */
+ if (bytesToRead > 0) {
int nread = ChanRead(chanPtr, readBuf, bytesToRead);
if (nread > 0) {
- /* Successful read (short is OK) - add to bytes copied */
+ /*
+ * Successful read (short is OK) - add to bytes copied.
+ */
+
copied += nread;
} else if (nread < 0) {
/*
- * An error signaled. If CHANNEL_BLOCKED, then the error
- * is not real, but an indication of blocked state. In
- * that case, retain the flag and let caller receive the
- * short read of copied bytes from the pushback.
- * HOWEVER, if copied==0 bytes from pushback then repeat
- * signalling the blocked state as an error to caller so
- * there is no false report of an EOF.
- * When !CHANNEL_BLOCKED, the error is real and passes on
- * to caller.
+ * An error signaled. If CHANNEL_BLOCKED, then the error is not
+ * real, but an indication of blocked state. In that case, retain
+ * the flag and let caller receive the short read of copied bytes
+ * from the pushback. HOWEVER, if copied==0 bytes from pushback
+ * then repeat signalling the blocked state as an error to caller
+ * so there is no false report of an EOF. When !CHANNEL_BLOCKED,
+ * the error is real and passes on to caller.
*/
+
if (!GotFlag(statePtr, CHANNEL_BLOCKED) || copied == 0) {
copied = -1;
}
@@ -5788,21 +5828,23 @@ DoReadChars(
/*
* Early out when next read will see eofchar.
*
- * NOTE: See DoRead for argument that it's a bug (one we're keeping)
- * to have this escape before the one for zero-char read request.
+ * NOTE: See DoRead for argument that it's a bug (one we're keeping) to
+ * have this escape before the one for zero-char read request.
*/
if (GotFlag(statePtr, CHANNEL_STICKY_EOF)) {
SetFlag(statePtr, CHANNEL_EOF);
- assert( statePtr->inputEncodingFlags & TCL_ENCODING_END );
- assert( !GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR) );
+ assert(statePtr->inputEncodingFlags & TCL_ENCODING_END);
+ assert(!GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR));
/* TODO: We don't need this call? */
UpdateInterest(chanPtr);
return 0;
}
- /* Special handling for zero-char read request. */
+ /*
+ * Special handling for zero-char read request.
+ */
if (toRead == 0) {
if (GotFlag(statePtr, CHANNEL_EOF)) {
statePtr->inputEncodingFlags |= TCL_ENCODING_START;
@@ -5821,7 +5863,10 @@ DoReadChars(
chanPtr = statePtr->topChanPtr;
TclChannelPreserve((Tcl_Channel)chanPtr);
- /* Must clear the BLOCKED|EOF flags here since we check before reading */
+ /*
+ * Must clear the BLOCKED|EOF flags here since we check before reading.
+ */
+
if (GotFlag(statePtr, CHANNEL_EOF)) {
statePtr->inputEncodingFlags |= TCL_ENCODING_START;
}
@@ -5879,10 +5924,11 @@ DoReadChars(
}
/*
- * Failure to fill a channel buffer may have left channel reporting
- * a "blocked" state, but so long as we fulfilled the request here,
- * the caller does not consider us blocked.
+ * Failure to fill a channel buffer may have left channel reporting a
+ * "blocked" state, but so long as we fulfilled the request here, the
+ * caller does not consider us blocked.
*/
+
if (toRead == 0) {
ResetFlag(statePtr, CHANNEL_BLOCKED);
}
@@ -5891,6 +5937,7 @@ DoReadChars(
* Regenerate the top channel, in case it was changed due to
* self-modifying reflected transforms.
*/
+
if (chanPtr != statePtr->topChanPtr) {
TclChannelRelease((Tcl_Channel)chanPtr);
chanPtr = statePtr->topChanPtr;
@@ -5901,11 +5948,12 @@ DoReadChars(
* Update the notifier state so we don't block while there is still data
* in the buffers.
*/
- assert(!GotFlag(statePtr, CHANNEL_EOF)
- || GotFlag(statePtr, CHANNEL_STICKY_EOF)
- || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
- assert( !(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
- == (CHANNEL_EOF|CHANNEL_BLOCKED)) );
+
+ assert(!GotFlag(statePtr, CHANNEL_EOF)
+ || GotFlag(statePtr, CHANNEL_STICKY_EOF)
+ || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
+ assert(!(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
+ == (CHANNEL_EOF|CHANNEL_BLOCKED)));
UpdateInterest(chanPtr);
TclChannelRelease((Tcl_Channel)chanPtr);
return copied;
@@ -6022,11 +6070,10 @@ ReadChars(
int numBytes, srcLen = BytesLeft(bufPtr);
/*
- * One src byte can yield at most one character. So when the
- * number of src bytes we plan to read is less than the limit on
- * character count to be read, clearly we will remain within that
- * limit, and we can use the value of "srcLen" as a tighter limit
- * for sizing receiving buffers.
+ * One src byte can yield at most one character. So when the number of
+ * src bytes we plan to read is less than the limit on character count to
+ * be read, clearly we will remain within that limit, and we can use the
+ * value of "srcLen" as a tighter limit for sizing receiving buffers.
*/
int toRead = ((charsToRead<0)||(charsToRead > srcLen)) ? srcLen : charsToRead;
@@ -6044,6 +6091,7 @@ ReadChars(
Tcl_AppendToObj(objPtr, NULL, dstLimit);
if (toRead == srcLen) {
unsigned int size;
+
dst = TclGetStringStorage(objPtr, &size) + numBytes;
dstLimit = size - numBytes;
} else {
@@ -6051,19 +6099,18 @@ ReadChars(
}
/*
- * This routine is burdened with satisfying several constraints.
- * It cannot append more than 'charsToRead` chars onto objPtr.
- * This is measured after encoding and translation transformations
- * are completed. There is no precise number of src bytes that can
- * be associated with the limit. Yet, when we are done, we must know
- * precisely the number of src bytes that were consumed to produce
- * the appended chars, so that all subsequent bytes are left in
- * the buffers for future read operations.
+ * This routine is burdened with satisfying several constraints. It cannot
+ * append more than 'charsToRead` chars onto objPtr. This is measured
+ * after encoding and translation transformations are completed. There is
+ * no precise number of src bytes that can be associated with the limit.
+ * Yet, when we are done, we must know precisely the number of src bytes
+ * that were consumed to produce the appended chars, so that all
+ * subsequent bytes are left in the buffers for future read operations.
*
- * The consequence is that we have no choice but to implement a
- * "trial and error" approach, where in general we may need to
- * perform transformations and copies multiple times to achieve
- * a consistent set of results. This takes the shape of a loop.
+ * The consequence is that we have no choice but to implement a "trial and
+ * error" approach, where in general we may need to perform
+ * transformations and copies multiple times to achieve a consistent set
+ * of results. This takes the shape of a loop.
*/
while (1) {
@@ -6076,18 +6123,17 @@ ReadChars(
}
/*
- * Perform the encoding transformation. Read no more than
- * srcLen bytes, write no more than dstLimit bytes.
+ * Perform the encoding transformation. Read no more than srcLen
+ * bytes, write no more than dstLimit bytes.
*
- * Some trickiness with encoding flags here. We do not want
- * the end of a buffer to be treated as the end of all input
- * when the presence of bytes in a next buffer are already
- * known to exist. This is checked with an assert() because
- * so far no test case causing the assertion to be false has
- * been created. The normal operations of channel reading
- * appear to cause EOF and TCL_ENCODING_END setting to appear
- * only in situations where there are no further bytes in
- * any buffers.
+ * Some trickiness with encoding flags here. We do not want the end
+ * of a buffer to be treated as the end of all input when the presence
+ * of bytes in a next buffer are already known to exist. This is
+ * checked with an assert() because so far no test case causing the
+ * assertion to be false has been created. The normal operations of
+ * channel reading appear to cause EOF and TCL_ENCODING_END setting to
+ * appear only in situations where there are no further bytes in any
+ * buffers.
*/
assert(bufPtr->nextPtr == NULL || BytesLeft(bufPtr->nextPtr) == 0
@@ -6098,10 +6144,10 @@ ReadChars(
dst, dstLimit, &srcRead, &dstDecoded, &numChars);
/*
- * Perform the translation transformation in place. Read no more
- * than the dstDecoded bytes the encoding transformation actually
- * produced. Capture the number of bytes written in dstWrote.
- * Capture the number of bytes actually consumed in dstRead.
+ * Perform the translation transformation in place. Read no more than
+ * the dstDecoded bytes the encoding transformation actually produced.
+ * Capture the number of bytes written in dstWrote. Capture the number
+ * of bytes actually consumed in dstRead.
*/
dstWrote = dstLimit;
@@ -6109,11 +6155,9 @@ ReadChars(
TranslateInputEOL(statePtr, dst, dst, &dstWrote, &dstRead);
if (dstRead < dstDecoded) {
-
/*
- * The encoding transformation produced bytes that the
- * translation transformation did not consume. Why did
- * this happen?
+ * The encoding transformation produced bytes that the translation
+ * transformation did not consume. Why did this happen?
*/
if (statePtr->inEofChar && dst[dstRead] == statePtr->inEofChar) {
@@ -6122,40 +6166,38 @@ ReadChars(
* we saw it and stopped translating at that point.
*
* NOTE the bizarre spec of TranslateInputEOL in this case.
- * Clearly the eof char had to be read in order to account
- * for the stopping, but the value of dstRead does not
- * include it.
+ * Clearly the eof char had to be read in order to account for
+ * the stopping, but the value of dstRead does not include it.
*
- * Also rather bizarre, our caller can only notice an
- * EOF condition if we return the value -1 as the number
- * of chars read. This forces us to perform a 2-call
- * dance where the first call can read all the chars
- * up to the eof char, and the second call is solely
- * for consuming the encoded eof char then pointed at
- * by src so that we can return that magic -1 value.
- * This seems really wasteful, especially since
- * the first decoding pass of each call is likely to
- * decode many bytes beyond that eof char that's all we
- * care about.
+ * Also rather bizarre, our caller can only notice an EOF
+ * condition if we return the value -1 as the number of chars
+ * read. This forces us to perform a 2-call dance where the
+ * first call can read all the chars up to the eof char, and
+ * the second call is solely for consuming the encoded eof
+ * char then pointed at by src so that we can return that
+ * magic -1 value. This seems really wasteful, especially
+ * since the first decoding pass of each call is likely to
+ * decode many bytes beyond that eof char that's all we care
+ * about.
*/
if (dstRead == 0) {
/*
- * Curious choice in the eof char handling. We leave
- * the eof char in the buffer. So, no need to compute
- * a proper srcRead value. At this point, there
- * are no chars before the eof char in the buffer.
+ * Curious choice in the eof char handling. We leave the
+ * eof char in the buffer. So, no need to compute a proper
+ * srcRead value. At this point, there are no chars before
+ * the eof char in the buffer.
*/
+
Tcl_SetObjLength(objPtr, numBytes);
return -1;
}
{
/*
- * There are chars leading the buffer before the eof
- * char. Adjust the dstLimit so we go back and read
- * only those and do not encounter the eof char this
- * time.
+ * There are chars leading the buffer before the eof char.
+ * Adjust the dstLimit so we go back and read only those
+ * and do not encounter the eof char this time.
*/
dstLimit = dstRead - 1 + TCL_UTF_MAX;
@@ -6167,10 +6209,9 @@ ReadChars(
}
/*
- * 2) The other way to read fewer bytes than are decoded
- * is when the final byte is \r and we're in a CRLF
- * translation mode so we cannot decide whether to
- * record \r or \n yet.
+ * 2) The other way to read fewer bytes than are decoded is when
+ * the final byte is \r and we're in a CRLF translation mode so
+ * we cannot decide whether to record \r or \n yet.
*/
assert(dst[dstRead] == '\r');
@@ -6178,10 +6219,10 @@ ReadChars(
if (dstWrote > 0) {
/*
- * There are chars we can read before we hit the bare cr.
- * Go back with a smaller dstLimit so we get them in the
- * next pass, compute a matching srcRead, and don't end
- * up back here in this call.
+ * There are chars we can read before we hit the bare CR. Go
+ * back with a smaller dstLimit so we get them in the next
+ * pass, compute a matching srcRead, and don't end up back
+ * here in this call.
*/
dstLimit = dstRead - 1 + TCL_UTF_MAX;
@@ -6195,9 +6236,9 @@ ReadChars(
assert(dstRead == 0);
/*
- * We decoded only the bare cr, and we cannot read a
- * translated char from that alone. We have to know what's
- * next. So why do we only have the one decoded char?
+ * We decoded only the bare CR, and we cannot read a translated
+ * char from that alone. We have to know what's next. So why do
+ * we only have the one decoded char?
*/
if (code != TCL_OK) {
@@ -6238,10 +6279,9 @@ ReadChars(
}
} else if (statePtr->flags & CHANNEL_EOF) {
-
/*
- * The bare \r is the only char and we will never read
- * a subsequent char to make the determination.
+ * The bare \r is the only char and we will never read a
+ * subsequent char to make the determination.
*/
dst[0] = '\r';
@@ -6251,8 +6291,8 @@ ReadChars(
}
/*
- * Revise the dstRead value so that the numChars calc
- * below correctly computes zero characters read.
+ * Revise the dstRead value so that the numChars calc below
+ * correctly computes zero characters read.
*/
dstRead = numChars;
@@ -6261,9 +6301,9 @@ ReadChars(
}
/*
- * The translation transformation can only reduce the number
- * of chars when it converts \r\n into \n. The reduction in
- * the number of chars is the difference in bytes read and written.
+ * The translation transformation can only reduce the number of chars
+ * when it converts \r\n into \n. The reduction in the number of chars
+ * is the difference in bytes read and written.
*/
numChars -= (dstRead - dstWrote);
@@ -6273,10 +6313,9 @@ ReadChars(
/*
* TODO: This cannot happen anymore.
*
- * We read more chars than allowed. Reset limits to
- * prevent that and try again. Don't forget the extra
- * padding of TCL_UTF_MAX bytes demanded by the
- * Tcl_ExternalToUtf() call!
+ * We read more chars than allowed. Reset limits to prevent that
+ * and try again. Don't forget the extra padding of TCL_UTF_MAX
+ * bytes demanded by the Tcl_ExternalToUtf() call!
*/
dstLimit = Tcl_UtfAtIndex(dst, charsToRead) - 1 + TCL_UTF_MAX - dst;
@@ -6289,18 +6328,19 @@ ReadChars(
if (dstWrote == 0) {
ChannelBuffer *nextPtr;
- /* We were not able to read any chars. */
+ /*
+ * We were not able to read any chars.
+ */
- assert (numChars == 0);
+ assert(numChars == 0);
/*
- * There is one situation where this is the correct final
- * result. If the src buffer contains only a single \n
- * byte, and we are in TCL_TRANSLATE_AUTO mode, and
- * when the translation pass was made the INPUT_SAW_CR
- * flag was set on the channel. In that case, the
- * correct behavior is to consume that \n and produce the
- * empty string.
+ * There is one situation where this is the correct final result.
+ * If the src buffer contains only a single \n byte, and we are in
+ * TCL_TRANSLATE_AUTO mode, and when the translation pass was made
+ * the INPUT_SAW_CR flag was set on the channel. In that case, the
+ * correct behavior is to consume that \n and produce the empty
+ * string.
*/
if (dstRead == 1 && dst[0] == '\n') {
@@ -6309,12 +6349,13 @@ ReadChars(
goto consume;
}
- /* Otherwise, reading zero characters indicates there's
- * something incomplete at the end of the src buffer.
- * Maybe there were not enough src bytes to decode into
- * a char. Maybe a lone \r could not be translated (crlf
- * mode). Need to combine any unused src bytes we have
- * in the first buffer with subsequent bytes to try again.
+ /*
+ * Otherwise, reading zero characters indicates there's something
+ * incomplete at the end of the src buffer. Maybe there were not
+ * enough src bytes to decode into a char. Maybe a lone \r could
+ * not be translated (crlf mode). Need to combine any unused src
+ * bytes we have in the first buffer with subsequent bytes to try
+ * again.
*/
nextPtr = bufPtr->nextPtr;
@@ -6329,15 +6370,15 @@ ReadChars(
/*
* Space is made at the beginning of the buffer to copy the
- * previous unused bytes there. Check first if the buffer we
- * are using actually has enough space at its beginning for
- * the data we are copying. Because if not we will write over
- * the buffer management information, especially the 'nextPtr'.
+ * previous unused bytes there. Check first if the buffer we are
+ * using actually has enough space at its beginning for the data
+ * we are copying. Because if not we will write over the buffer
+ * management information, especially the 'nextPtr'.
*
- * Note that the BUFFER_PADDING (See AllocChannelBuffer) is
- * used to prevent exactly this situation. I.e. it should never
- * happen. Therefore it is ok to panic should it happen despite
- * the precautions.
+ * Note that the BUFFER_PADDING (See AllocChannelBuffer) is used
+ * to prevent exactly this situation. I.e. it should never happen.
+ * Therefore it is ok to panic should it happen despite the
+ * precautions.
*/
if (nextPtr->nextRemoved - srcLen < 0) {
@@ -6356,10 +6397,12 @@ ReadChars(
consume:
bufPtr->nextRemoved += srcRead;
+
/*
- * If this read contained multibyte characters, revise factorPtr
- * so the next read will allocate bigger buffers.
+ * If this read contained multibyte characters, revise factorPtr so
+ * the next read will allocate bigger buffers.
*/
+
if (numChars && numChars < srcRead) {
*factorPtr = srcRead * UTF_EXPANSION_FACTOR / numChars;
}
@@ -6407,22 +6450,27 @@ TranslateInputEOL(
int inEofChar = statePtr->inEofChar;
/*
- * Depending on the translation mode in use, there's no need
- * to scan more srcLen bytes at srcStart than can possibly transform
- * to dstLen bytes. This keeps the scan for eof char below from
- * being pointlessly long.
+ * Depending on the translation mode in use, there's no need to scan more
+ * srcLen bytes at srcStart than can possibly transform to dstLen bytes.
+ * This keeps the scan for eof char below from being pointlessly long.
*/
switch (statePtr->inputTranslation) {
case TCL_TRANSLATE_LF:
case TCL_TRANSLATE_CR:
if (srcLen > dstLen) {
- /* In these modes, each src byte become a dst byte. */
+ /*
+ * In these modes, each src byte become a dst byte.
+ */
+
srcLen = dstLen;
}
break;
default:
- /* In other modes, at most 2 src bytes become a dst byte. */
+ /*
+ * In other modes, at most 2 src bytes become a dst byte.
+ */
+
if (srcLen/2 > dstLen) {
srcLen = 2 * dstLen;
}
@@ -6755,7 +6803,7 @@ GetInput(
* eofchar.
*/
- assert( !GotFlag(statePtr, CHANNEL_STICKY_EOF) );
+ assert(!GotFlag(statePtr, CHANNEL_STICKY_EOF));
/*
* Prevent reading from a dead channel -- a channel that has been closed
@@ -6769,24 +6817,21 @@ GetInput(
}
/*
- * WARNING: There was once a comment here claiming that it was
- * a bad idea to make another call to the inputproc of a channel
- * driver when EOF has already been detected on the channel. Through
- * much of Tcl's history, this warning was then completely negated
- * by having all (most?) read paths clear the EOF setting before
- * reaching here. So we had a guard that was never triggered.
+ * WARNING: There was once a comment here claiming that it was a bad idea
+ * to make another call to the inputproc of a channel driver when EOF has
+ * already been detected on the channel. Through much of Tcl's history,
+ * this warning was then completely negated by having all (most?) read
+ * paths clear the EOF setting before reaching here. So we had a guard
+ * that was never triggered.
+ *
+ * Don't be tempted to restore the guard. Even if EOF is set on the
+ * channel, continue through and call the inputproc again. This is the
+ * way to enable the ability to [read] again beyond the EOF, which seems a
+ * strange thing to do, but for which use cases exist [Tcl Bug 5adc350683]
+ * and which may even be essential for channels representing things like
+ * ttys or other devices where the stream might take the logical form of a
+ * series of 'files' separated by an EOF condition.
*
- * Don't be tempted to restore the guard. Even if EOF is set on
- * the channel, continue through and call the inputproc again. This
- * is the way to enable the ability to [read] again beyond the EOF,
- * which seems a strange thing to do, but for which use cases exist
- * [Tcl Bug 5adc350683] and which may even be essential for channels
- * representing things like ttys or other devices where the stream
- * might take the logical form of a series of 'files' separated by
- * an EOF condition.
- */
-
- /*
* First check for more buffers in the pushback area of the topmost
* channel in the stack and use them. They can be the result of a
* transformation which went away without reading all the information
@@ -6794,7 +6839,6 @@ GetInput(
*/
if (chanPtr->inQueueHead != NULL) {
-
/* TODO: Tests to cover this. */
assert(statePtr->inQueueHead == NULL);
@@ -6824,8 +6868,9 @@ GetInput(
/*
* Check the actual buffersize against the requested buffersize.
- * Saved buffers of the wrong size are squashed. This is done
- * to honor dynamic changes of the buffersize made by the user.
+ * Saved buffers of the wrong size are squashed. This is done to honor
+ * dynamic changes of the buffersize made by the user.
+ *
* TODO: Tests to cover this.
*/
@@ -7132,7 +7177,7 @@ Tcl_Tell(
* Truncate a channel to the given length.
*
* Results:
- * TCL_OK on success, TCL_ERROR if the operation failed (e.g. is not
+ * TCL_OK on success, TCL_ERROR if the operation failed (e.g., is not
* supported by the type of channel, or the underlying OS operation
* failed in some way).
*
@@ -9492,7 +9537,10 @@ CopyData(
}
if (size == 0) {
if (!GotFlag(inStatePtr, CHANNEL_NONBLOCKING)) {
- /* We allowed a short read. Keep trying. */
+ /*
+ * We allowed a short read. Keep trying.
+ */
+
continue;
}
if (bufObj != NULL) {
@@ -9706,7 +9754,7 @@ DoRead(
ChannelState *statePtr = chanPtr->state;
char *p = dst;
- assert (bytesToRead >= 0);
+ assert(bytesToRead >= 0);
/*
* Early out when we know a read will get the eofchar.
@@ -9722,15 +9770,18 @@ DoRead(
if (GotFlag(statePtr, CHANNEL_STICKY_EOF)) {
SetFlag(statePtr, CHANNEL_EOF);
- assert( statePtr->inputEncodingFlags & TCL_ENCODING_END );
- assert( !GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR) );
+ assert(statePtr->inputEncodingFlags & TCL_ENCODING_END);
+ assert(!GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR));
/* TODO: Don't need this call */
UpdateInterest(chanPtr);
return 0;
}
- /* Special handling for zero-char read request. */
+ /*
+ * Special handling for zero-char read request.
+ */
+
if (bytesToRead == 0) {
if (GotFlag(statePtr, CHANNEL_EOF)) {
statePtr->inputEncodingFlags |= TCL_ENCODING_START;
@@ -9745,8 +9796,8 @@ DoRead(
TclChannelPreserve((Tcl_Channel)chanPtr);
while (bytesToRead) {
/*
- * Each pass through the loop is intended to process up to
- * one channel buffer.
+ * Each pass through the loop is intended to process up to one channel
+ * buffer.
*/
int bytesRead, bytesWritten;
@@ -9758,33 +9809,39 @@ DoRead(
while (!bufPtr || /* We got no buffer! OR */
(!IsBufferFull(bufPtr) && /* Our buffer has room AND */
- (BytesLeft(bufPtr) < bytesToRead) ) ) {
- /* Not enough bytes in it
- * yet to fill the dst */
+ (BytesLeft(bufPtr) < bytesToRead))) {
+ /* Not enough bytes in it yet
+ * to fill the dst */
int code;
moreData:
code = GetInput(chanPtr);
bufPtr = statePtr->inQueueHead;
- assert (bufPtr != NULL);
+ assert(bufPtr != NULL);
if (GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)) {
- /* Further reads cannot do any more */
+ /*
+ * Further reads cannot do any more.
+ */
+
break;
}
if (code) {
- /* Read error */
+ /*
+ * Read error
+ */
+
UpdateInterest(chanPtr);
TclChannelRelease((Tcl_Channel)chanPtr);
return -1;
}
- assert (IsBufferFull(bufPtr));
+ assert(IsBufferFull(bufPtr));
}
- assert (bufPtr != NULL);
+ assert(bufPtr != NULL);
bytesRead = BytesLeft(bufPtr);
bytesWritten = bytesToRead;
@@ -9799,8 +9856,8 @@ DoRead(
/*
* Buffer is not empty. How can that be?
*
- * 0) We stopped early because we got all the bytes
- * we were seeking. That's fine.
+ * 0) We stopped early because we got all the bytes we were
+ * seeking. That's fine.
*/
if (bytesToRead == 0) {
@@ -9816,8 +9873,8 @@ DoRead(
}
/*
- * 2) The buffer holds a \r while in CRLF translation,
- * followed by the end of the buffer.
+ * 2) The buffer holds a \r while in CRLF translation, followed by
+ * the end of the buffer.
*/
assert(statePtr->inputTranslation == TCL_TRANSLATE_CRLF);
@@ -9825,26 +9882,38 @@ DoRead(
assert(BytesLeft(bufPtr) == 1);
if (bufPtr->nextPtr == NULL) {
- /* There's no more buffered data.... */
+ /*
+ * There's no more buffered data...
+ */
if (statePtr->flags & CHANNEL_EOF) {
- /* ...and there never will be. */
+ /*
+ * ...and there never will be.
+ */
*p++ = '\r';
bytesToRead--;
bufPtr->nextRemoved++;
} else if (statePtr->flags & CHANNEL_BLOCKED) {
- /* ...and we cannot get more now. */
+ /*
+ * ...and we cannot get more now.
+ */
+
SetFlag(statePtr, CHANNEL_NEED_MORE_DATA);
break;
} else {
- /* ... so we need to get some. */
+ /*
+ * ...so we need to get some.
+ */
+
goto moreData;
}
}
if (bufPtr->nextPtr) {
- /* There's a next buffer. Shift orphan \r to it. */
+ /*
+ * There's a next buffer. Shift orphan \r to it.
+ */
ChannelBuffer *nextPtr = bufPtr->nextPtr;
@@ -9869,8 +9938,8 @@ DoRead(
}
/*
- * When there's no buffered data to read, and we're at EOF,
- * escape to the caller.
+ * When there's no buffered data to read, and we're at EOF, escape to
+ * the caller.
*/
if (GotFlag(statePtr, CHANNEL_EOF)
@@ -9882,11 +9951,11 @@ DoRead(
ResetFlag(statePtr, CHANNEL_BLOCKED);
}
- assert(!GotFlag(statePtr, CHANNEL_EOF)
- || GotFlag(statePtr, CHANNEL_STICKY_EOF)
- || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
- assert( !(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
- == (CHANNEL_EOF|CHANNEL_BLOCKED)) );
+ assert(!GotFlag(statePtr, CHANNEL_EOF)
+ || GotFlag(statePtr, CHANNEL_STICKY_EOF)
+ || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
+ assert(!(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
+ == (CHANNEL_EOF|CHANNEL_BLOCKED)));
UpdateInterest(chanPtr);
TclChannelRelease((Tcl_Channel)chanPtr);
return (int)(p - dst);
diff --git a/generic/tclIORChan.c b/generic/tclIORChan.c
index 2fed3f4..433fb6f 100644
--- a/generic/tclIORChan.c
+++ b/generic/tclIORChan.c
@@ -851,11 +851,12 @@ TclChanPostEventObjCmd(
}
/*
- * Note that the search above subsumes several of the older checks, namely:
+ * Note that the search above subsumes several of the older checks,
+ * namely:
*
- * (1) Does the channel handle refer to a reflected channel ?
+ * (1) Does the channel handle refer to a reflected channel?
* (2) Is the post event issued from the interpreter holding the handler
- * of the reflected channel ?
+ * of the reflected channel?
*
* A successful search answers yes to both. Because the map holds only
* handles of reflected channels, and only of such whose handler is
@@ -939,7 +940,8 @@ TclChanPostEventObjCmd(
(void) GetThreadReflectedChannelMap();
- /* XXX Race condition !!
+ /*
+ * XXX Race condition !!
* XXX The destination thread may not exist anymore already.
* XXX (Delayed postevent executed after channel got removed).
* XXX Can we detect this ? (check the validity of the owner threadid ?)
@@ -1221,8 +1223,8 @@ ReflectClose(
#endif
tctPtr = ((Channel *)rcPtr->chan)->typePtr;
if (tctPtr && tctPtr != &tclRChannelType) {
- ckfree(tctPtr);
- ((Channel *)rcPtr->chan)->typePtr = NULL;
+ ckfree(tctPtr);
+ ((Channel *)rcPtr->chan)->typePtr = NULL;
}
Tcl_EventuallyFree(rcPtr, (Tcl_FreeProc *) FreeReflectedChannel);
return (result == TCL_OK) ? EOK : EINVAL;
@@ -1272,7 +1274,10 @@ ReflectInput(
if (p.base.code != TCL_OK) {
if (p.base.code < 0) {
- /* No error message, this is an errno signal. */
+ /*
+ * No error message, this is an errno signal.
+ */
+
*errorCodePtr = -p.base.code;
} else {
PassReceivedError(rcPtr->chan, &p);
@@ -1375,7 +1380,10 @@ ReflectOutput(
if (p.base.code != TCL_OK) {
if (p.base.code < 0) {
- /* No error message, this is an errno signal. */
+ /*
+ * No error message, this is an errno signal.
+ */
+
*errorCodePtr = -p.base.code;
} else {
PassReceivedError(rcPtr->chan, &p);
@@ -1426,8 +1434,8 @@ ReflectOutput(
if ((written == 0) && (toWrite > 0)) {
/*
- * The handler claims to have written nothing of what it was
- * given. That is bad.
+ * The handler claims to have written nothing of what it was given.
+ * That is bad.
*/
SetChannelErrorStr(rcPtr->chan, msg_write_nothing);
@@ -2373,8 +2381,8 @@ InvokeTclMethod(
* None.
*
* Users:
- * ReflectInput/Output(), to enable the signaling of EAGAIN
- * on 0-sized short reads/writes.
+ * ReflectInput/Output(), to enable the signaling of EAGAIN on 0-sized
+ * short reads/writes.
*
*----------------------------------------------------------------------
*/
@@ -2560,7 +2568,10 @@ DeleteReflectedChannelMap(
evPtr = resultPtr->evPtr;
- /* Basic crash safety until this routine can get revised [3411310] */
+ /*
+ * Basic crash safety until this routine can get revised [3411310]
+ */
+
if (evPtr == NULL) {
continue;
}
@@ -2675,8 +2686,8 @@ DeleteThreadReflectedChannelMap(
/*
* Go through the list of pending results and cancel all whose events were
- * destined for this thread. While this is in progress we block any
- * other access to the list of pending results.
+ * destined for this thread. While this is in progress we block any other
+ * access to the list of pending results.
*/
Tcl_MutexLock(&rcForwardMutex);
@@ -2707,7 +2718,10 @@ DeleteThreadReflectedChannelMap(
evPtr = resultPtr->evPtr;
- /* Basic crash safety until this routine can get revised [3411310] */
+ /*
+ * Basic crash safety until this routine can get revised [3411310]
+ */
+
if (evPtr == NULL ) {
continue;
}
@@ -2761,8 +2775,8 @@ ForwardOpToHandlerThread(
const void *param) /* Arguments */
{
/*
- * Core of the communication from OWNER to HANDLER thread.
- * The receiver is ForwardProc() below.
+ * Core of the communication from OWNER to HANDLER thread. The receiver is
+ * ForwardProc() below.
*/
Tcl_ThreadId dst = rcPtr->thread;
@@ -2812,7 +2826,10 @@ ForwardOpToHandlerThread(
*/
TclSpliceIn(resultPtr, forwardList);
- /* Do not unlock here. That is done by the ConditionWait */
+
+ /*
+ * Do not unlock here. That is done by the ConditionWait.
+ */
/*
* Ensure cleanup of the event if the origin thread exits while this event
@@ -2888,7 +2905,7 @@ ForwardProc(
* Notes regarding access to the referenced data.
*
* In principle the data belongs to the originating thread (see
- * evPtr->src), however this thread is currently blocked at (*), i.e.
+ * evPtr->src), however this thread is currently blocked at (*), i.e.,
* quiescent. Because of this we can treat the data as belonging to us,
* without fear of race conditions. I.e. we can read and write as we like.
*
diff --git a/generic/tclIOUtil.c b/generic/tclIOUtil.c
index de5d62d..5f79e6e 100644
--- a/generic/tclIOUtil.c
+++ b/generic/tclIOUtil.c
@@ -611,6 +611,7 @@ FsRecacheFilesystemList(void)
while (toFree) {
FilesystemRecord *next = toFree->nextPtr;
+
toFree->fsPtr = NULL;
ckfree(toFree);
toFree = next;
@@ -672,7 +673,6 @@ TclFSEpoch(void)
return tsdPtr->filesystemEpoch;
}
-
/*
* If non-NULL, clientData is owned by us and must be freed later.
@@ -784,7 +784,9 @@ TclFinalizeFilesystem(void)
while (fsRecPtr != NULL) {
FilesystemRecord *tmpFsRecPtr = fsRecPtr->nextPtr;
- /* The native filesystem is static, so we don't free it. */
+ /*
+ * The native filesystem is static, so we don't free it.
+ */
if (fsRecPtr != &nativeFilesystemRecord) {
ckfree(fsRecPtr);
@@ -947,7 +949,7 @@ Tcl_FSRegister(
int
Tcl_FSUnregister(
- const Tcl_Filesystem *fsPtr) /* The filesystem record to remove. */
+ const Tcl_Filesystem *fsPtr)/* The filesystem record to remove. */
{
int retVal = TCL_ERROR;
FilesystemRecord *fsRecPtr;
@@ -1233,7 +1235,7 @@ FsAddMountsToGlobResult(
len--;
}
- len++; /* account for '/' in the mElt [Bug 1602539] */
+ len++; /* account for '/' in the mElt [Bug 1602539] */
mElt = TclNewFSPathObj(pathPtr, mount + len, mlen - len);
Tcl_ListObjAppendElement(NULL, resultPtr, mElt);
}
@@ -1403,7 +1405,7 @@ TclFSNormalizeToUniquePath(
* Call each of the "normalise path" functions in succession. This is a
* special case, in which if we have a native filesystem handler, we call
* it first. This is because the root of Tcl's filesystem is always a
- * native filesystem (i.e. '/' on unix is native).
+ * native filesystem (i.e., '/' on unix is native).
*/
firstFsRecPtr = FsGetFirstFilesystem();
@@ -1525,7 +1527,7 @@ TclGetOpenModeEx(
#define RW_MODES (O_RDONLY|O_WRONLY|O_RDWR)
/*
- * Check for the simpler fopen-like access modes (e.g. "r"). They are
+ * Check for the simpler fopen-like access modes (e.g., "r"). They are
* distinguished from the POSIX access modes by the presence of a
* lower-case first letter.
*/
@@ -2671,6 +2673,7 @@ Tcl_FSGetCwd(
fsRecPtr = fsRecPtr->nextPtr) {
ClientData retCd;
TclFSGetCwdProc2 *proc2;
+
if (fsRecPtr->fsPtr->getCwdProc == NULL) {
continue;
}
@@ -3143,8 +3146,8 @@ Tcl_FSLoadFile(
* Workaround for issue with modern HPUX which do allow the unlink (no ETXTBSY
* error) yet somehow trash some internal data structures which prevents the
* second and further shared libraries from getting properly loaded. Only the
- * first is ok. We try to get around the issue by not unlinking,
- * i.e. emulating the behaviour of the older HPUX which denied removal.
+ * first is ok. We try to get around the issue by not unlinking, i.e.,
+ * emulating the behaviour of the older HPUX which denied removal.
*
* Doing the unlink is also an issue within docker containers, whose AUFS
* bungles this as well, see
@@ -3162,28 +3165,30 @@ Tcl_FSLoadFile(
*/
int
-TclSkipUnlink (Tcl_Obj* shlibFile)
+TclSkipUnlink(
+ Tcl_Obj *shlibFile)
{
- /* Order of testing:
+ /*
+ * Order of testing:
* 1. On hpux we generally want to skip unlink in general
*
* Outside of hpux then:
- * 2. For a general user request (TCL_TEMPLOAD_NO_UNLINK present, non-empty, => int)
+ * 2. For a general user request (TCL_TEMPLOAD_NO_UNLINK present,
+ * non-empty, => int)
* 3. For general AUFS environment (statfs, if available).
*
* Ad 2: This variable can disable/override the AUFS detection, i.e. for
- * testing if a newer AUFS does not have the bug any more.
+ * testing if a newer AUFS does not have the bug any more.
*
- * Ad 3: This is conditionally compiled in. Condition currently must be set manually.
- * This part needs proper tests in the configure(.in).
+ * Ad 3: This is conditionally compiled in. Condition currently must be
+ * set manually. This part needs proper tests in the configure(.in).
*/
#ifdef hpux
return 1;
#else
- char* skipstr;
+ char *skipstr = getenv("TCL_TEMPLOAD_NO_UNLINK");
- skipstr = getenv ("TCL_TEMPLOAD_NO_UNLINK");
if (skipstr && (skipstr[0] != '\0')) {
return atoi(skipstr);
}
@@ -3192,7 +3197,8 @@ TclSkipUnlink (Tcl_Obj* shlibFile)
#ifndef NO_FSTATFS
{
struct statfs fs;
- /* Have fstatfs. May not have the AUFS super magic ... Indeed our build
+ /*
+ * Have fstatfs. May not have the AUFS super magic ... Indeed our build
* box is too old to have it directly in the headers. Define taken from
* http://mooon.googlecode.com/svn/trunk/linux_include/linux/aufs_type.h
* http://aufs.sourceforge.net/
@@ -3209,8 +3215,10 @@ TclSkipUnlink (Tcl_Obj* shlibFile)
#endif /* ... NO_FSTATFS */
#endif /* ... TCL_TEMPLOAD_NO_UNLINK */
- /* Fallback: !hpux, no EV override, no AUFS (detection, nor detected):
- * Don't skip */
+ /*
+ * Fallback: !hpux, no EV override, no AUFS (detection, nor detected):
+ * Don't skip
+ */
return 0;
#endif /* hpux */
}
@@ -3415,9 +3423,8 @@ Tcl_LoadFile(
* avoids any worries about leaving the copy laying around on exit.
*/
- if (
- !TclSkipUnlink (copyToPtr) &&
- (Tcl_FSDeleteFile(copyToPtr) == TCL_OK)) {
+ if (!TclSkipUnlink(copyToPtr) &&
+ (Tcl_FSDeleteFile(copyToPtr) == TCL_OK)) {
Tcl_DecrRefCount(copyToPtr);
/*
diff --git a/generic/tclTimer.c b/generic/tclTimer.c
index 6d3938b..3467305 100644
--- a/generic/tclTimer.c
+++ b/generic/tclTimer.c
@@ -1053,11 +1053,17 @@ AfterDelay(
if (diff > TCL_TIME_MAXIMUM_SLICE) {
diff = TCL_TIME_MAXIMUM_SLICE;
}
- if (diff == 0 && TCL_TIME_BEFORE(now, endTime)) diff = 1;
+ if (diff == 0 && TCL_TIME_BEFORE(now, endTime)) {
+ diff = 1;
+ }
if (diff > 0) {
Tcl_Sleep((long) diff);
- if (diff < SLEEP_OFFLOAD_GETTIMEOFDAY) break;
- } else break;
+ if (diff < SLEEP_OFFLOAD_GETTIMEOFDAY) {
+ break;
+ }
+ } else {
+ break;
+ }
} else {
diff = TCL_TIME_DIFF_MS(iPtr->limit.time, now);
#ifndef TCL_WIDE_INT_IS_LONG
diff --git a/unix/tclUnixSock.c b/unix/tclUnixSock.c
index 0ae500b..b404080 100644
--- a/unix/tclUnixSock.c
+++ b/unix/tclUnixSock.c
@@ -19,6 +19,7 @@
#define SET_BITS(var, bits) ((var) |= (bits))
#define CLEAR_BITS(var, bits) ((var) &= ~(bits))
+#define GOT_BITS(var, bits) (((var) & (bits)) != 0)
/* "sock" + a pointer in hex + \0 */
#define SOCK_CHAN_LENGTH (4 + sizeof(void *) * 2 + 1)
@@ -99,9 +100,9 @@ struct TcpState {
* structure.
*/
-#define TCP_ASYNC_TEST_MODE (1<<0) /* Async testing activated
- * Do not automatically continue connection
- * process */
+#define TCP_ASYNC_TEST_MODE (1<<0) /* Async testing activated. Do not
+ * automatically continue connection
+ * process. */
/*
* The following defines the maximum length of the listen queue. This is the
@@ -389,7 +390,7 @@ TcpBlockModeProc(
} else {
SET_BITS(statePtr->flags, TCP_NONBLOCKING);
}
- if (statePtr->flags & TCP_ASYNC_CONNECT) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
statePtr->cachedBlocking = mode;
return 0;
}
@@ -442,7 +443,7 @@ WaitForConnect(
* demanded, return the error ENOTCONN
*/
- if (errorCodePtr != NULL && (statePtr->flags & TCP_ASYNC_FAILED)) {
+ if (errorCodePtr != NULL && GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
*errorCodePtr = ENOTCONN;
return -1;
}
@@ -451,24 +452,25 @@ WaitForConnect(
* Check if an async connect is running. If not return ok
*/
- if (!(statePtr->flags & TCP_ASYNC_PENDING)) {
+ if (!GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
return 0;
}
/*
- * In socket test mode do not continue with the connect
+ * In socket test mode do not continue with the connect.
* Exceptions are:
* - Call by recv/send and blocking socket
- * (errorCodePtr != NULL && ! flags & TCP_NONBLOCKING)
+ * (errorCodePtr != NULL && !GOT_BITS(flags, TCP_NONBLOCKING))
*/
- if ( (statePtr->testFlags & TCP_ASYNC_TEST_MODE)
- && ! (errorCodePtr != NULL && ! (statePtr->flags & TCP_NONBLOCKING))) {
+ if (GOT_BITS(statePtr->testFlags, TCP_ASYNC_TEST_MODE)
+ && !(errorCodePtr != NULL
+ && !GOT_BITS(statePtr->flags, TCP_NONBLOCKING))) {
*errorCodePtr = EWOULDBLOCK;
return -1;
}
- if (errorCodePtr == NULL || (statePtr->flags & TCP_NONBLOCKING)) {
+ if (errorCodePtr == NULL || GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
timeout = 0;
} else {
timeout = -1;
@@ -483,10 +485,10 @@ WaitForConnect(
* Do this only once in the nonblocking case and repeat it until the
* socket is final when blocking.
*/
- } while (timeout == -1 && statePtr->flags & TCP_ASYNC_CONNECT);
+ } while (timeout == -1 && GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT));
if (errorCodePtr != NULL) {
- if (statePtr->flags & TCP_ASYNC_PENDING) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
*errorCodePtr = EAGAIN;
return -1;
} else if (statePtr->connectError != 0) {
@@ -832,7 +834,7 @@ TcpGetOptionProc(
(strncmp(optionName, "-error", len) == 0)) {
socklen_t optlen = sizeof(int);
- if (statePtr->flags & TCP_ASYNC_CONNECT) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
/*
* Suppress errors as long as we are not done.
*/
@@ -856,9 +858,8 @@ TcpGetOptionProc(
if ((len > 1) && (optionName[1] == 'c') &&
(strncmp(optionName, "-connecting", len) == 0)) {
-
Tcl_DStringAppend(dsPtr,
- (statePtr->flags & TCP_ASYNC_CONNECT) ? "1" : "0", -1);
+ GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT) ? "1" : "0", -1);
return TCL_OK;
}
@@ -867,7 +868,7 @@ TcpGetOptionProc(
address peername;
socklen_t size = sizeof(peername);
- if (statePtr->flags & TCP_ASYNC_CONNECT) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
/*
* In async connect output an empty string
*/
@@ -922,7 +923,7 @@ TcpGetOptionProc(
Tcl_DStringAppendElement(dsPtr, "-sockname");
Tcl_DStringStartSublist(dsPtr);
}
- if (statePtr->flags & TCP_ASYNC_CONNECT) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
/*
* In async connect output an empty string
*/
@@ -1024,7 +1025,7 @@ TcpWatchProc(
return;
}
- if (statePtr->flags & TCP_ASYNC_PENDING) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
/*
* Async sockets use a FileHandler internally while connecting, so we
* need to cache this request until the connection has succeeded.
@@ -1149,9 +1150,9 @@ TcpConnect(
TcpState *statePtr)
{
socklen_t optlen;
- int async_callback = statePtr->flags & TCP_ASYNC_PENDING;
+ int async_callback = GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING);
int ret = -1, error = EHOSTUNREACH;
- int async = statePtr->flags & TCP_ASYNC_CONNECT;
+ int async = GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
if (async_callback) {
goto reenter;
@@ -1159,7 +1160,6 @@ TcpConnect(
for (statePtr->addr = statePtr->addrlist; statePtr->addr != NULL;
statePtr->addr = statePtr->addr->ai_next) {
-
for (statePtr->myaddr = statePtr->myaddrlist;
statePtr->myaddr != NULL;
statePtr->myaddr = statePtr->myaddr->ai_next) {
@@ -1580,13 +1580,13 @@ Tcl_OpenTcpServerEx(
* Set up to reuse server addresses and/or ports if requested.
*/
- if (flags & TCL_TCPSERVER_REUSEADDR) {
+ if (GOT_BITS(flags, TCL_TCPSERVER_REUSEADDR)) {
optvalue = 1;
(void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(char *) &optvalue, sizeof(optvalue));
}
- if (flags & TCL_TCPSERVER_REUSEPORT) {
+ if (GOT_BITS(flags, TCL_TCPSERVER_REUSEPORT)) {
#ifndef SO_REUSEPORT
/*
* If the platform doesn't support the SO_REUSEPORT flag we can't
diff --git a/win/tclWinSock.c b/win/tclWinSock.c
index a5d98ae..8e0f7d0 100644
--- a/win/tclWinSock.c
+++ b/win/tclWinSock.c
@@ -69,6 +69,7 @@
#define SET_BITS(var, bits) ((var) |= (bits))
#define CLEAR_BITS(var, bits) ((var) &= ~(bits))
+#define GOT_BITS(var, bits) (((var) & (bits)) != 0)
/* "sock" + a pointer in hex + \0 */
#define SOCK_CHAN_LENGTH (4 + sizeof(void *) * 2 + 1)
@@ -190,8 +191,8 @@ struct TcpState {
* structure.
*/
-#define TCP_ASYNC_TEST_MODE (1<<0) /* Async testing activated
- * Do not automatically continue connection
+#define TCP_ASYNC_TEST_MODE (1<<0) /* Async testing activated. Do not
+ * automatically continue connection
* process */
/*
@@ -303,6 +304,15 @@ static const Tcl_ChannelType tcpChannelType = {
static TclInitProcessGlobalValueProc InitializeHostName;
static ProcessGlobalValue hostName =
{0, 0, NULL, NULL, InitializeHostName, NULL, NULL};
+
+/*
+ * Simple wrapper round the SendMessage syscall.
+ */
+
+#define SendSelectMessage(tsdPtr, message, payload) \
+ SendMessage((tsdPtr)->hwnd, SOCKET_SELECT, \
+ (WPARAM) (message), (LPARAM) (payload))
+
/*
* Address print debug functions
@@ -596,7 +606,7 @@ WaitForConnect(
* demanded, return the error ENOTCONN.
*/
- if (errorCodePtr != NULL && (statePtr->flags & TCP_ASYNC_FAILED)) {
+ if (errorCodePtr != NULL && GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
*errorCodePtr = ENOTCONN;
return -1;
}
@@ -605,7 +615,7 @@ WaitForConnect(
* Check if an async connect is running. If not return ok
*/
- if (!(statePtr->flags & TCP_ASYNC_CONNECT)) {
+ if (!GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
return 0;
}
@@ -613,12 +623,13 @@ WaitForConnect(
* In socket test mode do not continue with the connect
* Exceptions are:
* - Call by recv/send and blocking socket
- * (errorCodePtr != NULL && ! flags & TCP_NONBLOCKING)
+ * (errorCodePtr != NULL && !GOT_BITS(flags, TCP_NONBLOCKING))
* - Call by the event queue (errorCodePtr == NULL)
*/
- if ( (statePtr->testFlags & TCP_ASYNC_TEST_MODE)
- && errorCodePtr != NULL && (statePtr->flags & TCP_NONBLOCKING)) {
+ if (GOT_BITS(statePtr->testFlags, TCP_ASYNC_TEST_MODE)
+ && errorCodePtr != NULL
+ && GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
*errorCodePtr = EWOULDBLOCK;
return -1;
}
@@ -645,7 +656,7 @@ WaitForConnect(
* Check for connect event.
*/
- if (statePtr->readyEvents & FD_CONNECT) {
+ if (GOT_BITS(statePtr->readyEvents, FD_CONNECT)) {
/*
* Consume the connect event.
*/
@@ -658,7 +669,7 @@ WaitForConnect(
*/
if (errorCodePtr != NULL &&
- !(statePtr->flags & TCP_NONBLOCKING)) {
+ !GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
}
@@ -691,7 +702,7 @@ WaitForConnect(
* foreground blocking operation)
*/
- if (statePtr->flags & TCP_ASYNC_PENDING) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
if (errorCodePtr != NULL) {
*errorCodePtr = EWOULDBLOCK;
}
@@ -731,7 +742,7 @@ WaitForConnect(
* directly the error EWOULDBLOCK.
*/
- if (statePtr->flags & TCP_NONBLOCKING) {
+ if (GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
*errorCodePtr = EWOULDBLOCK;
return -1;
}
@@ -795,7 +806,7 @@ TcpInputProc(
* socket stack after the first time EOF is detected.
*/
- if (statePtr->flags & SOCKET_EOF) {
+ if (GOT_BITS(statePtr->flags, SOCKET_EOF)) {
return 0;
}
@@ -818,8 +829,8 @@ TcpInputProc(
*/
while (1) {
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
- (WPARAM) UNSELECT, (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, UNSELECT, statePtr);
+
/*
* Single fd operation: this proc is only called for a connected
* socket.
@@ -844,7 +855,7 @@ TcpInputProc(
* error and report an EOF.
*/
- if (statePtr->readyEvents & FD_CLOSE) {
+ if (GOT_BITS(statePtr->readyEvents, FD_CLOSE)) {
SET_BITS(statePtr->flags, SOCKET_EOF);
bytesRead = 0;
break;
@@ -867,7 +878,8 @@ TcpInputProc(
* Check for error condition or underflow in non-blocking case.
*/
- if ((statePtr->flags & TCP_NONBLOCKING) || (error != WSAEWOULDBLOCK)) {
+ if (GOT_BITS(statePtr->flags, TCP_NONBLOCKING)
+ || (error != WSAEWOULDBLOCK)) {
TclWinConvertError(error);
*errorCodePtr = Tcl_GetErrno();
bytesRead = -1;
@@ -885,7 +897,7 @@ TcpInputProc(
}
}
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM)SELECT, (LPARAM)statePtr);
+ SendSelectMessage(tsdPtr, SELECT, statePtr);
return bytesRead;
}
@@ -943,8 +955,7 @@ TcpOutputProc(
}
while (1) {
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
- (WPARAM) UNSELECT, (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, UNSELECT, statePtr);
/*
* Single fd operation: this proc is only called for a connected
@@ -959,8 +970,9 @@ TcpOutputProc(
* until the condition changes.
*/
- if (statePtr->watchEvents & FD_WRITE) {
+ if (GOT_BITS(statePtr->watchEvents, FD_WRITE)) {
Tcl_Time blockTime = { 0, 0 };
+
Tcl_SetMaxBlockTime(&blockTime);
}
break;
@@ -976,7 +988,7 @@ TcpOutputProc(
error = WSAGetLastError();
if (error == WSAEWOULDBLOCK) {
CLEAR_BITS(statePtr->readyEvents, FD_WRITE);
- if (statePtr->flags & TCP_NONBLOCKING) {
+ if (GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
*errorCodePtr = EWOULDBLOCK;
written = -1;
break;
@@ -999,8 +1011,7 @@ TcpOutputProc(
}
}
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM)SELECT,
- (LPARAM)statePtr);
+ SendSelectMessage(tsdPtr, SELECT, statePtr);
return written;
}
@@ -1317,7 +1328,7 @@ TcpGetOptionProc(
* below.
*/
- if (! (statePtr->testFlags & TCP_ASYNC_TEST_MODE) ) {
+ if (!GOT_BITS(statePtr->testFlags, TCP_ASYNC_TEST_MODE)) {
WaitForConnect(statePtr, NULL);
}
@@ -1332,8 +1343,8 @@ TcpGetOptionProc(
* Do not return any errors if async connect is running.
*/
- if (!(statePtr->flags & TCP_ASYNC_PENDING)) {
- if (statePtr->flags & TCP_ASYNC_FAILED) {
+ if (!GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
/*
* In case of a failed async connect, eventually report the
* connect error only once. Do not report the system error,
@@ -1388,7 +1399,7 @@ TcpGetOptionProc(
if ((len > 1) && (optionName[1] == 'c') &&
(strncmp(optionName, "-connecting", len) == 0)) {
Tcl_DStringAppend(dsPtr,
- (statePtr->flags & TCP_ASYNC_PENDING)
+ GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)
? "1" : "0", -1);
return TCL_OK;
}
@@ -1403,7 +1414,7 @@ TcpGetOptionProc(
address peername;
socklen_t size = sizeof(peername);
- if (statePtr->flags & TCP_ASYNC_PENDING) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
/*
* In async connect output an empty string
*/
@@ -1468,7 +1479,7 @@ TcpGetOptionProc(
Tcl_DStringAppendElement(dsPtr, "-sockname");
Tcl_DStringStartSublist(dsPtr);
}
- if (statePtr->flags & TCP_ASYNC_PENDING) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
/*
* In async connect output an empty string
*/
@@ -1617,10 +1628,10 @@ TcpWatchProc(
if (!statePtr->acceptProc) {
statePtr->watchEvents = 0;
- if (mask & TCL_READABLE) {
+ if (GOT_BITS(mask, TCL_READABLE)) {
SET_BITS(statePtr->watchEvents, FD_READ | FD_CLOSE);
}
- if (mask & TCL_WRITABLE) {
+ if (GOT_BITS(mask, TCL_WRITABLE)) {
SET_BITS(statePtr->watchEvents, FD_WRITE | FD_CLOSE);
}
@@ -1712,11 +1723,11 @@ TcpConnect(
TcpState *statePtr)
{
DWORD error;
- int async_connect = statePtr->flags & TCP_ASYNC_CONNECT;
+ int async_connect = GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
/* We are started with async connect and the
* connect notification was not yet
* received. */
- int async_callback = statePtr->flags & TCP_ASYNC_PENDING;
+ int async_callback = GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING);
/* We were called by the event procedure and
* continue our loop. */
ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey);
@@ -1860,8 +1871,7 @@ TcpConnect(
* Activate accept notification.
*/
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT,
- (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, SELECT, statePtr);
}
/*
@@ -1957,8 +1967,7 @@ TcpConnect(
* automatically places the socket into non-blocking mode.
*/
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT,
- (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, SELECT, statePtr);
} else {
/*
* Connect failed
@@ -2155,8 +2164,7 @@ Tcl_MakeTcpClientChannel(
*/
statePtr->selectEvents = FD_READ | FD_CLOSE | FD_WRITE;
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM)SELECT,
- (LPARAM)statePtr);
+ SendSelectMessage(tsdPtr, SELECT, statePtr);
sprintf(channelName, SOCK_TEMPLATE, statePtr);
statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
@@ -2270,7 +2278,7 @@ Tcl_OpenTcpServerEx(
* unix systems.
*/
- if (flags & TCL_TCPSERVER_REUSEPORT) {
+ if (GOT_BITS(flags, TCL_TCPSERVER_REUSEPORT)) {
optvalue = 1;
(void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(char *) &optvalue, sizeof(optvalue));
@@ -2352,8 +2360,7 @@ Tcl_OpenTcpServerEx(
*/
ioctlsocket(sock, (long) FIONBIO, &flag);
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT,
- (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, SELECT, statePtr);
if (Tcl_SetChannelOption(interp, statePtr->channel, "-eofchar", "")
== TCL_ERROR) {
Tcl_Close(NULL, statePtr->channel);
@@ -2422,8 +2429,7 @@ TcpAccept(
*/
newInfoPtr->selectEvents = (FD_READ | FD_WRITE | FD_CLOSE);
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT,
- (LPARAM) newInfoPtr);
+ SendSelectMessage(tsdPtr, SELECT, newInfoPtr);
sprintf(channelName, SOCK_TEMPLATE, newInfoPtr);
newInfoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
@@ -2654,7 +2660,7 @@ SocketSetupProc(
Tcl_Time blockTime = { 0, 0 };
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
- if (!(flags & TCL_FILE_EVENTS)) {
+ if (!GET_BITS(flags, TCL_FILE_EVENTS)) {
return;
}
@@ -2664,9 +2670,8 @@ SocketSetupProc(
WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
for (statePtr = tsdPtr->socketList; statePtr != NULL;
statePtr = statePtr->nextPtr) {
- if (statePtr->readyEvents &
- (statePtr->watchEvents | FD_CONNECT | FD_ACCEPT)
- ) {
+ if (GOT_BITS(statePtr->readyEvents,
+ statePtr->watchEvents | FD_CONNECT | FD_ACCEPT)) {
Tcl_SetMaxBlockTime(&blockTime);
break;
}
@@ -2700,7 +2705,7 @@ SocketCheckProc(
SocketEvent *evPtr;
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
- if (!(flags & TCL_FILE_EVENTS)) {
+ if (!GOT_BITS(flags, TCL_FILE_EVENTS)) {
return;
}
@@ -2713,9 +2718,9 @@ SocketCheckProc(
WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
for (statePtr = tsdPtr->socketList; statePtr != NULL;
statePtr = statePtr->nextPtr) {
- if ((statePtr->readyEvents &
- (statePtr->watchEvents | FD_CONNECT | FD_ACCEPT))
- && !(statePtr->flags & SOCKET_PENDING)) {
+ if (GOT_BITS(statePtr->readyEvents,
+ statePtr->watchEvents | FD_CONNECT | FD_ACCEPT)
+ && !GOT_BITS(statePtr->flags, SOCKET_PENDING)) {
SET_BITS(statePtr->flags, SOCKET_PENDING);
evPtr = ckalloc(sizeof(SocketEvent));
evPtr->header.proc = SocketEventProc;
@@ -2762,7 +2767,7 @@ SocketEventProc(
address addr;
int len;
- if (!(flags & TCL_FILE_EVENTS)) {
+ if (!GOT_BITS(flags, TCL_FILE_EVENTS)) {
return 0;
}
@@ -2797,8 +2802,8 @@ SocketEventProc(
* Continue async connect if pending and ready
*/
- if (statePtr->readyEvents & FD_CONNECT) {
- if (statePtr->flags & TCP_ASYNC_PENDING) {
+ if (GOT_BITS(statePtr->readyEvents, FD_CONNECT)) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
/*
* Do one step and save eventual connect error
*/
@@ -2820,7 +2825,7 @@ SocketEventProc(
* Handle connection requests directly.
*/
- if (statePtr->readyEvents & FD_ACCEPT) {
+ if (GOT_BITS(statePtr->readyEvents, FD_ACCEPT)) {
for (fds = statePtr->sockets; fds != NULL; fds = fds->next) {
/*
* Accept the incoming connection request.
@@ -2895,7 +2900,7 @@ SocketEventProc(
events = statePtr->readyEvents & statePtr->watchEvents;
- if (events & FD_CLOSE) {
+ if (GOT_BITS(events, FD_CLOSE)) {
/*
* If the socket was closed and the channel is still interested in
* read events, then we need to ensure that we keep polling for this
@@ -2910,15 +2915,13 @@ SocketEventProc(
Tcl_SetMaxBlockTime(&blockTime);
SET_BITS(mask, TCL_READABLE | TCL_WRITABLE);
- } else if (events & FD_READ) {
-
+ } else if (GOT_BITS(events, FD_READ)) {
/*
* Throw the readable event if an async connect failed.
*/
- if (statePtr->flags & TCP_ASYNC_FAILED) {
+ if (GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
SET_BITS(mask, TCL_READABLE);
-
} else {
fd_set readFds;
struct timeval timeout;
@@ -2931,8 +2934,7 @@ SocketEventProc(
* async select handler and keep waiting.
*/
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
- (WPARAM) UNSELECT, (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, UNSELECT, statePtr);
FD_ZERO(&readFds);
FD_SET(statePtr->sockets->fd, &readFds);
@@ -2943,8 +2945,7 @@ SocketEventProc(
SET_BITS(mask, TCL_READABLE);
} else {
CLEAR_BITS(statePtr->readyEvents, FD_READ);
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
- (WPARAM) SELECT, (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, SELECT, statePtr);
}
}
}
@@ -2953,7 +2954,7 @@ SocketEventProc(
* writable event
*/
- if (events & FD_WRITE) {
+ if (GOT_BITS(events, FD_WRITE)) {
SET_BITS(mask, TCL_WRITABLE);
}
@@ -3095,10 +3096,8 @@ WaitForSocketEvent(
* Reset WSAAsyncSelect so we have a fresh set of events pending.
*/
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) UNSELECT,
- (LPARAM) statePtr);
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT,
- (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, UNSELECT, statePtr);
+ SendSelectMessage(tsdPtr, SELECT, statePtr);
while (1) {
int event_found;
@@ -3113,7 +3112,7 @@ WaitForSocketEvent(
* Check if event occured.
*/
- event_found = (statePtr->readyEvents & events);
+ event_found = GOT_BITS(statePtr->readyEvents, events);
/*
* Free list lock.
@@ -3314,14 +3313,14 @@ SocketProc(
* the count if the current event is an FD_ACCEPT.
*/
- if (event & FD_CLOSE) {
+ if (GOT_BITS(event, FD_CLOSE)) {
statePtr->acceptEventCount = 0;
CLEAR_BITS(statePtr->readyEvents, FD_WRITE | FD_ACCEPT);
- } else if (event & FD_ACCEPT) {
+ } else if (GOT_BITS(event, FD_ACCEPT)) {
statePtr->acceptEventCount++;
}
- if (event & FD_CONNECT) {
+ if (GOT_BITS(event, FD_CONNECT)) {
/*
* Remember any error that occurred so we can report
* connection failures.
@@ -3552,8 +3551,7 @@ TcpThreadActionProc(
* thread.
*/
- SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
- (WPARAM) notifyCmd, (LPARAM) statePtr);
+ SendSelectMessage(tsdPtr, notifyCmd, statePtr);
}
/*