Debian Codegraph @

nx-X11/lib/src/XlibInt.c

raw
1 /**************************************************************************/
2 /* */
3 /* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com) */
4 /* Copyright (c) 2008-2017 Oleksandr Shneyder <[email protected]> */
5 /* Copyright (c) 2011-2022 Mike Gabriel <[email protected]>*/
6 /* Copyright (c) 2014-2019 Mihai Moldovan <[email protected]> */
7 /* Copyright (c) 2014-2022 Ulrich Sibiller <[email protected]> */
8 /* Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com) */
9 /* */
10 /* nx-X11, NX protocol compression and NX extensions to this software */
11 /* are copyright of the aforementioned persons and companies. */
12 /* */
13 /* Redistribution and use of the present software is allowed according */
14 /* to terms specified in the file LICENSE which comes in the source */
15 /* distribution. */
16 /* */
17 /* All rights reserved. */
18 /* */
19 /* NOTE: This software has received contributions from various other */
20 /* contributors, only the core maintainers and supporters are listed as */
21 /* copyright holders. Please contact us, if you feel you should be listed */
22 /* as copyright holder, as well. */
23 /* */
24 /**************************************************************************/
25
26 /*
27
28 Copyright 1985, 1986, 1987, 1998 The Open Group
29
30 Permission to use, copy, modify, distribute, and sell this software and its
31 documentation for any purpose is hereby granted without fee, provided that
32 the above copyright notice appear in all copies and that both that
33 copyright notice and this permission notice appear in supporting
34 documentation.
35
36 The above copyright notice and this permission notice shall be included
37 in all copies or substantial portions of the Software.
38
39 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
40 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
41 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
42 IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
43 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
44 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
45 OTHER DEALINGS IN THE SOFTWARE.
46
47 Except as contained in this notice, the name of The Open Group shall
48 not be used in advertising or otherwise to promote the sale, use or
49 other dealings in this Software without prior written authorization
50 from The Open Group.
51
52 */
53
54 /*
55 * XlibInt.c - Internal support routines for the C subroutine
56 * interface library (Xlib) to the X Window System Protocol V11.0.
57 */
58
59 #ifdef WIN32
60 #define _XLIBINT_
61 #endif
62 #ifdef HAVE_CONFIG_H
63 #include <config.h>
64 #endif
65 #include "Xlibint.h"
66 #include "Xprivate.h"
67 #include "reallocarray.h"
68 #include <nx-X11/Xpoll.h>
69 #if !USE_XCB
70 #include <nx-X11/Xtrans/Xtrans.h>
71 #include <nx-X11/extensions/xcmiscstr.h>
72 #endif /* !USE_XCB */
73 #include <assert.h>
74 #include <stdio.h>
75 #ifdef WIN32
76 #include <direct.h>
77 #endif
78
79 /* Needed for FIONREAD on Solaris */
80 #ifdef HAVE_SYS_FILIO_H
81 #include <sys/filio.h>
82 #endif
83
84 /* Needed for FIONREAD on Cygwin */
85 #ifdef HAVE_SYS_SOCKET_H
86 #include <sys/socket.h>
87 #endif
88
89 /* Needed for ioctl() on Solaris */
90 #ifdef HAVE_UNISTD_H
91 #include <unistd.h>
92 #endif
93
94 #ifdef XTHREADS
95 #include "locking.h"
96
97 #ifdef HAVE_SYS_IOCTL_H
98 #include <sys/ioctl.h>
99 #endif
100
101 /* these pointers get initialized by XInitThreads */
102 LockInfoPtr _Xglobal_lock = NULL;
103 void (*_XCreateMutex_fn)(LockInfoPtr) = NULL;
104 /* struct _XCVList *(*_XCreateCVL_fn)() = NULL; */
105 void (*_XFreeMutex_fn)(LockInfoPtr) = NULL;
106 void (*_XLockMutex_fn)(
107 LockInfoPtr /* lock */
108 #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE)
109 , char * /* file */
110 , int /* line */
111 #endif
112 ) = NULL;
113 void (*_XUnlockMutex_fn)(
114 LockInfoPtr /* lock */
115 #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE)
116 , char * /* file */
117 , int /* line */
118 #endif
119 ) = NULL;
120 xthread_t (*_Xthread_self_fn)(void) = NULL;
121
122 #define XThread_Self() ((*_Xthread_self_fn)())
123
124 #if !USE_XCB
125 #define UnlockNextReplyReader(d) if ((d)->lock) \
126 (*(d)->lock->pop_reader)((d),&(d)->lock->reply_awaiters,&(d)->lock->reply_awaiters_tail)
127
128 #define QueueReplyReaderLock(d) ((d)->lock ? \
129 (*(d)->lock->push_reader)(d,&(d)->lock->reply_awaiters_tail) : NULL)
130 #define QueueEventReaderLock(d) ((d)->lock ? \
131 (*(d)->lock->push_reader)(d,&(d)->lock->event_awaiters_tail) : NULL)
132 #endif /* !USE_XCB */
133
134 #else /* XTHREADS else */
135
136 #if !USE_XCB
137 #define UnlockNextReplyReader(d)
138 #define UnlockNextEventReader(d)
139 #endif /* !USE_XCB */
140
141 #endif /* XTHREADS else */
142
143 #ifdef NX_TRANS_SOCKET
144
145 #include <nx/NX.h>
146 #include <nx/NXvars.h>
147
148 static struct timeval retry;
149
150 /*
151 * From Xtranssock.c. Presently the congestion state is reported by
152 * the proxy to the application, by invoking the callback
153 * directly. The function will be possibly used in the future, to be
154 * able to track the bandwidth usage even when the NX transport is not
155 * running. Note that in this sample implementation the congestion
156 * state is checked very often and can be surely optimized.
157 */
158
159 #ifdef NX_TRANS_CHANGE
160 extern int _X11TransSocketCongestionChange(XtransConnInfo, int *);
161 #endif
162
163 #else
164 /*
165 * unifdef to simplify subsequent checks. IF NX_TRANS_CHANGE is set it
166 * is safe to assume NX_TRANS_SOCKET is also set. Same for NX_TRANS_DEBUG.
167 */
168 # ifdef NX_TRANS_CHANGE
169 # undef NX_TRANS_CHANGE
170 # endif
171 # ifdef NX_TRANS_DEBUG
172 # undef NX_TRANS_DEBUG
173 # endif
174 #endif /* #ifdef NX_TRANS_SOCKET */
175
176 /* check for both EAGAIN and EWOULDBLOCK, because some supposedly POSIX
177 * systems are broken and return EWOULDBLOCK when they should return EAGAIN
178 */
179 #ifdef WIN32
180 #define ETEST() (WSAGetLastError() == WSAEWOULDBLOCK)
181 #else
182 #ifdef __CYGWIN__ /* Cygwin uses ENOBUFS to signal socket is full */
183 #define ETEST() (errno == EAGAIN || errno == EWOULDBLOCK || errno == ENOBUFS)
184 #else
185 #if defined(EAGAIN) && defined(EWOULDBLOCK)
186 #define ETEST() (errno == EAGAIN || errno == EWOULDBLOCK)
187 #else
188 #ifdef EAGAIN
189 #define ETEST() (errno == EAGAIN)
190 #else
191 #define ETEST() (errno == EWOULDBLOCK)
192 #endif /* EAGAIN */
193 #endif /* EAGAIN && EWOULDBLOCK */
194 #endif /* __CYGWIN__ */
195 #endif /* WIN32 */
196
197 #ifdef WIN32
198 #define ECHECK(err) (WSAGetLastError() == err)
199 #define ESET(val) WSASetLastError(val)
200 #else
201 #define ECHECK(err) (errno == err)
202 #define ESET(val) errno = val
203 #endif
204
205 #if defined(LOCALCONN) || defined(LACHMAN)
206 #ifdef EMSGSIZE
207 #define ESZTEST() (ECHECK(EMSGSIZE) || ECHECK(ERANGE))
208 #else
209 #define ESZTEST() ECHECK(ERANGE)
210 #endif
211 #else
212 #ifdef EMSGSIZE
213 #define ESZTEST() ECHECK(EMSGSIZE)
214 #endif
215 #endif
216
217 #if !USE_XCB
218
219 #define STARTITERATE(tpvar,type,start,endcond) \
220 for (tpvar = (type *) (start); endcond; )
221 #define ITERPTR(tpvar) (char *)tpvar
222 #define RESETITERPTR(tpvar,type,start) tpvar = (type *) (start)
223 #define INCITERPTR(tpvar,type) tpvar++
224 #define ENDITERATE
225
226
227 typedef union {
228 xReply rep;
229 char buf[BUFSIZE];
230 } _XAlignedBuffer;
231
232 static char *_XAsyncReply(
233 Display *dpy,
234 register xReply *rep,
235 char *buf,
236 register int *lenp,
237 Bool discard);
238 #endif /* !USE_XCB */
239
240 /*
241 * The following routines are internal routines used by Xlib for protocol
242 * packet transmission and reception.
243 *
244 * _XIOError(Display *) will be called if any sort of system call error occurs.
245 * This is assumed to be a fatal condition, i.e., XIOError should not return.
246 *
247 * _XError(Display *, xError *) will be called whenever an X_Error event is
248 * received. This is not assumed to be a fatal condition, i.e., it is
249 * acceptable for this procedure to return. However, XError should NOT
250 * perform any operations (directly or indirectly) on the DISPLAY.
251 *
252 * Routines declared with a return type of 'Status' return 0 on failure,
253 * and non 0 on success. Routines with no declared return type don't
254 * return anything. Whenever possible routines that create objects return
255 * the object they have created.
256 */
257
258 #if !USE_XCB
259 static xReq _dummy_request = {
260 0, 0, 0
261 };
262
263 #ifdef NX_TRANS_SOCKET
264
265 /*
266 * Replace the standard Select with a version giving NX a
267 * chance to check its own descriptors. This doesn't cover
268 * the cases where the system is using poll or when system-
269 * specific defines override the Select definition (OS/2).
270 */
271
272 int _XSelect(int maxfds, fd_set *readfds, fd_set *writefds,
273 fd_set *exceptfds, struct timeval *timeout)
274 {
275 #ifdef NX_TRANS_TEST
276 fprintf(stderr, "_XSelect: Called with [%d][%p][%p][%p][%p].\n",
277 maxfds, (void *) readfds, (void *) writefds, (void *) exceptfds,
278 (void *) timeout);
279 #endif
280
281 if (NXTransRunning(NX_FD_ANY))
282 {
283 fd_set t_readfds, t_writefds;
284 struct timeval t_timeout;
285
286 #ifdef NX_TRANS_TEST
287 if (exceptfds != NULL)
288 {
289 fprintf(stderr, "_XSelect: WARNING! Can't handle exception fds in select.\n");
290 }
291 #endif
292
293 if (readfds == NULL)
294 {
295 FD_ZERO(&t_readfds);
296 readfds = &t_readfds;
297 }
298
299 if (writefds == NULL)
300 {
301 FD_ZERO(&t_writefds);
302 writefds = &t_writefds;
303 }
304
305 if (timeout == NULL)
306 {
307 t_timeout.tv_sec = 10;
308 t_timeout.tv_usec = 0;
309 timeout = &t_timeout;
310 }
311
312 int n = maxfds;
313
314 /*
315 * If the transport is gone avoid
316 * sleeping until the timeout.
317 */
318
319 if (NXTransPrepare(&n, readfds, writefds, timeout) != 0)
320 {
321 int r, e;
322
323 NXTransSelect(&r, &e, &n, readfds, writefds, timeout);
324 NXTransExecute(&r, &e, &n, readfds, writefds, timeout);
325 errno = e;
326
327 return r;
328 }
329 else
330 {
331 return 0;
332 }
333 }
334 else
335 {
336 return select(maxfds, readfds, writefds, exceptfds, timeout);
337 }
338 }
339
340 #else /* #ifdef NX_TRANS_SOCKET */
341
342 int _XSelect(int maxfds, fd_set *readfds, fd_set *writefds,
343 fd_set *exceptfds, struct timeval *timeout)
344 {
345 return select(maxfds, readfds, writefds, exceptfds, timeout);
346 }
347
348 #endif /* #ifdef NX_TRANS_SOCKET */
349
350 /*
351 * This is an OS dependent routine which:
352 * 1) returns as soon as the connection can be written on....
353 * 2) if the connection can be read, must enqueue events and handle errors,
354 * until the connection is writable.
355 */
356 static void
357 _XWaitForWritable(
358 Display *dpy
359 #ifdef XTHREADS
360 ,
361 xcondition_t cv /* our reading condition variable */
362 #endif
363 )
364 {
365 #ifdef USE_POLL
366 struct pollfd filedes;
367 #else
368 fd_set r_mask;
369 fd_set w_mask;
370 #endif
371 int nfound;
372
373 #ifdef NX_TRANS_SOCKET
374 #if defined(NX_TRANS_CHANGE)
375 int congestion;
376 #endif
377 if (_XGetIOError(dpy)) {
378 return;
379 }
380 #endif
381
382 #ifdef USE_POLL
383 filedes.fd = dpy->fd;
384 filedes.events = 0;
385 #else
386 FD_ZERO(&r_mask);
387 FD_ZERO(&w_mask);
388 #endif
389
390 for (;;) {
391 #ifdef XTHREADS
392 /* We allow only one thread at a time to read, to minimize
393 passing of read data between threads.
394 Now, who is it? If there is a non-NULL reply_awaiters and
395 we (i.e., our cv) are not at the head of it, then whoever
396 is at the head is the reader, and we don't read.
397 Otherwise there is no reply_awaiters or we are at the
398 head, having just appended ourselves.
399 In this case, if there is a event_awaiters, then whoever
400 is at the head of it got there before we did, and they are the
401 reader.
402
403 Last cases: no event_awaiters and we are at the head of
404 reply_awaiters or reply_awaiters is NULL: we are the reader,
405 since there is obviously no one else involved.
406
407 XXX - what if cv is NULL and someone else comes along after
408 us while we are waiting?
409 */
410
411 if (!dpy->lock ||
412 (!dpy->lock->event_awaiters &&
413 (!dpy->lock->reply_awaiters ||
414 dpy->lock->reply_awaiters->cv == cv)))
415 #endif
416
417 #ifndef NX_TRANS_SOCKET
418 #ifdef USE_POLL
419 filedes.events = POLLIN;
420 filedes.events |= POLLOUT;
421 #else
422 FD_SET(dpy->fd, &r_mask);
423 FD_SET(dpy->fd, &w_mask);
424 #endif
425 #endif /* #ifndef NX_TRANS_SOCKET */
426
427 do {
428 #ifdef NX_TRANS_SOCKET
429 /*
430 * Give a chance to the registered client to perform
431 * any needed operation before entering the select.
432 */
433
434 #ifdef NX_TRANS_TEST
435 fprintf(stderr, "_XWaitForWritable: WAIT! Waiting for the display to become writable.\n");
436 #endif
437 NXTransFlush(dpy->fd);
438
439 if (_NXDisplayBlockFunction != NULL) {
440 (*_NXDisplayBlockFunction)(dpy, NXBlockWrite);
441 }
442
443 /*
444 * Need to set again the descriptors as we could have
445 * run multiple selects before having the possibility
446 * to read or write to the X connection.
447 */
448
449 #ifdef USE_POLL
450 filedes.events = POLLIN;
451 filedes.events |= POLLOUT;
452 #else
453 FD_SET(dpy->fd, &r_mask);
454 FD_SET(dpy->fd, &w_mask);
455 #endif
456 #endif /* #ifdef NX_TRANS_SOCKET */
457 UnlockDisplay(dpy);
458 #ifdef USE_POLL
459 #ifdef NX_TRANS_DEBUG
460 fprintf(stderr, "_XWaitForWritable: Calling poll().\n");
461 #endif
462 nfound = poll (&filedes, 1, -1);
463 #else /* USE_POLL */
464 #ifdef NX_TRANS_DEBUG
465 fprintf(stderr, "_XWaitForWritable: Calling select() after [%ld] ms.\n",
466 NXTransTime());
467 #endif /* ifdef NX_TRANS_DEBUG */
468 #ifdef NX_TRANS_SOCKET
469 /*
470 * Give a chance to the callback to detect
471 * the failure of the display even if we
472 * miss the interrupt inside the select.
473 */
474
475 if (_NXDisplayErrorFunction != NULL) {
476 retry.tv_sec = 5;
477 retry.tv_usec = 0;
478 nfound = Select (dpy->fd + 1, &r_mask, &w_mask, NULL, &retry);
479 } else {
480 nfound = Select (dpy->fd + 1, &r_mask, &w_mask, NULL, NULL);
481 }
482 #else /* NX_TRANS_SOCKET */
483 nfound = Select (dpy->fd + 1, &r_mask, &w_mask, NULL, NULL);
484 #endif /* NX_TRANS_SOCKET */
485 #ifdef NX_TRANS_DEBUG
486 fprintf(stderr, "_XWaitForWritable: Out of select() with [%d] after [%ld] ms.\n",
487 nfound, NXTransTime());
488
489 if (FD_ISSET(dpy->fd, &r_mask))
490 {
491 BytesReadable_t pend;
492
493 _X11TransBytesReadable(dpy->trans_conn, &pend);
494
495 fprintf(stderr, "_XWaitForWritable: Descriptor [%d] is ready with [%ld] bytes to read.\n",
496 dpy->fd, pend);
497 }
498
499 if (FD_ISSET(dpy->fd, &w_mask))
500 {
501 fprintf(stderr, "_XWaitForWritable: Descriptor [%d] has become writable.\n\n",
502 dpy->fd);
503 }
504 #endif /* ifdef NX_TRANS_DEBUG */
505 #endif /* USE_POLL */
506 InternalLockDisplay(dpy, cv != NULL);
507 #ifdef NX_TRANS_SOCKET
508 #ifdef NX_TRANS_CHANGE
509 if (_NXDisplayCongestionFunction != NULL &&
510 _X11TransSocketCongestionChange(dpy->trans_conn, &congestion) == 1) {
511 (*_NXDisplayCongestionFunction)(dpy, congestion);
512 }
513 #endif /* ifdef NX_TRANS_CHANGE */
514 if (nfound <= 0) {
515 if ((nfound == -1 && !(ECHECK(EINTR) || ETEST())) ||
516 (_NXDisplayErrorFunction != NULL &&
517 (*_NXDisplayErrorFunction)(dpy, _XGetIOError(dpy)))) {
518 _XIOError(dpy);
519 return;
520 }
521 }
522 #else /* NX_TRANS_SOCKET */
523 if (nfound < 0 && !(ECHECK(EINTR) || ETEST()))
524 _XIOError(dpy);
525 #endif /* NX_TRANS_SOCKET */
526 } while (nfound <= 0);
527
528 if (
529 #ifdef USE_POLL
530 filedes.revents & POLLIN
531 #else /* USE_POLL */
532 FD_ISSET(dpy->fd, &r_mask)
533 #endif /* USE_POLL */
534 )
535 {
536 _XAlignedBuffer buf;
537 BytesReadable_t pend;
538 register int len;
539 register xReply *rep;
540
541 /* find out how much data can be read */
542 if (_X11TransBytesReadable(dpy->trans_conn, &pend) < 0)
543 #ifdef NX_TRANS_SOCKET
544 {
545 _XIOError(dpy);
546 return;
547 }
548 #else /* NX_TRANS_SOCKET */
549 _XIOError(dpy);
550 #endif /* NX_TRANS_SOCKET */
551 len = pend;
552
553 /* must read at least one xEvent; if none is pending, then
554 we'll just block waiting for it */
555 if (len < SIZEOF(xReply)
556 #ifdef XTHREADS
557 || dpy->async_handlers
558 #endif
559 )
560 len = SIZEOF(xReply);
561
562 /* but we won't read more than the max buffer size */
563 if (len > BUFSIZE) len = BUFSIZE;
564
565 /* round down to an integral number of XReps */
566 len = (len / SIZEOF(xReply)) * SIZEOF(xReply);
567
568 (void) _XRead (dpy, buf.buf, (long) len);
569
570 STARTITERATE(rep,xReply,buf.buf,len > 0) {
571 if (rep->generic.type == X_Reply) {
572 int tmp = len;
573 RESETITERPTR(rep,xReply,
574 _XAsyncReply (dpy, rep,
575 ITERPTR(rep), &tmp, True));
576 len = tmp;
577 pend = len;
578 } else {
579 if (rep->generic.type == X_Error)
580 _XError (dpy, (xError *)rep);
581 else /* must be an event packet */
582 _XEnq (dpy, (xEvent *)rep);
583 INCITERPTR(rep,xReply);
584 len -= SIZEOF(xReply);
585 }
586 } ENDITERATE
587 #ifdef XTHREADS
588 if (dpy->lock && dpy->lock->event_awaiters)
589 ConditionSignal(dpy, dpy->lock->event_awaiters->cv);
590 #endif
591 }
592 #ifdef USE_POLL
593 if (filedes.revents & (POLLOUT|POLLHUP|POLLERR))
594 #else
595 if (FD_ISSET(dpy->fd, &w_mask))
596 #endif
597 {
598 #ifdef XTHREADS
599 if (dpy->lock) {
600 ConditionBroadcast(dpy, dpy->lock->writers);
601 }
602 #endif
603 return;
604 }
605 }
606 }
607 #endif /* !USE_XCB */
608
609
610 #define POLLFD_CACHE_SIZE 5
611
612 /* initialize the struct array passed to poll() below */
613 Bool _XPollfdCacheInit(
614 Display *dpy)
615 {
616 #ifdef USE_POLL
617 struct pollfd *pfp;
618
619 pfp = Xmalloc(POLLFD_CACHE_SIZE * sizeof(struct pollfd));
620 if (!pfp)
621 return False;
622 pfp[0].fd = dpy->fd;
623 pfp[0].events = POLLIN;
624
625 dpy->filedes = (XPointer)pfp;
626 #endif
627 return True;
628 }
629
630 void _XPollfdCacheAdd(
631 Display *dpy,
632 int fd)
633 {
634 #ifdef USE_POLL
635 struct pollfd *pfp = (struct pollfd *)dpy->filedes;
636
637 if (dpy->im_fd_length <= POLLFD_CACHE_SIZE) {
638 pfp[dpy->im_fd_length].fd = fd;
639 pfp[dpy->im_fd_length].events = POLLIN;
640 }
641 #endif
642 }
643
644 /* ARGSUSED */
645 void _XPollfdCacheDel(
646 Display *dpy,
647 int fd) /* not used */
648 {
649 #ifdef USE_POLL
650 struct pollfd *pfp = (struct pollfd *)dpy->filedes;
651 struct _XConnectionInfo *conni;
652
653 /* just recalculate whole list */
654 if (dpy->im_fd_length <= POLLFD_CACHE_SIZE) {
655 int loc = 1;
656 for (conni = dpy->im_fd_info; conni; conni=conni->next) {
657 pfp[loc].fd = conni->fd;
658 pfp[loc].events = POLLIN;
659 loc++;
660 }
661 }
662 #endif
663 }
664
665 #if !USE_XCB
666 /* returns True iff there is an event in the queue newer than serial_num */
667
668 static Bool
669 _XNewerQueuedEvent(
670 Display *dpy,
671 int serial_num)
672 {
673 _XQEvent *qev;
674
675 if (dpy->next_event_serial_num == serial_num)
676 return False;
677
678 qev = dpy->head;
679 while (qev) {
680 if (qev->qserial_num >= serial_num) {
681 return True;
682 }
683 qev = qev->next;
684 }
685 return False;
686 }
687
688 static int
689 _XWaitForReadable(
690 Display *dpy)
691 {
692 int result;
693 int fd = dpy->fd;
694 struct _XConnectionInfo *ilist;
695 register int saved_event_serial = 0;
696 int in_read_events = 0;
697 register Bool did_proc_conni = False;
698 #ifdef USE_POLL
699 struct pollfd *filedes;
700 #else
701 fd_set r_mask;
702 int highest_fd = fd;
703 #endif
704
705 #ifdef NX_TRANS_CHANGE
706 int congestion;
707 #endif
708 #ifdef NX_TRANS_SOCKET
709 if (_XGetIOError(dpy)) {
710 return -1;
711 }
712 #endif
713
714 #ifdef USE_POLL
715 if (dpy->im_fd_length + 1 > POLLFD_CACHE_SIZE
716 && !(dpy->flags & XlibDisplayProcConni)) {
717 /* XXX - this fallback is gross */
718 int i;
719
720 filedes = (struct pollfd *)Xmalloc(dpy->im_fd_length * sizeof(struct pollfd));
721 filedes[0].fd = fd;
722 filedes[0].events = POLLIN;
723 for (ilist=dpy->im_fd_info, i=1; ilist; ilist=ilist->next, i++) {
724 filedes[i].fd = ilist->fd;
725 filedes[i].events = POLLIN;
726 }
727 } else {
728 filedes = (struct pollfd *)dpy->filedes;
729 }
730 #else /* USE_POLL */
731 FD_ZERO(&r_mask);
732 #endif /* USE_POLL */
733 for (;;) {
734 #ifndef USE_POLL
735 FD_SET(fd, &r_mask);
736 if (!(dpy->flags & XlibDisplayProcConni))
737 for (ilist=dpy->im_fd_info; ilist; ilist=ilist->next) {
738 FD_SET(ilist->fd, &r_mask);
739 if (ilist->fd > highest_fd)
740 highest_fd = ilist->fd;
741 }
742 #endif /* USE_POLL */
743 UnlockDisplay(dpy);
744 #ifdef USE_POLL
745 #ifdef NX_TRANS_DEBUG
746 fprintf(stderr, "_XWaitForReadable: Calling poll().\n");
747 #endif
748 result = poll(filedes,
749 (dpy->flags & XlibDisplayProcConni) ? 1 : 1+dpy->im_fd_length,
750 -1);
751 #else /* USE_POLL */
752 #ifdef NX_TRANS_DEBUG
753 fprintf(stderr, "_XWaitForReadable: Calling select().\n");
754 #endif
755 #ifdef NX_TRANS_SOCKET
756 /*
757 * Give a chance to the registered application
758 * to perform any needed operation.
759 */
760
761 #ifdef NX_TRANS_TEST
762 fprintf(stderr, "_XWaitForReadable: WAIT! Waiting for the display to become readable.\n");
763 #endif
764 NXTransFlush(dpy->fd);
765
766 if (_NXDisplayBlockFunction != NULL) {
767 (*_NXDisplayBlockFunction)(dpy, NXBlockRead);
768 }
769
770 if (_NXDisplayErrorFunction != NULL) {
771 retry.tv_sec = 5;
772 retry.tv_usec = 0;
773 result = Select(highest_fd + 1, &r_mask, NULL, NULL, &retry);
774 } else {
775 result = Select(highest_fd + 1, &r_mask, NULL, NULL, NULL);
776 }
777 #else /* NX_TRANS_SOCKET */
778 result = Select(highest_fd + 1, &r_mask, NULL, NULL, NULL);
779 #endif /* NX_TRANS_SOCKET */
780 #endif /* USE_POLL */
781 #ifdef NX_TRANS_DEBUG
782 fprintf(stderr, "_XWaitForReadable: Out of select with result [%d] and errno [%d].\n",
783 result, (result < 0 ? errno : 0));
784 #endif
785 InternalLockDisplay(dpy, dpy->flags & XlibDisplayReply);
786 #ifdef NX_TRANS_CHANGE
787 if (_NXDisplayCongestionFunction != NULL &&
788 _X11TransSocketCongestionChange(dpy->trans_conn, &congestion) == 1) {
789 (*_NXDisplayCongestionFunction)(dpy, congestion);
790 }
791 #endif
792 #ifdef NX_TRANS_SOCKET
793 if (result <= 0) {
794 if ((result == -1 && !(ECHECK(EINTR) || ETEST())) ||
795 (_NXDisplayErrorFunction != NULL &&
796 (*_NXDisplayErrorFunction)(dpy, _XGetIOError(dpy)))) {
797 _XIOError(dpy);
798 return -1;
799 }
800 continue;
801 }
802 #else
803 if (result == -1 && !(ECHECK(EINTR) || ETEST())) _XIOError(dpy);
804 if (result <= 0)
805 continue;
806 #endif
807 #ifdef USE_POLL
808 if (filedes[0].revents & (POLLIN|POLLHUP|POLLERR))
809 #else
810 if (FD_ISSET(fd, &r_mask))
811 #endif
812 break;
813 if (!(dpy->flags & XlibDisplayProcConni)) {
814 int i;
815
816 saved_event_serial = dpy->next_event_serial_num;
817 /* dpy flags can be clobbered by internal connection callback */
818 in_read_events = dpy->flags & XlibDisplayReadEvents;
819 for (ilist=dpy->im_fd_info, i=1; ilist; ilist=ilist->next, i++) {
820 #ifdef USE_POLL
821 if (filedes[i].revents & POLLIN)
822 #else
823 if (FD_ISSET(ilist->fd, &r_mask))
824 #endif
825 {
826 _XProcessInternalConnection(dpy, ilist);
827 did_proc_conni = True;
828 }
829 }
830 #ifdef USE_POLL
831 if (dpy->im_fd_length + 1 > POLLFD_CACHE_SIZE)
832 Xfree(filedes);
833 #endif
834 }
835 if (did_proc_conni) {
836 /* some internal connection callback might have done an
837 XPutBackEvent. We notice it here and if we needed an event,
838 we can return all the way. */
839 if (_XNewerQueuedEvent(dpy, saved_event_serial)
840 && (in_read_events
841 #ifdef XTHREADS
842 || (dpy->lock && dpy->lock->event_awaiters)
843 #endif
844 ))
845 return -2;
846 did_proc_conni = False;
847 }
848 }
849 #ifdef XTHREADS
850 #ifdef XTHREADS_DEBUG
851 printf("thread %x _XWaitForReadable returning\n", XThread_Self());
852 #endif
853 #endif
854 return 0;
855 }
856 #endif /* !USE_XCB */
857
858 static int sync_hazard(Display *dpy)
859 {
860 /*
861 * "span" and "hazard" need to be signed such that the ">=" comparison
862 * works correctly in the case that hazard is greater than 65525
863 */
864 int64_t span = X_DPY_GET_REQUEST(dpy) - X_DPY_GET_LAST_REQUEST_READ(dpy);
865 int64_t hazard = min((dpy->bufmax - dpy->buffer) / SIZEOF(xReq), 65535 - 10);
866 return span >= 65535 - hazard - 10;
867 }
868
869 static
870 void sync_while_locked(Display *dpy)
871 {
872 #ifdef XTHREADS
873 if (dpy->lock)
874 (*dpy->lock->user_lock_display)(dpy);
875 #endif
876 UnlockDisplay(dpy);
877 SyncHandle();
878 InternalLockDisplay(dpy, /* don't skip user locks */ 0);
879 #ifdef XTHREADS
880 if (dpy->lock)
881 (*dpy->lock->user_unlock_display)(dpy);
882 #endif
883 }
884
885 void _XSeqSyncFunction(
886 register Display *dpy)
887 {
888 xGetInputFocusReply rep;
889 _X_UNUSED register xReq *req;
890
891 #ifdef NX_TRANS_SOCKET
892 #ifdef NX_TRANS_DEBUG
893 fprintf(stderr, "_XSeqSyncFunction: Going to synchronize the display.\n");
894 #endif
895
896 if (dpy->flags & XlibDisplayIOError)
897 {
898 #ifdef NX_TRANS_DEBUG
899 fprintf(stderr, "_XSeqSyncFunction: Returning with I/O error detected.\n");
900 #endif
901 return;
902 }
903 #endif /* NX_TRANS_SOCKET */
904 if ((X_DPY_GET_REQUEST(dpy) - X_DPY_GET_LAST_REQUEST_READ(dpy)) >= (65535 - BUFSIZE/SIZEOF(xReq))) {
905 GetEmptyReq(GetInputFocus, req);
906 (void) _XReply (dpy, (xReply *)&rep, 0, xTrue);
907 sync_while_locked(dpy);
908 } else if (sync_hazard(dpy))
909 _XSetPrivSyncFunction(dpy);
910 }
911
912 /* NOTE: only called if !XTHREADS, or when XInitThreads wasn't called. */
913 static int
914 _XPrivSyncFunction (Display *dpy)
915 {
916 #ifdef NX_TRANS_SOCKET
917 if (dpy->flags & XlibDisplayIOError)
918 {
919 #ifdef NX_TRANS_DEBUG
920 fprintf(stderr, "%s: Returning 0 with I/O error detected.\n", __func__);
921 #endif
922 return 0;
923 }
924 #endif /* NX_TRANS_SOCKET */
925
926 #ifdef XTHREADS
927 assert(!dpy->lock_fns);
928 #endif
929 assert(dpy->synchandler == _XPrivSyncFunction);
930 assert((dpy->flags & XlibDisplayPrivSync) != 0);
931 dpy->synchandler = dpy->savedsynchandler;
932 dpy->savedsynchandler = NULL;
933 dpy->flags &= ~XlibDisplayPrivSync;
934 if(dpy->synchandler)
935 dpy->synchandler(dpy);
936 _XIDHandler(dpy);
937 _XSeqSyncFunction(dpy);
938 return 0;
939 }
940
941 void _XSetPrivSyncFunction(Display *dpy)
942 {
943 #ifdef XTHREADS
944 if (dpy->lock_fns)
945 return;
946 #endif
947 if (!(dpy->flags & XlibDisplayPrivSync)) {
948 dpy->savedsynchandler = dpy->synchandler;
949 dpy->synchandler = _XPrivSyncFunction;
950 dpy->flags |= XlibDisplayPrivSync;
951 }
952 }
953
954 void _XSetSeqSyncFunction(Display *dpy)
955 {
956 if (sync_hazard(dpy))
957 _XSetPrivSyncFunction (dpy);
958 }
959
960 #if !USE_XCB
961 #ifdef XTHREADS
962 static void _XFlushInt(
963 register Display *dpy,
964 register xcondition_t cv);
965 #endif
966
967 /*
968 * _XFlush - Flush the X request buffer. If the buffer is empty, no
969 * action is taken. This routine correctly handles incremental writes.
970 * This routine may have to be reworked if int < long.
971 */
972 void _XFlush(
973 register Display *dpy)
974 {
975 #ifdef XTHREADS
976 /* With multi-threading we introduce an internal routine to which
977 we can pass a condition variable to do locking correctly. */
978
979 _XFlushInt(dpy, NULL);
980 }
981
982 /* _XFlushInt - Internal version of _XFlush used to do multi-threaded
983 * locking correctly.
984 */
985
986 static void _XFlushInt(
987 register Display *dpy,
988 register xcondition_t cv)
989 {
990 #endif /* XTHREADS*/
991 register long size, todo;
992 register int write_stat;
993 register char *bufindex;
994 _XExtension *ext;
995 #ifdef NX_TRANS_CHANGE
996 int congestion;
997 #endif
998
999 #ifdef NX_TRANS_DEBUG
1000 fprintf(stderr, "_XFlushInt: Entering flush with [%d] bytes to write.\n",
1001 (dpy->bufptr - dpy->buffer));
1002 #endif
1003 /* This fix resets the bufptr to the front of the buffer so
1004 * additional appends to the bufptr will not corrupt memory. Since
1005 * the server is down, these appends are no-op's anyway but
1006 * callers of _XFlush() are not verifying this before they call it.
1007 */
1008 if (dpy->flags & XlibDisplayIOError)
1009 {
1010 #ifdef NX_TRANS_DEBUG
1011 fprintf(stderr, "_XFlushInt: Returning with I/O error detected.\n");
1012 #endif
1013 dpy->bufptr = dpy->buffer;
1014 dpy->last_req = (char *)&_dummy_request;
1015 return;
1016 }
1017
1018 #ifdef XTHREADS
1019 #ifdef NX_TRANS_SOCKET
1020 while (dpy->flags & XlibDisplayWriting) {
1021 if (_XGetIOError(dpy)) {
1022 return;
1023 }
1024 #else
1025 while (dpy->flags & XlibDisplayWriting) {
1026 #endif
1027 if (dpy->lock) {
1028 ConditionWait(dpy, dpy->lock->writers);
1029 } else {
1030 _XWaitForWritable (dpy, cv);
1031 }
1032 }
1033 #endif
1034 size = todo = dpy->bufptr - dpy->buffer;
1035 if (!size) return;
1036 #ifdef XTHREADS
1037 dpy->flags |= XlibDisplayWriting;
1038 /* make sure no one else can put in data */
1039 dpy->bufptr = dpy->bufmax;
1040 #endif
1041 for (ext = dpy->flushes; ext; ext = ext->next_flush)
1042 (*ext->before_flush)(dpy, &ext->codes, dpy->buffer, size);
1043 bufindex = dpy->buffer;
1044 /*
1045 * While write has not written the entire buffer, keep looping
1046 * until the entire buffer is written. bufindex will be
1047 * incremented and size decremented as buffer is written out.
1048 */
1049 while (size) {
1050 ESET(0);
1051 write_stat = _X11TransWrite(dpy->trans_conn,
1052 bufindex, (int) todo);
1053 if (write_stat >= 0) {
1054 #ifdef NX_TRANS_SOCKET
1055 if (_NXDisplayWriteFunction != NULL) {
1056 (*_NXDisplayWriteFunction)(dpy, write_stat);
1057 }
1058 #ifdef NX_TRANS_CHANGE
1059 if (_NXDisplayCongestionFunction != NULL &&
1060 _X11TransSocketCongestionChange(dpy->trans_conn, &congestion) == 1) {
1061 (*_NXDisplayCongestionFunction)(dpy, congestion);
1062 }
1063 #endif
1064 #endif
1065 size -= write_stat;
1066 todo = size;
1067 bufindex += write_stat;
1068 } else if (ETEST()) {
1069 _XWaitForWritable(dpy
1070 #ifdef XTHREADS
1071 , cv
1072 #endif
1073 );
1074 #ifdef SUNSYSV
1075 } else if (ECHECK(0)) {
1076 _XWaitForWritable(dpy
1077 #ifdef XTHREADS
1078 , cv
1079 #endif
1080 );
1081 #endif
1082 #ifdef ESZTEST
1083 } else if (ESZTEST()) {
1084 if (todo > 1)
1085 todo >>= 1;
1086 else {
1087 _XWaitForWritable(dpy
1088 #ifdef XTHREADS
1089 , cv
1090 #endif
1091 );
1092 }
1093 #endif
1094 #ifdef NX_TRANS_SOCKET
1095 } else if (!ECHECK(EINTR) ||
1096 (_NXDisplayErrorFunction != NULL &&
1097 (*_NXDisplayErrorFunction)(dpy, _XGetIOError(dpy)))) {
1098 _XIOError(dpy);
1099 return;
1100 }
1101 #else
1102 } else if (!ECHECK(EINTR)) {
1103 /* Write failed! */
1104 /* errno set by write system call. */
1105 _XIOError(dpy);
1106 }
1107 #endif
1108 #ifdef NX_TRANS_SOCKET
1109 if (_XGetIOError(dpy)) {
1110 return;
1111 }
1112 #endif
1113 }
1114 dpy->last_req = (char *)&_dummy_request;
1115 _XSetSeqSyncFunction(dpy);
1116 dpy->bufptr = dpy->buffer;
1117 #ifdef XTHREADS
1118 dpy->flags &= ~XlibDisplayWriting;
1119 #endif
1120 }
1121
1122 int
1123 _XEventsQueued(
1124 register Display *dpy,
1125 int mode)
1126 {
1127 register int len;
1128 BytesReadable_t pend;
1129 _XAlignedBuffer buf;
1130 register xReply *rep;
1131 char *read_buf;
1132 #ifdef XTHREADS
1133 int entry_event_serial_num;
1134 struct _XCVList *cvl = NULL;
1135 xthread_t self;
1136
1137 #ifdef XTHREADS_DEBUG
1138 printf("_XEventsQueued called in thread %x\n", XThread_Self());
1139 #endif
1140 #endif /* XTHREADS*/
1141
1142 if (mode == QueuedAfterFlush)
1143 {
1144 _XFlush(dpy);
1145 if (dpy->qlen)
1146 return(dpy->qlen);
1147 }
1148 #ifdef NX_TRANS_DEBUG
1149 if (dpy->flags & XlibDisplayIOError) {
1150 fprintf(stderr, "_XEventsQueued: Returning [%d] after display failure.\n",
1151 dpy->qlen);
1152 }
1153 #endif
1154 if (dpy->flags & XlibDisplayIOError) return(dpy->qlen);
1155
1156 #ifdef XTHREADS
1157 /* create our condition variable and append to list,
1158 * unless we were called from within XProcessInternalConnection
1159 * or XLockDisplay
1160 */
1161 xthread_clear_id(self);
1162 if (dpy->lock && (xthread_have_id (dpy->lock->conni_thread)
1163 || xthread_have_id (dpy->lock->locking_thread)))
1164 /* some thread is in XProcessInternalConnection or XLockDisplay
1165 so we have to see if we are it */
1166 self = XThread_Self();
1167 if (!xthread_have_id(self)
1168 || (!xthread_equal(self, dpy->lock->conni_thread)
1169 && !xthread_equal(self, dpy->lock->locking_thread))) {
1170 /* In the multi-threaded case, if there is someone else
1171 reading events, then there aren't any available, so
1172 we just return. If we waited we would block.
1173 */
1174 if (dpy->lock && dpy->lock->event_awaiters)
1175 return dpy->qlen;
1176 /* nobody here but us, so lock out any newcomers */
1177 cvl = QueueEventReaderLock(dpy);
1178 }
1179
1180 while (dpy->lock && cvl && dpy->lock->reply_first) {
1181 /* note which events we have already seen so we'll know
1182 if _XReply (in another thread) reads one */
1183 entry_event_serial_num = dpy->next_event_serial_num;
1184 ConditionWait(dpy, cvl->cv);
1185 /* did _XReply read an event we can return? */
1186 if (_XNewerQueuedEvent(dpy, entry_event_serial_num))
1187 {
1188 UnlockNextEventReader(dpy);
1189 return 0;
1190 }
1191 }
1192 #endif /* XTHREADS*/
1193
1194 #ifdef NX_TRANS_DEBUG
1195 fprintf(stderr, "_XEventsQueued: Checking bytes readable.\n");
1196 #endif
1197 if (_X11TransBytesReadable(dpy->trans_conn, &pend) < 0)
1198 #ifdef NX_TRANS_SOCKET
1199 {
1200 _XIOError(dpy);
1201 return (dpy->qlen);
1202 }
1203 #else
1204 _XIOError(dpy);
1205 #endif
1206 #ifdef XCONN_CHECK_FREQ
1207 /* This is a crock, required because FIONREAD or equivalent is
1208 * not guaranteed to detect a broken connection.
1209 */
1210 if (!pend && !dpy->qlen && ++dpy->conn_checker >= XCONN_CHECK_FREQ)
1211 {
1212 int result;
1213 #ifdef USE_POLL
1214 struct pollfd filedes;
1215 #else
1216 fd_set r_mask;
1217 static struct timeval zero_time;
1218 #endif
1219
1220 dpy->conn_checker = 0;
1221 #ifdef USE_POLL
1222 #ifdef NX_TRANS_DEBUG
1223 fprintf(stderr, "_XEventsQueued: Calling poll().\n");
1224 #endif
1225 filedes.fd = dpy->fd;
1226 filedes.events = POLLIN;
1227 if ((result = poll(&filedes, 1, 0)))
1228 #else
1229 #ifdef NX_TRANS_DEBUG
1230 fprintf(stderr, "_XEventsQueued: Calling select().\n");
1231 #endif
1232 FD_ZERO(&r_mask);
1233 FD_SET(dpy->fd, &r_mask);
1234 if ((result = Select(dpy->fd + 1, &r_mask, NULL, NULL, &zero_time)))
1235 #endif
1236 {
1237 if (result > 0)
1238 {
1239 if (_X11TransBytesReadable(dpy->trans_conn, &pend) < 0)
1240 #ifdef NX_TRANS_SOCKET
1241 {
1242 _XIOError(dpy);
1243 return (dpy->qlen);
1244 }
1245 #else
1246 _XIOError(dpy);
1247 #endif
1248 /* we should not get zero, if we do, force a read */
1249 if (!pend)
1250 pend = SIZEOF(xReply);
1251 }
1252 #ifdef NX_TRANS_SOCKET
1253 if (result <= 0) {
1254 if ((result == -1 && !(ECHECK(EINTR) || ETEST())) ||
1255 (_NXDisplayErrorFunction != NULL &&
1256 (*_NXDisplayErrorFunction)(dpy, _XGetIOError(dpy)))) {
1257 _XIOError(dpy);
1258 return (dpy->qlen);
1259 }
1260 }
1261 #else
1262 else if (result < 0 && !(ECHECK(EINTR) || ETEST()))
1263 #endif
1264 _XIOError(dpy);
1265 }
1266 }
1267 #endif /* XCONN_CHECK_FREQ */
1268 if (!(len = pend)) {
1269 /* _XFlush can enqueue events */
1270 #ifdef XTHREADS
1271 if (cvl)
1272 #endif
1273 {
1274 UnlockNextEventReader(dpy);
1275 }
1276 #ifdef NX_TRANS_DEBUG
1277 fprintf(stderr, "_XEventsQueued: Returning [%d].\n", dpy->qlen);
1278 #endif
1279 return(dpy->qlen);
1280 }
1281 /* Force a read if there is not enough data. Otherwise,
1282 * a select() loop at a higher-level will spin undesirably,
1283 * and we've seen at least one OS that appears to not update
1284 * the result from FIONREAD once it has returned nonzero.
1285 */
1286 #ifdef XTHREADS
1287 if (dpy->lock && dpy->lock->reply_awaiters) {
1288 read_buf = (char *)dpy->lock->reply_awaiters->buf;
1289 len = SIZEOF(xReply);
1290 } else
1291 #endif /* XTHREADS*/
1292 {
1293 read_buf = buf.buf;
1294
1295 if (len < SIZEOF(xReply)
1296 #ifdef XTHREADS
1297 || dpy->async_handlers
1298 #endif
1299 )
1300 len = SIZEOF(xReply);
1301 else if (len > BUFSIZE)
1302 len = BUFSIZE;
1303 len = (len / SIZEOF(xReply)) * SIZEOF(xReply);
1304 }
1305 #ifdef XCONN_CHECK_FREQ
1306 dpy->conn_checker = 0;
1307 #endif
1308
1309 (void) _XRead (dpy, read_buf, (long) len);
1310
1311 #ifdef NX_TRANS_SOCKET
1312 if (_XGetIOError(dpy)) {
1313 return(dpy->qlen);
1314 }
1315 #endif
1316 #ifdef XTHREADS
1317 /* what did we actually read: reply or event? */
1318 if (dpy->lock && dpy->lock->reply_awaiters) {
1319 if (((xReply *)read_buf)->generic.type == X_Reply ||
1320 ((xReply *)read_buf)->generic.type == X_Error)
1321 {
1322 dpy->lock->reply_was_read = True;
1323 dpy->lock->reply_first = True;
1324 if (read_buf != (char *)dpy->lock->reply_awaiters->buf)
1325 memcpy(dpy->lock->reply_awaiters->buf, read_buf,
1326 len);
1327 if (cvl) {
1328 UnlockNextEventReader(dpy);
1329 }
1330 return(dpy->qlen); /* we read, so we can return */
1331 } else if (read_buf != buf.buf)
1332 memcpy(buf.buf, read_buf, len);
1333 }
1334 #endif /* XTHREADS*/
1335
1336 STARTITERATE(rep,xReply,buf.buf,len > 0) {
1337 if (rep->generic.type == X_Reply) {
1338 int tmp = len;
1339 RESETITERPTR(rep,xReply,
1340 _XAsyncReply (dpy, rep,
1341 ITERPTR(rep), &tmp, True));
1342 len = tmp;
1343 pend = len;
1344 } else {
1345 if (rep->generic.type == X_Error)
1346 _XError (dpy, (xError *)rep);
1347 else /* must be an event packet */
1348 _XEnq (dpy, (xEvent *)rep);
1349 INCITERPTR(rep,xReply);
1350 len -= SIZEOF(xReply);
1351 }
1352 } ENDITERATE
1353
1354 #ifdef XTHREADS
1355 if (cvl)
1356 #endif
1357 {
1358 UnlockNextEventReader(dpy);
1359 }
1360 return(dpy->qlen);
1361 }
1362
1363 /* _XReadEvents - Flush the output queue,
1364 * then read as many events as possible (but at least 1) and enqueue them
1365 */
1366 void _XReadEvents(
1367 register Display *dpy)
1368 {
1369 _XAlignedBuffer buf;
1370 BytesReadable_t pend;
1371 int len;
1372 register xReply *rep;
1373 Bool not_yet_flushed = True;
1374 char *read_buf;
1375 int i;
1376 int entry_event_serial_num = dpy->next_event_serial_num;
1377 #ifdef XTHREADS
1378 struct _XCVList *cvl = NULL;
1379 xthread_t self;
1380
1381 #ifdef XTHREADS_DEBUG
1382 printf("_XReadEvents called in thread %x\n",
1383 XThread_Self());
1384 #endif
1385 /* create our condition variable and append to list,
1386 * unless we were called from within XProcessInternalConnection
1387 * or XLockDisplay
1388 */
1389 xthread_clear_id(self);
1390 if (dpy->lock && (xthread_have_id (dpy->lock->conni_thread)
1391 || xthread_have_id (dpy->lock->locking_thread)))
1392 /* some thread is in XProcessInternalConnection or XLockDisplay
1393 so we have to see if we are it */
1394 self = XThread_Self();
1395 if (!xthread_have_id(self)
1396 || (!xthread_equal(self, dpy->lock->conni_thread)
1397 && !xthread_equal(self, dpy->lock->locking_thread)))
1398 cvl = QueueEventReaderLock(dpy);
1399 #endif /* XTHREADS */
1400
1401 do {
1402 #ifdef XTHREADS
1403 /* if it is not our turn to read an event off the wire,
1404 wait til we're at head of list */
1405 if (dpy->lock && cvl &&
1406 (dpy->lock->event_awaiters != cvl ||
1407 dpy->lock->reply_first)) {
1408 ConditionWait(dpy, cvl->cv);
1409 continue;
1410 }
1411 #endif /* XTHREADS */
1412 /* find out how much data can be read */
1413 if (_X11TransBytesReadable(dpy->trans_conn, &pend) < 0)
1414 {
1415 _XIOError(dpy);
1416 #ifdef NX_TRANS_SOCKET
1417 return;
1418 #endif
1419 }
1420 len = pend;
1421
1422 /* must read at least one xEvent; if none is pending, then
1423 we'll just flush and block waiting for it */
1424 if (len < SIZEOF(xEvent)
1425 #ifdef XTHREADS
1426 || dpy->async_handlers
1427 #endif
1428 ) {
1429 len = SIZEOF(xEvent);
1430 /* don't flush until the first time we would block */
1431 if (not_yet_flushed) {
1432 _XFlush (dpy);
1433 if (_XNewerQueuedEvent(dpy, entry_event_serial_num)) {
1434 /* _XReply has read an event for us */
1435 goto got_event;
1436 }
1437 not_yet_flushed = False;
1438 }
1439 }
1440
1441 #ifdef XTHREADS
1442 /* If someone is waiting for a reply, gamble that
1443 the reply will be the next thing on the wire
1444 and read it into their buffer. */
1445 if (dpy->lock && dpy->lock->reply_awaiters) {
1446 read_buf = (char *)dpy->lock->reply_awaiters->buf;
1447 len = SIZEOF(xReply);
1448 } else
1449 #endif /* XTHREADS*/
1450 {
1451 read_buf = buf.buf;
1452
1453 /* but we won't read more than the max buffer size */
1454 if (len > BUFSIZE)
1455 len = BUFSIZE;
1456
1457 /* round down to an integral number of XReps */
1458 len = (len / SIZEOF(xEvent)) * SIZEOF(xEvent);
1459 }
1460
1461 #ifdef XTHREADS
1462 if (xthread_have_id(self))
1463 /* save value we may have to stick in conni_thread */
1464 dpy->lock->reading_thread = self;
1465 #endif /* XTHREADS */
1466 dpy->flags |= XlibDisplayReadEvents;
1467 i = _XRead (dpy, read_buf, (long) len);
1468 dpy->flags &= ~XlibDisplayReadEvents;
1469 #ifdef NX_TRANS_SOCKET
1470 if (dpy->flags & XlibDisplayIOError)
1471 {
1472 #ifdef NX_TRANS_DEBUG
1473 fprintf(stderr, "_XReadEvents: Returning with I/O error detected.\n");
1474 #endif
1475 return;
1476 }
1477 #endif
1478 if (i == -2) {
1479 /* special flag from _XRead to say that internal connection has
1480 done XPutBackEvent. Which we can use so we're done. */
1481 got_event:
1482 #ifdef XTHREADS
1483 if (dpy->lock && dpy->lock->lock_wait) {
1484 if (dpy->lock->event_awaiters != cvl)
1485 /* since it is not us, must be user lock thread */
1486 ConditionSignal(dpy,
1487 dpy->lock->event_awaiters->cv);
1488 (*dpy->lock->lock_wait)(dpy);
1489 continue;
1490 }
1491 #endif
1492 break;
1493 }
1494 #ifdef XTHREADS
1495 if (xthread_have_id(self))
1496 xthread_clear_id(dpy->lock->reading_thread);
1497
1498 /* what did we actually read: reply or event? */
1499 if (dpy->lock && dpy->lock->reply_awaiters) {
1500 if (((xReply *)read_buf)->generic.type == X_Reply ||
1501 ((xReply *)read_buf)->generic.type == X_Error)
1502 {
1503 dpy->lock->reply_was_read = True;
1504 dpy->lock->reply_first = True;
1505 if (read_buf != (char *)dpy->lock->reply_awaiters->buf)
1506 memcpy(dpy->lock->reply_awaiters->buf,
1507 read_buf, len);
1508 ConditionSignal(dpy, dpy->lock->reply_awaiters->cv);
1509 continue;
1510 } else if (read_buf != buf.buf)
1511 memcpy(buf.buf, read_buf, len);
1512 }
1513 #endif /* XTHREADS */
1514
1515 STARTITERATE(rep,xReply,buf.buf,len > 0) {
1516 if (rep->generic.type == X_Reply) {
1517 RESETITERPTR(rep,xReply,
1518 _XAsyncReply (dpy, rep,
1519 ITERPTR(rep), &len, True));
1520 pend = len;
1521 } else {
1522 if (rep->generic.type == X_Error)
1523 _XError (dpy, (xError *) rep);
1524 else /* must be an event packet */
1525 {
1526 if (rep->generic.type == GenericEvent)
1527 {
1528 int evlen;
1529 evlen = (rep->generic.length << 2);
1530 if (_XRead(dpy, &read_buf[len], evlen) == -2)
1531 goto got_event; /* XXX: aargh! */
1532 }
1533
1534 _XEnq (dpy, (xEvent *)rep);
1535 }
1536 INCITERPTR(rep,xReply);
1537 len -= SIZEOF(xReply);
1538 }
1539 } ENDITERATE;
1540 } while (!_XNewerQueuedEvent(dpy, entry_event_serial_num));
1541
1542 UnlockNextEventReader(dpy);
1543 }
1544
1545 /*
1546 * _XRead - Read bytes from the socket taking into account incomplete
1547 * reads. This routine may have to be reworked if int < long.
1548 */
1549 int _XRead(
1550 register Display *dpy,
1551 register char *data,
1552 register long size)
1553 {
1554 register long bytes_read;
1555 #ifdef XTHREADS
1556 int original_size = size;
1557 #endif
1558 #ifdef NX_TRANS_CHANGE
1559 int congestion;
1560 #endif
1561
1562 if ((dpy->flags & XlibDisplayIOError) || size == 0)
1563 return 0;
1564 ESET(0);
1565 #ifdef NX_TRANS_CHANGE
1566 while (1) {
1567 /*
1568 * Need to check the congestion state
1569 * after the read so split the statement
1570 * in multiple blocks.
1571 */
1572
1573 bytes_read = _X11TransRead(dpy->trans_conn, data, (int)size);
1574 if (_NXDisplayCongestionFunction != NULL &&
1575 _X11TransSocketCongestionChange(dpy->trans_conn, &congestion) == 1) {
1576 (*_NXDisplayCongestionFunction)(dpy, congestion);
1577 }
1578 if (bytes_read == size) {
1579 break;
1580 }
1581 #else
1582 while ((bytes_read = _X11TransRead(dpy->trans_conn, data, (int)size))
1583 != size) {
1584 #endif
1585
1586 if (bytes_read > 0) {
1587 size -= bytes_read;
1588 data += bytes_read;
1589 }
1590 else if (ETEST()) {
1591 if (_XWaitForReadable(dpy) == -2)
1592 return -2; /* internal connection did XPutBackEvent */
1593 ESET(0);
1594 }
1595 #ifdef SUNSYSV
1596 else if (ECHECK(0)) {
1597 if (_XWaitForReadable(dpy) == -2)
1598 return -2; /* internal connection did XPutBackEvent */
1599 }
1600 #endif
1601 else if (bytes_read == 0) {
1602 /* Read failed because of end of file! */
1603 ESET(EPIPE);
1604
1605 _XIOError(dpy);
1606 #ifdef NX_TRANS_SOCKET
1607 return -1;
1608 #endif
1609 }
1610
1611 else /* bytes_read is less than 0; presumably -1 */ {
1612 /* If it's a system call interrupt, it's not an error. */
1613 #ifdef NX_TRANS_SOCKET
1614 if (!ECHECK(EINTR) ||
1615 (_NXDisplayErrorFunction != NULL &&
1616 (*_NXDisplayErrorFunction)(dpy, _XGetIOError(dpy)))) {
1617 _XIOError(dpy);
1618 return -1;
1619 }
1620 #else
1621 if (!ECHECK(EINTR))
1622 _XIOError(dpy);
1623 #endif
1624 }
1625 #ifdef NX_TRANS_SOCKET
1626 if (_XGetIOError(dpy)) {
1627 return -1;
1628 }
1629 #endif
1630 }
1631 #ifdef XTHREADS
1632 if (dpy->lock && dpy->lock->reply_bytes_left > 0)
1633 {
1634 dpy->lock->reply_bytes_left -= original_size;
1635 if (dpy->lock->reply_bytes_left == 0) {
1636 dpy->flags &= ~XlibDisplayReply;
1637 UnlockNextReplyReader(dpy);
1638 }
1639 }
1640 #endif /* XTHREADS*/
1641 return 0;
1642 }
1643 #endif /* !USE_XCB */
1644
1645 #ifdef LONG64
1646 void _XRead32(
1647 Display *dpy,
1648 long *data,
1649 long len)
1650 {
1651 register int *buf;
1652 register long i;
1653
1654 if (len) {
1655 (void) _XRead(dpy, (char *)data, len);
1656 i = len >> 2;
1657 buf = (int *)data + i;
1658 data += i;
1659 while (--i >= 0)
1660 *--data = *--buf;
1661 }
1662 }
1663 #endif /* LONG64 */
1664
1665
1666
1667 #if !USE_XCB
1668 /*
1669 * _XReadPad - Read bytes from the socket taking into account incomplete
1670 * reads. If the number of bytes is not 0 mod 4, read additional pad
1671 * bytes. This routine may have to be reworked if int < long.
1672 */
1673 void _XReadPad(
1674 register Display *dpy,
1675 register char *data,
1676 register long size)
1677 {
1678 register long bytes_read;
1679 struct iovec iov[2];
1680 char pad[3];
1681 #ifdef XTHREADS
1682 int original_size;
1683 #endif
1684 #ifdef NX_TRANS_CHANGE
1685 int congestion;
1686 #endif
1687
1688 if ((dpy->flags & XlibDisplayIOError) || size == 0) return;
1689 iov[0].iov_len = (int)size;
1690 iov[0].iov_base = data;
1691 /*
1692 * The following hack is used to provide 32 bit long-word
1693 * aligned padding. The [1] vector is of length 0, 1, 2, or 3,
1694 * whatever is needed.
1695 */
1696
1697 iov[1].iov_len = -size & 3;
1698 iov[1].iov_base = pad;
1699 size += iov[1].iov_len;
1700 #ifdef XTHREADS
1701 original_size = size;
1702 #endif
1703 ESET(0);
1704 #ifdef NX_TRANS_CHANGE
1705 while (1) {
1706 bytes_read = _X11TransReadv (dpy->trans_conn, iov, 2);
1707 if (_NXDisplayCongestionFunction != NULL &&
1708 _X11TransSocketCongestionChange(dpy->trans_conn, &congestion) == 1) {
1709 (*_NXDisplayCongestionFunction)(dpy, congestion);
1710 }
1711 if (bytes_read == size) {
1712 break;
1713 }
1714 #else
1715 while ((bytes_read = _X11TransReadv (dpy->trans_conn, iov, 2)) != size) {
1716 #endif
1717
1718 if (bytes_read > 0) {
1719 size -= bytes_read;
1720 if (iov[0].iov_len < bytes_read) {
1721 int pad_bytes_read = bytes_read - iov[0].iov_len;
1722 iov[1].iov_len -= pad_bytes_read;
1723 iov[1].iov_base =
1724 (char *)iov[1].iov_base + pad_bytes_read;
1725 iov[0].iov_len = 0;
1726 }
1727 else {
1728 iov[0].iov_len -= bytes_read;
1729 iov[0].iov_base = (char *)iov[0].iov_base + bytes_read;
1730 }
1731 }
1732 else if (ETEST()) {
1733 _XWaitForReadable(dpy);
1734 ESET(0);
1735 }
1736 #ifdef SUNSYSV
1737 else if (ECHECK(0)) {
1738 _XWaitForReadable(dpy);
1739 }
1740 #endif
1741 else if (bytes_read == 0) {
1742 /* Read failed because of end of file! */
1743 ESET(EPIPE);
1744 #ifdef NX_TRANS_SOCKET
1745 _XIOError(dpy);
1746
1747 return;
1748 #else
1749 _XIOError(dpy);
1750 #endif
1751 }
1752
1753 else /* bytes_read is less than 0; presumably -1 */ {
1754 /* If it's a system call interrupt, it's not an error. */
1755 #ifdef NX_TRANS_SOCKET
1756 if (!ECHECK(EINTR) ||
1757 (_NXDisplayErrorFunction != NULL &&
1758 (*_NXDisplayErrorFunction)(dpy, _XGetIOError(dpy)))) {
1759 _XIOError(dpy);
1760 return;
1761 }
1762 #else
1763 if (!ECHECK(EINTR))
1764 _XIOError(dpy);
1765 #endif
1766 }
1767 #ifdef NX_TRANS_SOCKET
1768 if (_XGetIOError(dpy)) {
1769 return;
1770 }
1771 #endif
1772 }
1773 #ifdef XTHREADS
1774 if (dpy->lock && dpy->lock->reply_bytes_left > 0)
1775 {
1776 dpy->lock->reply_bytes_left -= original_size;
1777 if (dpy->lock->reply_bytes_left == 0) {
1778 dpy->flags &= ~XlibDisplayReply;
1779 UnlockNextReplyReader(dpy);
1780 }
1781 }
1782 #endif /* XTHREADS*/
1783 }
1784
1785 /*
1786 * _XSend - Flush the buffer and send the client data. 32 bit word aligned
1787 * transmission is used, if size is not 0 mod 4, extra bytes are transmitted.
1788 * This routine may have to be reworked if int < long;
1789 */
1790 void
1791 _XSend (
1792 register Display *dpy,
1793 _Xconst char *data,
1794 register long size)
1795 {
1796 struct iovec iov[3];
1797 static char const pad[3] = {0, 0, 0};
1798 /* XText8 and XText16 require that the padding bytes be zero! */
1799
1800 long skip, dbufsize, padsize, total, todo;
1801 _XExtension *ext;
1802 #ifdef NX_TRANS_CHANGE
1803 int congestion;
1804 #endif
1805
1806 #ifdef NX_TRANS_SOCKET
1807 #ifdef NX_TRANS_DEBUG
1808 fprintf(stderr, "_XSend: Sending data with [%d] bytes to write.\n",
1809 (dpy->bufptr - dpy->buffer));
1810 #endif
1811 if (!size || (dpy->flags & XlibDisplayIOError))
1812 {
1813 if (dpy->flags & XlibDisplayIOError)
1814 {
1815 #ifdef NX_TRANS_DEBUG
1816 fprintf(stderr, "_XSend: Returning with I/O error detected.\n");
1817 #endif
1818 dpy->bufptr = dpy->buffer;
1819 dpy->last_req = (char *)&_dummy_request;
1820 }
1821
1822 return;
1823 }
1824 #else
1825 if (!size || (dpy->flags & XlibDisplayIOError)) return;
1826 #endif
1827 dbufsize = dpy->bufptr - dpy->buffer;
1828 #ifdef XTHREADS
1829 dpy->flags |= XlibDisplayWriting;
1830 /* make sure no one else can put in data */
1831 dpy->bufptr = dpy->bufmax;
1832 #endif
1833 padsize = -size & 3;
1834 for (ext = dpy->flushes; ext; ext = ext->next_flush) {
1835 (*ext->before_flush)(dpy, &ext->codes, dpy->buffer, dbufsize);
1836 (*ext->before_flush)(dpy, &ext->codes, (char *)data, size);
1837 if (padsize)
1838 (*ext->before_flush)(dpy, &ext->codes, pad, padsize);
1839 }
1840 skip = 0;
1841 todo = total = dbufsize + size + padsize;
1842
1843 /*
1844 * There are 3 pieces that may need to be written out:
1845 *
1846 * o whatever is in the display buffer
1847 * o the data passed in by the user
1848 * o any padding needed to 32bit align the whole mess
1849 *
1850 * This loop looks at all 3 pieces each time through. It uses skip
1851 * to figure out whether or not a given piece is needed.
1852 */
1853 while (total) {
1854 long before = skip; /* amount of whole thing written */
1855 long remain = todo; /* amount to try this time, <= total */
1856 int i = 0;
1857 long len;
1858
1859 /* You could be very general here and have "in" and "out" iovecs
1860 * and write a loop without using a macro, but what the heck. This
1861 * translates to:
1862 *
1863 * how much of this piece is new?
1864 * if more new then we are trying this time, clamp
1865 * if nothing new
1866 * then bump down amount already written, for next piece
1867 * else put new stuff in iovec, will need all of next piece
1868 *
1869 * Note that todo had better be at least 1 or else we'll end up
1870 * writing 0 iovecs.
1871 */
1872 #define InsertIOV(pointer, length) \
1873 len = (length) - before; \
1874 if (len > remain) \
1875 len = remain; \
1876 if (len <= 0) { \
1877 before = (-len); \
1878 } else { \
1879 iov[i].iov_len = len; \
1880 iov[i].iov_base = (pointer) + before; \
1881 i++; \
1882 remain -= len; \
1883 before = 0; \
1884 }
1885
1886 InsertIOV (dpy->buffer, dbufsize)
1887 InsertIOV ((char *)data, size)
1888 InsertIOV ((char *)pad, padsize)
1889
1890 ESET(0);
1891 if ((len = _X11TransWritev(dpy->trans_conn, iov, i)) >= 0) {
1892 #ifdef NX_TRANS_SOCKET
1893 if (_NXDisplayWriteFunction != NULL) {
1894 (*_NXDisplayWriteFunction)(dpy, len);
1895 }
1896 #ifdef NX_TRANS_CHANGE
1897 if (_NXDisplayCongestionFunction != NULL &&
1898 _X11TransSocketCongestionChange(dpy->trans_conn, &congestion) == 1) {
1899 (*_NXDisplayCongestionFunction)(dpy, congestion);
1900 }
1901 #endif
1902 #endif
1903 skip += len;
1904 total -= len;
1905 todo = total;
1906 } else if (ETEST()) {
1907 _XWaitForWritable(dpy
1908 #ifdef XTHREADS
1909 , NULL
1910 #endif
1911 );
1912 #ifdef SUNSYSV
1913 } else if (ECHECK(0)) {
1914 _XWaitForWritable(dpy
1915 #ifdef XTHREADS
1916 , NULL
1917 #endif
1918 );
1919 #endif
1920 #ifdef ESZTEST
1921 } else if (ESZTEST()) {
1922 if (todo > 1)
1923 todo >>= 1;
1924 else {
1925 _XWaitForWritable(dpy
1926 #ifdef XTHREADS
1927 , NULL
1928 #endif
1929 );
1930 }
1931 #endif
1932 #ifdef NX_TRANS_SOCKET
1933 } else if (!ECHECK(EINTR) ||
1934 (_NXDisplayErrorFunction != NULL &&
1935 (*_NXDisplayErrorFunction)(dpy, _XGetIOError(dpy)))) {
1936 _XIOError(dpy);
1937 return;
1938 }
1939 #else
1940 } else if (!ECHECK(EINTR)) {
1941 _XIOError(dpy);
1942 }
1943 #endif
1944 #ifdef NX_TRANS_SOCKET
1945 if (_XGetIOError(dpy)) {
1946 return;
1947 }
1948 #endif
1949 }
1950 dpy->last_req = (char *) & _dummy_request;
1951 _XSetSeqSyncFunction(dpy);
1952 dpy->bufptr = dpy->buffer;
1953 #ifdef XTHREADS
1954 dpy->flags &= ~XlibDisplayWriting;
1955 #endif
1956 return;
1957 }
1958
1959 static void
1960 _XGetMiscCode(
1961 register Display *dpy)
1962 {
1963 xQueryExtensionReply qrep;
1964 register xQueryExtensionReq *qreq;
1965 xXCMiscGetVersionReply vrep;
1966 register xXCMiscGetVersionReq *vreq;
1967
1968 if (dpy->xcmisc_opcode)
1969 return;
1970 GetReq(QueryExtension, qreq);
1971 qreq->nbytes = sizeof(XCMiscExtensionName) - 1;
1972 qreq->length += (qreq->nbytes+(unsigned)3)>>2;
1973 _XSend(dpy, XCMiscExtensionName, (long)qreq->nbytes);
1974 if (!_XReply (dpy, (xReply *)&qrep, 0, xTrue))
1975 dpy->xcmisc_opcode = -1;
1976 else {
1977 GetReq(XCMiscGetVersion, vreq);
1978 vreq->reqType = qrep.major_opcode;
1979 vreq->miscReqType = X_XCMiscGetVersion;
1980 vreq->majorVersion = XCMiscMajorVersion;
1981 vreq->minorVersion = XCMiscMinorVersion;
1982 if (!_XReply (dpy, (xReply *)&vrep, 0, xTrue))
1983 dpy->xcmisc_opcode = -1;
1984 else
1985 dpy->xcmisc_opcode = qrep.major_opcode;
1986 }
1987 }
1988
1989 void
1990 _XIDHandler(
1991 register Display *dpy)
1992 {
1993 xXCMiscGetXIDRangeReply grep;
1994 register xXCMiscGetXIDRangeReq *greq;
1995
1996 if (dpy->resource_max == dpy->resource_mask + 1) {
1997 _XGetMiscCode(dpy);
1998 if (dpy->xcmisc_opcode > 0) {
1999 GetReq(XCMiscGetXIDRange, greq);
2000 greq->reqType = dpy->xcmisc_opcode;
2001 greq->miscReqType = X_XCMiscGetXIDRange;
2002 if (_XReply (dpy, (xReply *)&grep, 0, xTrue) && grep.count) {
2003 dpy->resource_id = ((grep.start_id - dpy->resource_base) >>
2004 dpy->resource_shift);
2005 dpy->resource_max = dpy->resource_id;
2006 if (grep.count > 5)
2007 dpy->resource_max += grep.count - 6;
2008 dpy->resource_max <<= dpy->resource_shift;
2009 }
2010 sync_while_locked(dpy);
2011 }
2012 }
2013 }
2014
2015 /*
2016 * _XAllocID - resource ID allocation routine.
2017 */
2018 XID _XAllocID(
2019 register Display *dpy)
2020 {
2021 XID id;
2022
2023 id = dpy->resource_id << dpy->resource_shift;
2024 if (id >= dpy->resource_max) {
2025 _XSetPrivSyncFunction(dpy);
2026 dpy->resource_max = dpy->resource_mask + 1;
2027 }
2028 if (id <= dpy->resource_mask) {
2029 dpy->resource_id++;
2030 return (dpy->resource_base + id);
2031 }
2032 if (id != 0x10000000) {
2033 (void) fprintf(stderr,
2034 "Xlib: resource ID allocation space exhausted!\n");
2035 id = 0x10000000;
2036 dpy->resource_id = id >> dpy->resource_shift;
2037 }
2038 return id;
2039 }
2040
2041 /*
2042 * _XAllocIDs - multiple resource ID allocation routine.
2043 */
2044 void _XAllocIDs(
2045 register Display *dpy,
2046 XID *ids,
2047 int count)
2048 {
2049 XID id;
2050 int i;
2051 xXCMiscGetXIDListReply grep;
2052 register xXCMiscGetXIDListReq *greq;
2053
2054 id = dpy->resource_id << dpy->resource_shift;
2055 if (dpy->resource_max <= dpy->resource_mask &&
2056 id <= dpy->resource_mask &&
2057 (dpy->resource_max - id) > ((count - 1) << dpy->resource_shift)) {
2058 id += dpy->resource_base;
2059 for (i = 0; i < count; i++) {
2060 ids[i] = id;
2061 id += (1 << dpy->resource_shift);
2062 dpy->resource_id++;
2063 }
2064 return;
2065 }
2066 grep.count = 0;
2067 _XGetMiscCode(dpy);
2068 if (dpy->xcmisc_opcode > 0) {
2069 GetReq(XCMiscGetXIDList, greq);
2070 greq->reqType = dpy->xcmisc_opcode;
2071 greq->miscReqType = X_XCMiscGetXIDList;
2072 greq->count = count;
2073 if (_XReply(dpy, (xReply *)&grep, 0, xFalse) && grep.count) {
2074 _XRead32(dpy, (long *) ids, 4L * (long) (grep.count));
2075 for (i = 0; i < grep.count; i++) {
2076 id = (ids[i] - dpy->resource_base) >> dpy->resource_shift;
2077 if (id >= dpy->resource_id)
2078 dpy->resource_id = id;
2079 }
2080 if (id >= dpy->resource_max) {
2081 _XSetPrivSyncFunction(dpy);
2082 dpy->resource_max = dpy->resource_mask + 1;
2083 }
2084 }
2085 }
2086 for (i = grep.count; i < count; i++)
2087 ids[i] = XAllocID(dpy);
2088 }
2089 #endif /* !USE_XCB */
2090
2091 /*
2092 * The hard part about this is that we only get 16 bits from a reply.
2093 * We have three values that will march along, with the following invariant:
2094 * dpy->last_request_read <= rep->sequenceNumber <= dpy->request
2095 * We have to keep
2096 * dpy->request - dpy->last_request_read < 2^16
2097 * or else we won't know for sure what value to use in events. We do this
2098 * by forcing syncs when we get close.
2099 */
2100
2101 unsigned long
2102 _XSetLastRequestRead(
2103 register Display *dpy,
2104 register xGenericReply *rep)
2105 {
2106 register uint64_t newseq, lastseq;
2107
2108 lastseq = X_DPY_GET_LAST_REQUEST_READ(dpy);
2109 /*
2110 * KeymapNotify has no sequence number, but is always guaranteed
2111 * to immediately follow another event, except when generated via
2112 * SendEvent (hmmm).
2113 */
2114 if ((rep->type & 0x7f) == KeymapNotify)
2115 return(lastseq);
2116
2117 newseq = (lastseq & ~((uint64_t)0xffff)) | rep->sequenceNumber;
2118
2119 if (newseq < lastseq) {
2120 newseq += 0x10000;
2121 if (newseq > X_DPY_GET_REQUEST(dpy)) {
2122 #ifdef NX_TRANS_SOCKET
2123 if (_NXLostSequenceFunction != NULL)
2124 {
2125 (*_NXLostSequenceFunction)(dpy, newseq, X_DPY_GET_REQUEST(dpy),
2126 (unsigned int) rep->type);
2127 }
2128 else
2129 #endif /* #ifdef NX_TRANS_SOCKET */
2130 {
2131 (void) fprintf (stderr,
2132 "Xlib: sequence lost (0x%llx > 0x%llx) in reply type 0x%x!\n",
2133 (unsigned long long)newseq,
2134 (unsigned long long)(X_DPY_GET_REQUEST(dpy)),
2135 (unsigned int) rep->type);
2136 }
2137 newseq -= 0x10000;
2138 }
2139 }
2140
2141 X_DPY_SET_LAST_REQUEST_READ(dpy, newseq);
2142 return(newseq);
2143 }
2144
2145 #if !USE_XCB
2146 /*
2147 * _XReply - Wait for a reply packet and copy its contents into the
2148 * specified rep. Meanwhile we must handle error and event packets that
2149 * we may encounter.
2150 */
2151 Status
2152 _XReply (
2153 register Display *dpy,
2154 register xReply *rep,
2155 int extra, /* number of 32-bit words expected after the reply */
2156 Bool discard) /* should I discard data following "extra" words? */
2157 {
2158 /* Pull out the serial number now, so that (currently illegal) requests
2159 * generated by an error handler don't confuse us.
2160 */
2161 unsigned long cur_request = dpy->request;
2162 #ifdef XTHREADS
2163 struct _XCVList *cvl;
2164 #endif
2165 #ifdef NX_TRANS_DEBUG
2166 fprintf(stderr, "_XReply: Going to wait for an X reply.\n");
2167 #endif
2168
2169 #ifdef NX_TRANS_SOCKET
2170 if (dpy->flags & XlibDisplayIOError)
2171 {
2172 #ifdef NX_TRANS_DEBUG
2173 fprintf(stderr, "_XReply: Returning 0 with I/O error detected.\n");
2174 #endif
2175 return 0;
2176 }
2177 #else
2178 if (dpy->flags & XlibDisplayIOError)
2179 return 0;
2180 #endif
2181
2182 #ifdef XTHREADS
2183 /* create our condition variable and append to list */
2184 cvl = QueueReplyReaderLock(dpy);
2185 if (cvl) {
2186 cvl->buf = rep;
2187 if (dpy->lock->reply_awaiters == cvl && !dpy->lock->event_awaiters)
2188 dpy->lock->reply_first = True;
2189 }
2190
2191 #ifdef XTHREADS_DEBUG
2192 printf("_XReply called in thread %x, adding %x to cvl\n",
2193 XThread_Self(), cvl);
2194 #endif
2195
2196 #ifdef NX_TRANS_DEBUG
2197 fprintf(stderr, "_XReply: Going to flush the display buffer.\n");
2198 #endif
2199 _XFlushInt(dpy, cvl ? cvl->cv : NULL);
2200 /* if it is not our turn to read a reply off the wire,
2201 * wait til we're at head of list. if there is an event waiter,
2202 * and our reply hasn't been read, they'll be in select and will
2203 * hand control back to us next.
2204 */
2205 if(dpy->lock &&
2206 (dpy->lock->reply_awaiters != cvl || !dpy->lock->reply_first)) {
2207 ConditionWait(dpy, cvl->cv);
2208 }
2209 dpy->flags |= XlibDisplayReply;
2210 #else /* XTHREADS else */
2211 _XFlush(dpy);
2212 #endif
2213
2214 #ifdef NX_TRANS_SOCKET
2215 /*
2216 * We are going to block waiting for the remote X server. Be sure
2217 * that the proxy has flushed all the data.
2218 */
2219
2220 #ifdef NX_TRANS_TEST
2221 fprintf(stderr, "_XReply: Requesting a flush of the NX transport.\n");
2222 #endif
2223 NXTransFlush(dpy->fd);
2224 #endif
2225
2226 for (;;) {
2227 #ifdef XTHREADS
2228 /* Did another thread's _XReadEvents get our reply by accident? */
2229 if (!dpy->lock || !dpy->lock->reply_was_read)
2230 #endif
2231 (void) _XRead(dpy, (char *)rep, (long)SIZEOF(xReply));
2232 #ifdef XTHREADS
2233 if (dpy->lock)
2234 dpy->lock->reply_was_read = False;
2235 #endif
2236
2237 switch ((int)rep->generic.type) {
2238
2239 case X_Reply:
2240 /* Reply received. Fast update for synchronous replies,
2241 * but deal with multiple outstanding replies.
2242 */
2243 if (rep->generic.sequenceNumber == (cur_request & 0xffff))
2244 dpy->last_request_read = cur_request;
2245 else {
2246 int pend = SIZEOF(xReply);
2247 if (_XAsyncReply(dpy, rep, (char *)rep, &pend, False)
2248 != (char *)rep)
2249 continue;
2250 }
2251 if (extra <= rep->generic.length) {
2252 if (extra > 0)
2253 /*
2254 * Read the extra data into storage immediately
2255 * following the GenericReply structure.
2256 */
2257 (void) _XRead (dpy, (char *) (NEXTPTR(rep,xReply)),
2258 ((long)extra) << 2);
2259 if (discard) {
2260 if (extra < rep->generic.length)
2261 _XEatData(dpy, (rep->generic.length - extra) << 2);
2262 }
2263 #ifdef XTHREADS
2264 if (dpy->lock) {
2265 if (discard) {
2266 dpy->lock->reply_bytes_left = 0;
2267 } else {
2268 dpy->lock->reply_bytes_left =
2269 (rep->generic.length - extra) << 2;
2270 }
2271 if (dpy->lock->reply_bytes_left == 0) {
2272 dpy->flags &= ~XlibDisplayReply;
2273 UnlockNextReplyReader(dpy);
2274 }
2275 } else
2276 dpy->flags &= ~XlibDisplayReply;
2277 #endif
2278 return 1;
2279 }
2280 /*
2281 *if we get here, then extra > rep->generic.length--meaning we
2282 * read a reply that's shorter than we expected. This is an
2283 * error, but we still need to figure out how to handle it...
2284 */
2285 (void) _XRead (dpy, (char *) (NEXTPTR(rep,xReply)),
2286 ((long) rep->generic.length) << 2);
2287 dpy->flags &= ~XlibDisplayReply;
2288 UnlockNextReplyReader(dpy);
2289 #ifdef NX_TRANS_SOCKET
2290 /*
2291 * The original code has provision for returning
2292 * already.
2293 */
2294 #endif
2295 _XIOError (dpy);
2296 return (0);
2297
2298 case X_Error:
2299 {
2300 register _XExtension *ext;
2301 register Bool ret = False;
2302 int ret_code;
2303 xError *err = (xError *) rep;
2304 unsigned long serial;
2305
2306 dpy->flags &= ~XlibDisplayReply;
2307 serial = _XSetLastRequestRead(dpy, (xGenericReply *)rep);
2308 if (serial == cur_request)
2309 /* do not die on "no such font", "can't allocate",
2310 "can't grab" failures */
2311 switch ((int)err->errorCode) {
2312 case BadName:
2313 switch (err->majorCode) {
2314 case X_LookupColor:
2315 case X_AllocNamedColor:
2316 UnlockNextReplyReader(dpy);
2317 return(0);
2318 }
2319 break;
2320 case BadFont:
2321 if (err->majorCode == X_QueryFont) {
2322 UnlockNextReplyReader(dpy);
2323 return (0);
2324 }
2325 break;
2326 case BadAlloc:
2327 case BadAccess:
2328 UnlockNextReplyReader(dpy);
2329 return (0);
2330 }
2331 /*
2332 * we better see if there is an extension who may
2333 * want to suppress the error.
2334 */
2335 for (ext = dpy->ext_procs; !ret && ext; ext = ext->next) {
2336 if (ext->error)
2337 ret = (*ext->error)(dpy, err, &ext->codes, &ret_code);
2338 }
2339 if (!ret) {
2340 _XError(dpy, err);
2341 ret_code = 0;
2342 }
2343 if (serial == cur_request) {
2344 UnlockNextReplyReader(dpy);
2345 return(ret_code);
2346 }
2347
2348 } /* case X_Error */
2349 break;
2350 default:
2351 _XEnq(dpy, (xEvent *) rep);
2352 #ifdef XTHREADS
2353 if (dpy->lock && dpy->lock->event_awaiters)
2354 ConditionSignal(dpy, dpy->lock->event_awaiters->cv);
2355 #endif
2356 break;
2357 }
2358 #ifdef NX_TRANS_SOCKET
2359 if (_XGetIOError(dpy)) {
2360 UnlockNextReplyReader(dpy);
2361 return 0;
2362 }
2363 #endif
2364 }
2365 }
2366
2367 static char *
2368 _XAsyncReply(
2369 Display *dpy,
2370 register xReply *rep,
2371 char *buf,
2372 register int *lenp,
2373 Bool discard)
2374 {
2375 register _XAsyncHandler *async, *next;
2376 register int len;
2377 register Bool consumed = False;
2378 char *nbuf;
2379
2380 (void) _XSetLastRequestRead(dpy, &rep->generic);
2381 len = SIZEOF(xReply) + (rep->generic.length << 2);
2382 if (len < SIZEOF(xReply)) {
2383 #ifdef NX_TRANS_SOCKET
2384
2385 /*
2386 * The original code has provision
2387 * for returning already.
2388 */
2389
2390 #endif
2391 _XIOError (dpy);
2392 buf += *lenp;
2393 *lenp = 0;
2394 return buf;
2395 }
2396
2397 for (async = dpy->async_handlers; async; async = next) {
2398 next = async->next;
2399 if ((consumed = (*async->handler)(dpy, rep, buf, *lenp, async->data)))
2400 break;
2401 }
2402 if (!consumed) {
2403 if (!discard)
2404 return buf;
2405 (void) fprintf(stderr,
2406 "Xlib: unexpected async reply (sequence 0x%lx)!\n",
2407 dpy->last_request_read);
2408 #ifdef XTHREADS
2409 #ifdef XTHREADS_DEBUG
2410 printf("thread %x, unexpected async reply\n", XThread_Self());
2411 #endif
2412 #endif
2413 if (len > *lenp)
2414 _XEatData(dpy, len - *lenp);
2415 }
2416 if (len < SIZEOF(xReply))
2417 {
2418 #ifdef NX_TRANS_SOCKET
2419
2420 /*
2421 * The original code has provision for returning already.
2422 */
2423
2424 #endif
2425 _XIOError (dpy);
2426 buf += *lenp;
2427 *lenp = 0;
2428 return buf;
2429 }
2430 if (len >= *lenp) {
2431 buf += *lenp;
2432 *lenp = 0;
2433 return buf;
2434 }
2435 *lenp -= len;
2436 buf += len;
2437 len = *lenp;
2438 nbuf = buf;
2439 while (len > SIZEOF(xReply)) {
2440 if (*buf == X_Reply)
2441 return nbuf;
2442 buf += SIZEOF(xReply);
2443 len -= SIZEOF(xReply);
2444 }
2445 if (len > 0 && len < SIZEOF(xReply)) {
2446 buf = nbuf;
2447 len = SIZEOF(xReply) - len;
2448 nbuf -= len;
2449 memmove(nbuf, buf, *lenp);
2450 (void) _XRead(dpy, nbuf + *lenp, (long)len);
2451 *lenp += len;
2452 }
2453 return nbuf;
2454 }
2455 #endif /* !USE_XCB */
2456
2457 /*
2458 * Support for internal connections, such as an IM might use.
2459 * By Stephen Gildea, X Consortium, September 1993
2460 */
2461
2462 /* _XRegisterInternalConnection
2463 * Each IM (or Xlib extension) that opens a file descriptor that Xlib should
2464 * include in its select/poll mask must call this function to register the
2465 * fd with Xlib. Any XConnectionWatchProc registered by XAddConnectionWatch
2466 * will also be called.
2467 *
2468 * Whenever Xlib detects input available on fd, it will call callback
2469 * with call_data to process it. If non-Xlib code calls select/poll
2470 * and detects input available, it must call XProcessInternalConnection,
2471 * which will call the associated callback.
2472 *
2473 * Non-Xlib code can learn about these additional fds by calling
2474 * XInternalConnectionNumbers or, more typically, by registering
2475 * a XConnectionWatchProc with XAddConnectionWatch
2476 * to be called when fds are registered or unregistered.
2477 *
2478 * Returns True if registration succeeded, False if not, typically
2479 * because could not allocate memory.
2480 * Assumes Display locked when called.
2481 */
2482 Status
2483 _XRegisterInternalConnection(
2484 Display* dpy,
2485 int fd,
2486 _XInternalConnectionProc callback,
2487 XPointer call_data
2488 )
2489 {
2490 struct _XConnectionInfo *new_conni, **iptr;
2491 struct _XConnWatchInfo *watchers;
2492 XPointer *wd;
2493
2494 #ifdef NX_TRANS_DEBUG
2495 fprintf(stderr, "_XRegisterInternalConnection: Got called.\n");
2496 #endif
2497 new_conni = Xmalloc(sizeof(struct _XConnectionInfo));
2498 if (!new_conni)
2499 return 0;
2500 new_conni->watch_data = Xmallocarray(dpy->watcher_count, sizeof(XPointer));
2501 if (!new_conni->watch_data) {
2502 Xfree(new_conni);
2503 return 0;
2504 }
2505 new_conni->fd = fd;
2506 new_conni->read_callback = callback;
2507 new_conni->call_data = call_data;
2508 new_conni->next = NULL;
2509 /* link new structure onto end of list */
2510 for (iptr = &dpy->im_fd_info; *iptr; iptr = &(*iptr)->next)
2511 ;
2512 *iptr = new_conni;
2513 dpy->im_fd_length++;
2514 _XPollfdCacheAdd(dpy, fd);
2515
2516 for (watchers=dpy->conn_watchers, wd=new_conni->watch_data;
2517 watchers;
2518 watchers=watchers->next, wd++) {
2519 *wd = NULL; /* for cleanliness */
2520 (*watchers->fn) (dpy, watchers->client_data, fd, True, wd);
2521 }
2522
2523 return 1;
2524 }
2525
2526 /* _XUnregisterInternalConnection
2527 * Each IM (or Xlib extension) that closes a file descriptor previously
2528 * registered with _XRegisterInternalConnection must call this function.
2529 * Any XConnectionWatchProc registered by XAddConnectionWatch
2530 * will also be called.
2531 *
2532 * Assumes Display locked when called.
2533 */
2534 void
2535 _XUnregisterInternalConnection(
2536 Display* dpy,
2537 int fd
2538 )
2539 {
2540 struct _XConnectionInfo *info_list, **prev;
2541 struct _XConnWatchInfo *watch;
2542 XPointer *wd;
2543
2544 #ifdef NX_TRANS_DEBUG
2545 fprintf(stderr, "_XUnregisterInternalConnection: Got called.\n");
2546 #endif
2547 for (prev = &dpy->im_fd_info; (info_list = *prev);
2548 prev = &info_list->next) {
2549 if (info_list->fd == fd) {
2550 *prev = info_list->next;
2551 dpy->im_fd_length--;
2552 for (watch=dpy->conn_watchers, wd=info_list->watch_data;
2553 watch;
2554 watch=watch->next, wd++) {
2555 (*watch->fn) (dpy, watch->client_data, fd, False, wd);
2556 }
2557 Xfree (info_list->watch_data);
2558 Xfree (info_list);
2559 break;
2560 }
2561 }
2562 _XPollfdCacheDel(dpy, fd);
2563 }
2564
2565 /* XInternalConnectionNumbers
2566 * Returns an array of fds and an array of corresponding call data.
2567 * Typically a XConnectionWatchProc registered with XAddConnectionWatch
2568 * will be used instead of this function to discover
2569 * additional fds to include in the select/poll mask.
2570 *
2571 * The list is allocated with Xmalloc and should be freed by the caller
2572 * with Xfree;
2573 */
2574 Status
2575 XInternalConnectionNumbers(
2576 Display *dpy,
2577 int **fd_return,
2578 int *count_return
2579 )
2580 {
2581 int count;
2582 struct _XConnectionInfo *info_list;
2583 int *fd_list;
2584
2585 #ifdef NX_TRANS_DEBUG
2586 fprintf(stderr, "XInternalConnectionNumbers: Got called.\n");
2587 #endif
2588 LockDisplay(dpy);
2589 count = 0;
2590 for (info_list=dpy->im_fd_info; info_list; info_list=info_list->next)
2591 count++;
2592 fd_list = Xmallocarray (count, sizeof(int));
2593 if (!fd_list) {
2594 UnlockDisplay(dpy);
2595 return 0;
2596 }
2597 count = 0;
2598 for (info_list=dpy->im_fd_info; info_list; info_list=info_list->next) {
2599 fd_list[count] = info_list->fd;
2600 count++;
2601 }
2602 UnlockDisplay(dpy);
2603
2604 *fd_return = fd_list;
2605 *count_return = count;
2606 return 1;
2607 }
2608
2609 void _XProcessInternalConnection(
2610 Display *dpy,
2611 struct _XConnectionInfo *conn_info)
2612 {
2613 dpy->flags |= XlibDisplayProcConni;
2614 #if defined(XTHREADS) && !USE_XCB
2615 if (dpy->lock) {
2616 /* check cache to avoid call to thread_self */
2617 if (xthread_have_id(dpy->lock->reading_thread))
2618 dpy->lock->conni_thread = dpy->lock->reading_thread;
2619 else
2620 dpy->lock->conni_thread = XThread_Self();
2621 }
2622 #endif /* XTHREADS && !USE_XCB */
2623 UnlockDisplay(dpy);
2624 (*conn_info->read_callback) (dpy, conn_info->fd, conn_info->call_data);
2625 LockDisplay(dpy);
2626 #if defined(XTHREADS) && !USE_XCB
2627 if (dpy->lock)
2628 xthread_clear_id(dpy->lock->conni_thread);
2629 #endif /* XTHREADS && !USE_XCB */
2630 dpy->flags &= ~XlibDisplayProcConni;
2631 }
2632
2633 /* XProcessInternalConnection
2634 * Call the _XInternalConnectionProc registered by _XRegisterInternalConnection
2635 * for this fd.
2636 * The Display is NOT locked during the call.
2637 */
2638 void
2639 XProcessInternalConnection(
2640 Display* dpy,
2641 int fd
2642 )
2643 {
2644 struct _XConnectionInfo *info_list;
2645
2646 #ifdef NX_TRANS_DEBUG
2647 fprintf(stderr, "XProcessInternalConnection: Got called.\n");
2648 #endif
2649
2650 LockDisplay(dpy);
2651 for (info_list=dpy->im_fd_info; info_list; info_list=info_list->next) {
2652 if (info_list->fd == fd) {
2653 _XProcessInternalConnection(dpy, info_list);
2654 break;
2655 }
2656 }
2657 UnlockDisplay(dpy);
2658 }
2659
2660 /* XAddConnectionWatch
2661 * Register a callback to be called whenever _XRegisterInternalConnection
2662 * or _XUnregisterInternalConnection is called.
2663 * Callbacks are called with the Display locked.
2664 * If any connections are already registered, the callback is immediately
2665 * called for each of them.
2666 */
2667 Status
2668 XAddConnectionWatch(
2669 Display* dpy,
2670 XConnectionWatchProc callback,
2671 XPointer client_data
2672 )
2673 {
2674 struct _XConnWatchInfo *new_watcher, **wptr;
2675 struct _XConnectionInfo *info_list;
2676 XPointer *wd_array;
2677
2678 #ifdef NX_TRANS_DEBUG
2679 fprintf(stderr, "XAddConnectionWatch: Got called.\n");
2680 #endif
2681 LockDisplay(dpy);
2682
2683 /* allocate new watch data */
2684 for (info_list=dpy->im_fd_info; info_list; info_list=info_list->next) {
2685 wd_array = Xreallocarray(info_list->watch_data,
2686 dpy->watcher_count + 1, sizeof(XPointer));
2687 if (!wd_array) {
2688 UnlockDisplay(dpy);
2689 return 0;
2690 }
2691 info_list->watch_data = wd_array;
2692 wd_array[dpy->watcher_count] = NULL; /* for cleanliness */
2693 }
2694
2695 new_watcher = Xmalloc(sizeof(struct _XConnWatchInfo));
2696 if (!new_watcher) {
2697 UnlockDisplay(dpy);
2698 return 0;
2699 }
2700 new_watcher->fn = callback;
2701 new_watcher->client_data = client_data;
2702 new_watcher->next = NULL;
2703
2704 /* link new structure onto end of list */
2705 for (wptr = &dpy->conn_watchers; *wptr; wptr = &(*wptr)->next)
2706 ;
2707 *wptr = new_watcher;
2708 dpy->watcher_count++;
2709
2710 /* call new watcher on all currently registered fds */
2711 for (info_list=dpy->im_fd_info; info_list; info_list=info_list->next) {
2712 (*callback) (dpy, client_data, info_list->fd, True,
2713 info_list->watch_data + dpy->watcher_count - 1);
2714 }
2715
2716 UnlockDisplay(dpy);
2717 return 1;
2718 }
2719
2720 /* XRemoveConnectionWatch
2721 * Unregister a callback registered by XAddConnectionWatch.
2722 * Both callback and client_data must match what was passed to
2723 * XAddConnectionWatch.
2724 */
2725 void
2726 XRemoveConnectionWatch(
2727 Display* dpy,
2728 XConnectionWatchProc callback,
2729 XPointer client_data
2730 )
2731 {
2732 struct _XConnWatchInfo *watch;
2733 struct _XConnWatchInfo *previous = NULL;
2734 struct _XConnectionInfo *conni;
2735 int counter = 0;
2736
2737 #ifdef NX_TRANS_DEBUG
2738 fprintf(stderr, "XRemoveConnectionWatch: Got called.\n");
2739 #endif
2740 LockDisplay(dpy);
2741 for (watch=dpy->conn_watchers; watch; watch=watch->next) {
2742 if (watch->fn == callback && watch->client_data == client_data) {
2743 if (previous)
2744 previous->next = watch->next;
2745 else
2746 dpy->conn_watchers = watch->next;
2747 Xfree (watch);
2748 dpy->watcher_count--;
2749 /* remove our watch_data for each connection */
2750 for (conni=dpy->im_fd_info; conni; conni=conni->next) {
2751 /* don't bother realloc'ing; these arrays are small anyway */
2752 /* overlapping */
2753 memmove(conni->watch_data+counter,
2754 conni->watch_data+counter+1,
2755 dpy->watcher_count - counter);
2756 }
2757 break;
2758 }
2759 previous = watch;
2760 counter++;
2761 }
2762 UnlockDisplay(dpy);
2763 }
2764
2765 /* end of internal connections support */
2766
2767
2768 #if !USE_XCB
2769 /* Read and discard "n" 8-bit bytes of data */
2770
2771 void _XEatData(
2772 Display *dpy,
2773 register unsigned long n)
2774 {
2775 #define SCRATCHSIZE 2048
2776 char buf[SCRATCHSIZE];
2777
2778 #ifdef NX_TRANS_DEBUG
2779 fprintf(stderr, "_XEatData: Going to eat [%ld] bytes of data from descriptor [%d].\n",
2780 n, dpy->fd);
2781 #endif
2782 while (n > 0) {
2783 register long bytes_read = (n > SCRATCHSIZE) ? SCRATCHSIZE : n;
2784 (void) _XRead (dpy, buf, bytes_read);
2785 n -= bytes_read;
2786 }
2787 #undef SCRATCHSIZE
2788 }
2789
2790 /*
2791 Port from libXfixes commit
2792 b031e3b60fa1af9e49449f23d4a84395868be3ab We need this here to
2793 enable linking of current libXrender against libNX_X11 instead of
2794 the system's libX11
2795
2796 The original implementation of this function (libX11 commit
2797 9f5d83706543696fc944c1835a403938c06f2cc5) uses xcb stuff which we
2798 do not have in libNX_X11. So we take a workaround from another
2799 lib. This workaround had been implemented temporarily in a couple
2800 of X libs, see e.g. https://lists.x.org/archives/xorg-devel/2013-July/036763.html.
2801 */
2802 #include <nx-X11/Xmd.h> /* for LONG64 on 64-bit platforms */
2803 #include <limits.h>
2804
2805 void _XEatDataWords(Display *dpy, unsigned long n)
2806 {
2807 #ifndef LONG64
2808 if (n >= (ULONG_MAX >> 2))
2809 _XIOError(dpy);
2810 #endif
2811 _XEatData (dpy, n << 2);
2812 }
2813 #endif /* !USE_XCB */
2814
2815 /* Cookie jar implementation
2816 dpy->cookiejar is a linked list. _XEnq receives the events but leaves
2817 them in the normal EQ. _XStoreEvent returns the cookie event (minus
2818 data pointer) and adds it to the cookiejar. _XDeq just removes
2819 the entry like any other event but resets the data pointer for
2820 cookie events (to avoid double-free, the memory is re-used by Xlib).
2821
2822 _XFetchEventCookie (called from XGetEventData) removes a cookie from the
2823 jar. _XFreeEventCookies removes all unclaimed cookies from the jar
2824 (called by XNextEvent).
2825
2826 _XFreeDisplayStructure calls _XFreeEventCookies for each cookie in the
2827 normal EQ.
2828 */
2829
2830 #include "utlist.h"
2831 struct stored_event {
2832 XGenericEventCookie ev;
2833 struct stored_event *prev;
2834 struct stored_event *next;
2835 };
2836
2837 Bool
2838 _XIsEventCookie(Display *dpy, XEvent *ev)
2839 {
2840 return (ev->xcookie.type == GenericEvent &&
2841 dpy->generic_event_vec[ev->xcookie.extension & 0x7F] != NULL);
2842 }
2843
2844 /**
2845 * Free all events in the event list.
2846 */
2847 void
2848 _XFreeEventCookies(Display *dpy)
2849 {
2850 struct stored_event **head, *e, *tmp;
2851
2852 if (!dpy->cookiejar)
2853 return;
2854
2855 head = (struct stored_event**)&dpy->cookiejar;
2856
2857 DL_FOREACH_SAFE(*head, e, tmp) {
2858 XFree(e->ev.data);
2859 XFree(e);
2860 }
2861 dpy->cookiejar = NULL;
2862 }
2863
2864 /**
2865 * Add an event to the display's event list. This event must be freed on the
2866 * next call to XNextEvent().
2867 */
2868 void
2869 _XStoreEventCookie(Display *dpy, XEvent *event)
2870 {
2871 XGenericEventCookie* cookie = &event->xcookie;
2872 struct stored_event **head, *add;
2873
2874 if (!_XIsEventCookie(dpy, event))
2875 return;
2876
2877 head = (struct stored_event**)(&dpy->cookiejar);
2878
2879 add = Xmalloc(sizeof(struct stored_event));
2880 if (!add) {
2881 ESET(ENOMEM);
2882 _XIOError(dpy);
2883 return;
2884 }
2885 add->ev = *cookie;
2886 DL_APPEND(*head, add);
2887 cookie->data = NULL; /* don't return data yet, must be claimed */
2888 }
2889
2890 /**
2891 * Return the event with the given cookie and remove it from the list.
2892 */
2893 Bool
2894 _XFetchEventCookie(Display *dpy, XGenericEventCookie* ev)
2895 {
2896 Bool ret = False;
2897 struct stored_event **head, *event;
2898 head = (struct stored_event**)&dpy->cookiejar;
2899
2900 if (!_XIsEventCookie(dpy, (XEvent*)ev))
2901 return ret;
2902
2903 DL_FOREACH(*head, event) {
2904 if (event->ev.cookie == ev->cookie &&
2905 event->ev.extension == ev->extension &&
2906 event->ev.evtype == ev->evtype) {
2907 *ev = event->ev;
2908 DL_DELETE(*head, event);
2909 Xfree(event);
2910 ret = True;
2911 break;
2912 }
2913 }
2914
2915 return ret;
2916 }
2917
2918 Bool
2919 _XCopyEventCookie(Display *dpy, XGenericEventCookie *in, XGenericEventCookie *out)
2920 {
2921 Bool ret = False;
2922 int extension;
2923
2924 if (!_XIsEventCookie(dpy, (XEvent*)in) || !out)
2925 return ret;
2926
2927 extension = in->extension & 0x7F;
2928
2929 if (!dpy->generic_event_copy_vec[extension])
2930 return ret;
2931
2932 ret = ((*dpy->generic_event_copy_vec[extension])(dpy, in, out));
2933 out->cookie = ret ? ++dpy->next_cookie : 0;
2934 return ret;
2935 }
2936
2937
2938 /*
2939 * _XEnq - Place event packets on the display's queue.
2940 * note that no squishing of move events in V11, since there
2941 * is pointer motion hints....
2942 */
2943 void _XEnq(
2944 register Display *dpy,
2945 register xEvent *event)
2946 {
2947 register _XQEvent *qelt;
2948 int type, extension;
2949
2950 if ((qelt = dpy->qfree)) {
2951 /* If dpy->qfree is non-NULL do this, else malloc a new one. */
2952 dpy->qfree = qelt->next;
2953 }
2954 else if ((qelt = Xmalloc(sizeof(_XQEvent))) == NULL) {
2955 /* Malloc call failed! */
2956 ESET(ENOMEM);
2957 _XIOError(dpy);
2958 return;
2959 }
2960 qelt->next = NULL;
2961
2962 type = event->u.u.type & 0177;
2963 extension = ((xGenericEvent*)event)->extension;
2964
2965 qelt->event.type = type;
2966 /* If an extension has registered a generic_event_vec handler, then
2967 * it can handle event cookies. Otherwise, proceed with the normal
2968 * event handlers.
2969 *
2970 * If the generic_event_vec is called, qelt->event is a event cookie
2971 * with the data pointer and the "free" pointer set. Data pointer is
2972 * some memory allocated by the extension.
2973 */
2974 if (type == GenericEvent && dpy->generic_event_vec[extension & 0x7F]) {
2975 XGenericEventCookie *cookie = &qelt->event.xcookie;
2976 (*dpy->generic_event_vec[extension & 0x7F])(dpy, cookie, event);
2977 cookie->cookie = ++dpy->next_cookie;
2978
2979 qelt->qserial_num = dpy->next_event_serial_num++;
2980 if (dpy->tail) dpy->tail->next = qelt;
2981 else dpy->head = qelt;
2982
2983 dpy->tail = qelt;
2984 dpy->qlen++;
2985 } else if ((*dpy->event_vec[type])(dpy, &qelt->event, event)) {
2986 qelt->qserial_num = dpy->next_event_serial_num++;
2987 if (dpy->tail) dpy->tail->next = qelt;
2988 else dpy->head = qelt;
2989
2990 dpy->tail = qelt;
2991 dpy->qlen++;
2992 } else {
2993 /* ignored, or stashed away for many-to-one compression */
2994 qelt->next = dpy->qfree;
2995 dpy->qfree = qelt;
2996 }
2997 }
2998
2999 /*
3000 * _XDeq - Remove event packet from the display's queue.
3001 */
3002 void _XDeq(
3003 register Display *dpy,
3004 register _XQEvent *prev, /* element before qelt */
3005 register _XQEvent *qelt) /* element to be unlinked */
3006 {
3007 if (prev) {
3008 if ((prev->next = qelt->next) == NULL)
3009 dpy->tail = prev;
3010 } else {
3011 /* no prev, so removing first elt */
3012 if ((dpy->head = qelt->next) == NULL)
3013 dpy->tail = NULL;
3014 }
3015 qelt->qserial_num = 0;
3016 qelt->next = dpy->qfree;
3017 dpy->qfree = qelt;
3018 dpy->qlen--;
3019
3020 if (_XIsEventCookie(dpy, &qelt->event)) {
3021 XGenericEventCookie* cookie = &qelt->event.xcookie;
3022 /* dpy->qfree is re-used, reset memory to avoid double free on
3023 * _XFreeDisplayStructure */
3024 cookie->data = NULL;
3025 }
3026 }
3027
3028 /*
3029 * EventToWire in separate file in that often not needed.
3030 */
3031
3032 /*ARGSUSED*/
3033 Bool
3034 _XUnknownWireEvent(
3035 register Display *dpy, /* pointer to display structure */
3036 register XEvent *re, /* pointer to where event should be reformatted */
3037 register xEvent *event) /* wire protocol event */
3038 {
3039 #ifdef notdef
3040 (void) fprintf(stderr,
3041 "Xlib: unhandled wire event! event number = %d, display = %x\n.",
3042 event->u.u.type, dpy);
3043 #endif
3044 return(False);
3045 }
3046
3047 Bool
3048 _XUnknownWireEventCookie(
3049 Display *dpy, /* pointer to display structure */
3050 XGenericEventCookie *re, /* pointer to where event should be reformatted */
3051 xEvent *event) /* wire protocol event */
3052 {
3053 #ifdef notdef
3054 fprintf(stderr,
3055 "Xlib: unhandled wire cookie event! extension number = %d, display = %x\n.",
3056 ((xGenericEvent*)event)->extension, dpy);
3057 #endif
3058 return(False);
3059 }
3060
3061 Bool
3062 _XUnknownCopyEventCookie(
3063 Display *dpy, /* pointer to display structure */
3064 XGenericEventCookie *in, /* source */
3065 XGenericEventCookie *out) /* destination */
3066 {
3067 #ifdef notdef
3068 fprintf(stderr,
3069 "Xlib: unhandled cookie event copy! extension number = %d, display = %x\n.",
3070 in->extension, dpy);
3071 #endif
3072 return(False);
3073 }
3074
3075 /*ARGSUSED*/
3076 Status
3077 _XUnknownNativeEvent(
3078 register Display *dpy, /* pointer to display structure */
3079 register XEvent *re, /* pointer to where event should be reformatted */
3080 register xEvent *event) /* wire protocol event */
3081 {
3082 #ifdef notdef
3083 (void) fprintf(stderr,
3084 "Xlib: unhandled native event! event number = %d, display = %x\n.",
3085 re->type, dpy);
3086 #endif
3087 return(0);
3088 }
3089 /*
3090 * reformat a wire event into an XEvent structure of the right type.
3091 */
3092 Bool
3093 _XWireToEvent(
3094 register Display *dpy, /* pointer to display structure */
3095 register XEvent *re, /* pointer to where event should be reformatted */
3096 register xEvent *event) /* wire protocol event */
3097 {
3098
3099 re->type = event->u.u.type & 0x7f;
3100 ((XAnyEvent *)re)->serial = _XSetLastRequestRead(dpy,
3101 (xGenericReply *)event);
3102 ((XAnyEvent *)re)->send_event = ((event->u.u.type & 0x80) != 0);
3103 ((XAnyEvent *)re)->display = dpy;
3104
3105 /* Ignore the leading bit of the event type since it is set when a
3106 client sends an event rather than the server. */
3107
3108 switch (event-> u.u.type & 0177) {
3109 case KeyPress:
3110 case KeyRelease:
3111 {
3112 register XKeyEvent *ev = (XKeyEvent*) re;
3113 ev->root = event->u.keyButtonPointer.root;
3114 ev->window = event->u.keyButtonPointer.event;
3115 ev->subwindow = event->u.keyButtonPointer.child;
3116 ev->time = event->u.keyButtonPointer.time;
3117 ev->x = cvtINT16toInt(event->u.keyButtonPointer.eventX);
3118 ev->y = cvtINT16toInt(event->u.keyButtonPointer.eventY);
3119 ev->x_root = cvtINT16toInt(event->u.keyButtonPointer.rootX);
3120 ev->y_root = cvtINT16toInt(event->u.keyButtonPointer.rootY);
3121 ev->state = event->u.keyButtonPointer.state;
3122 ev->same_screen = event->u.keyButtonPointer.sameScreen;
3123 ev->keycode = event->u.u.detail;
3124 }
3125 break;
3126 case ButtonPress:
3127 case ButtonRelease:
3128 {
3129 register XButtonEvent *ev = (XButtonEvent *) re;
3130 ev->root = event->u.keyButtonPointer.root;
3131 ev->window = event->u.keyButtonPointer.event;
3132 ev->subwindow = event->u.keyButtonPointer.child;
3133 ev->time = event->u.keyButtonPointer.time;
3134 ev->x = cvtINT16toInt(event->u.keyButtonPointer.eventX);
3135 ev->y = cvtINT16toInt(event->u.keyButtonPointer.eventY);
3136 ev->x_root = cvtINT16toInt(event->u.keyButtonPointer.rootX);
3137 ev->y_root = cvtINT16toInt(event->u.keyButtonPointer.rootY);
3138 ev->state = event->u.keyButtonPointer.state;
3139 ev->same_screen = event->u.keyButtonPointer.sameScreen;
3140 ev->button = event->u.u.detail;
3141 }
3142 break;
3143 case MotionNotify:
3144 {
3145 register XMotionEvent *ev = (XMotionEvent *)re;
3146 ev->root = event->u.keyButtonPointer.root;
3147 ev->window = event->u.keyButtonPointer.event;
3148 ev->subwindow = event->u.keyButtonPointer.child;
3149 ev->time = event->u.keyButtonPointer.time;
3150 ev->x = cvtINT16toInt(event->u.keyButtonPointer.eventX);
3151 ev->y = cvtINT16toInt(event->u.keyButtonPointer.eventY);
3152 ev->x_root = cvtINT16toInt(event->u.keyButtonPointer.rootX);
3153 ev->y_root = cvtINT16toInt(event->u.keyButtonPointer.rootY);
3154 ev->state = event->u.keyButtonPointer.state;
3155 ev->same_screen = event->u.keyButtonPointer.sameScreen;
3156 ev->is_hint = event->u.u.detail;
3157 }
3158 break;
3159 case EnterNotify:
3160 case LeaveNotify:
3161 {
3162 register XCrossingEvent *ev = (XCrossingEvent *) re;
3163 ev->root = event->u.enterLeave.root;
3164 ev->window = event->u.enterLeave.event;
3165 ev->subwindow = event->u.enterLeave.child;
3166 ev->time = event->u.enterLeave.time;
3167 ev->x = cvtINT16toInt(event->u.enterLeave.eventX);
3168 ev->y = cvtINT16toInt(event->u.enterLeave.eventY);
3169 ev->x_root = cvtINT16toInt(event->u.enterLeave.rootX);
3170 ev->y_root = cvtINT16toInt(event->u.enterLeave.rootY);
3171 ev->state = event->u.enterLeave.state;
3172 ev->mode = event->u.enterLeave.mode;
3173 ev->same_screen = (event->u.enterLeave.flags &
3174 ELFlagSameScreen) && True;
3175 ev->focus = (event->u.enterLeave.flags &
3176 ELFlagFocus) && True;
3177 ev->detail = event->u.u.detail;
3178 }
3179 break;
3180 case FocusIn:
3181 case FocusOut:
3182 {
3183 register XFocusChangeEvent *ev = (XFocusChangeEvent *) re;
3184 ev->window = event->u.focus.window;
3185 ev->mode = event->u.focus.mode;
3186 ev->detail = event->u.u.detail;
3187 }
3188 break;
3189 case KeymapNotify:
3190 {
3191 register XKeymapEvent *ev = (XKeymapEvent *) re;
3192 ev->window = None;
3193 memcpy(&ev->key_vector[1],
3194 (char *)((xKeymapEvent *) event)->map,
3195 sizeof (((xKeymapEvent *) event)->map));
3196 }
3197 break;
3198 case Expose:
3199 {
3200 register XExposeEvent *ev = (XExposeEvent *) re;
3201 ev->window = event->u.expose.window;
3202 ev->x = event->u.expose.x;
3203 ev->y = event->u.expose.y;
3204 ev->width = event->u.expose.width;
3205 ev->height = event->u.expose.height;
3206 ev->count = event->u.expose.count;
3207 }
3208 break;
3209 case GraphicsExpose:
3210 {
3211 register XGraphicsExposeEvent *ev =
3212 (XGraphicsExposeEvent *) re;
3213 ev->drawable = event->u.graphicsExposure.drawable;
3214 ev->x = event->u.graphicsExposure.x;
3215 ev->y = event->u.graphicsExposure.y;
3216 ev->width = event->u.graphicsExposure.width;
3217 ev->height = event->u.graphicsExposure.height;
3218 ev->count = event->u.graphicsExposure.count;
3219 ev->major_code = event->u.graphicsExposure.majorEvent;
3220 ev->minor_code = event->u.graphicsExposure.minorEvent;
3221 }
3222 break;
3223 case NoExpose:
3224 {
3225 register XNoExposeEvent *ev = (XNoExposeEvent *) re;
3226 ev->drawable = event->u.noExposure.drawable;
3227 ev->major_code = event->u.noExposure.majorEvent;
3228 ev->minor_code = event->u.noExposure.minorEvent;
3229 }
3230 break;
3231 case VisibilityNotify:
3232 {
3233 register XVisibilityEvent *ev = (XVisibilityEvent *) re;
3234 ev->window = event->u.visibility.window;
3235 ev->state = event->u.visibility.state;
3236 }
3237 break;
3238 case CreateNotify:
3239 {
3240 register XCreateWindowEvent *ev =
3241 (XCreateWindowEvent *) re;
3242 ev->window = event->u.createNotify.window;
3243 ev->parent = event->u.createNotify.parent;
3244 ev->x = cvtINT16toInt(event->u.createNotify.x);
3245 ev->y = cvtINT16toInt(event->u.createNotify.y);
3246 ev->width = event->u.createNotify.width;
3247 ev->height = event->u.createNotify.height;
3248 ev->border_width = event->u.createNotify.borderWidth;
3249 ev->override_redirect = event->u.createNotify.override;
3250 }
3251 break;
3252 case DestroyNotify:
3253 {
3254 register XDestroyWindowEvent *ev =
3255 (XDestroyWindowEvent *) re;
3256 ev->window = event->u.destroyNotify.window;
3257 ev->event = event->u.destroyNotify.event;
3258 }
3259 break;
3260 case UnmapNotify:
3261 {
3262 register XUnmapEvent *ev = (XUnmapEvent *) re;
3263 ev->window = event->u.unmapNotify.window;
3264 ev->event = event->u.unmapNotify.event;
3265 ev->from_configure = event->u.unmapNotify.fromConfigure;
3266 }
3267 break;
3268 case MapNotify:
3269 {
3270 register XMapEvent *ev = (XMapEvent *) re;
3271 ev->window = event->u.mapNotify.window;
3272 ev->event = event->u.mapNotify.event;
3273 ev->override_redirect = event->u.mapNotify.override;
3274 }
3275 break;
3276 case MapRequest:
3277 {
3278 register XMapRequestEvent *ev = (XMapRequestEvent *) re;
3279 ev->window = event->u.mapRequest.window;
3280 ev->parent = event->u.mapRequest.parent;
3281 }
3282 break;
3283 case ReparentNotify:
3284 {
3285 register XReparentEvent *ev = (XReparentEvent *) re;
3286 ev->event = event->u.reparent.event;
3287 ev->window = event->u.reparent.window;
3288 ev->parent = event->u.reparent.parent;
3289 ev->x = cvtINT16toInt(event->u.reparent.x);
3290 ev->y = cvtINT16toInt(event->u.reparent.y);
3291 ev->override_redirect = event->u.reparent.override;
3292 }
3293 break;
3294 case ConfigureNotify:
3295 {
3296 register XConfigureEvent *ev = (XConfigureEvent *) re;
3297 ev->event = event->u.configureNotify.event;
3298 ev->window = event->u.configureNotify.window;
3299 ev->above = event->u.configureNotify.aboveSibling;
3300 ev->x = cvtINT16toInt(event->u.configureNotify.x);
3301 ev->y = cvtINT16toInt(event->u.configureNotify.y);
3302 ev->width = event->u.configureNotify.width;
3303 ev->height = event->u.configureNotify.height;
3304 ev->border_width = event->u.configureNotify.borderWidth;
3305 ev->override_redirect = event->u.configureNotify.override;
3306 }
3307 break;
3308 case ConfigureRequest:
3309 {
3310 register XConfigureRequestEvent *ev =
3311 (XConfigureRequestEvent *) re;
3312 ev->window = event->u.configureRequest.window;
3313 ev->parent = event->u.configureRequest.parent;
3314 ev->above = event->u.configureRequest.sibling;
3315 ev->x = cvtINT16toInt(event->u.configureRequest.x);
3316 ev->y = cvtINT16toInt(event->u.configureRequest.y);
3317 ev->width = event->u.configureRequest.width;
3318 ev->height = event->u.configureRequest.height;
3319 ev->border_width = event->u.configureRequest.borderWidth;
3320 ev->value_mask = event->u.configureRequest.valueMask;
3321 ev->detail = event->u.u.detail;
3322 }
3323 break;
3324 case GravityNotify:
3325 {
3326 register XGravityEvent *ev = (XGravityEvent *) re;
3327 ev->window = event->u.gravity.window;
3328 ev->event = event->u.gravity.event;
3329 ev->x = cvtINT16toInt(event->u.gravity.x);
3330 ev->y = cvtINT16toInt(event->u.gravity.y);
3331 }
3332 break;
3333 case ResizeRequest:
3334 {
3335 register XResizeRequestEvent *ev =
3336 (XResizeRequestEvent *) re;
3337 ev->window = event->u.resizeRequest.window;
3338 ev->width = event->u.resizeRequest.width;
3339 ev->height = event->u.resizeRequest.height;
3340 }
3341 break;
3342 case CirculateNotify:
3343 {
3344 register XCirculateEvent *ev = (XCirculateEvent *) re;
3345 ev->window = event->u.circulate.window;
3346 ev->event = event->u.circulate.event;
3347 ev->place = event->u.circulate.place;
3348 }
3349 break;
3350 case CirculateRequest:
3351 {
3352 register XCirculateRequestEvent *ev =
3353 (XCirculateRequestEvent *) re;
3354 ev->window = event->u.circulate.window;
3355 ev->parent = event->u.circulate.event;
3356 ev->place = event->u.circulate.place;
3357 }
3358 break;
3359 case PropertyNotify:
3360 {
3361 register XPropertyEvent *ev = (XPropertyEvent *) re;
3362 ev->window = event->u.property.window;
3363 ev->atom = event->u.property.atom;
3364 ev->time = event->u.property.time;
3365 ev->state = event->u.property.state;
3366 }
3367 break;
3368 case SelectionClear:
3369 {
3370 register XSelectionClearEvent *ev =
3371 (XSelectionClearEvent *) re;
3372 ev->window = event->u.selectionClear.window;
3373 ev->selection = event->u.selectionClear.atom;
3374 ev->time = event->u.selectionClear.time;
3375 }
3376 break;
3377 case SelectionRequest:
3378 {
3379 register XSelectionRequestEvent *ev =
3380 (XSelectionRequestEvent *) re;
3381 ev->owner = event->u.selectionRequest.owner;
3382 ev->requestor = event->u.selectionRequest.requestor;
3383 ev->selection = event->u.selectionRequest.selection;
3384 ev->target = event->u.selectionRequest.target;
3385 ev->property = event->u.selectionRequest.property;
3386 ev->time = event->u.selectionRequest.time;
3387 }
3388 break;
3389 case SelectionNotify:
3390 {
3391 register XSelectionEvent *ev = (XSelectionEvent *) re;
3392 ev->requestor = event->u.selectionNotify.requestor;
3393 ev->selection = event->u.selectionNotify.selection;
3394 ev->target = event->u.selectionNotify.target;
3395 ev->property = event->u.selectionNotify.property;
3396 ev->time = event->u.selectionNotify.time;
3397 }
3398 break;
3399 case ColormapNotify:
3400 {
3401 register XColormapEvent *ev = (XColormapEvent *) re;
3402 ev->window = event->u.colormap.window;
3403 ev->colormap = event->u.colormap.colormap;
3404 ev->new = event->u.colormap.new;
3405 ev->state = event->u.colormap.state;
3406 }
3407 break;
3408 case ClientMessage:
3409 {
3410 register int i;
3411 register XClientMessageEvent *ev
3412 = (XClientMessageEvent *) re;
3413 ev->window = event->u.clientMessage.window;
3414 ev->format = event->u.u.detail;
3415 switch (ev->format) {
3416 case 8:
3417 ev->message_type = event->u.clientMessage.u.b.type;
3418 for (i = 0; i < 20; i++)
3419 ev->data.b[i] = event->u.clientMessage.u.b.bytes[i];
3420 break;
3421 case 16:
3422 ev->message_type = event->u.clientMessage.u.s.type;
3423 ev->data.s[0] = cvtINT16toShort(event->u.clientMessage.u.s.shorts0);
3424 ev->data.s[1] = cvtINT16toShort(event->u.clientMessage.u.s.shorts1);
3425 ev->data.s[2] = cvtINT16toShort(event->u.clientMessage.u.s.shorts2);
3426 ev->data.s[3] = cvtINT16toShort(event->u.clientMessage.u.s.shorts3);
3427 ev->data.s[4] = cvtINT16toShort(event->u.clientMessage.u.s.shorts4);
3428 ev->data.s[5] = cvtINT16toShort(event->u.clientMessage.u.s.shorts5);
3429 ev->data.s[6] = cvtINT16toShort(event->u.clientMessage.u.s.shorts6);
3430 ev->data.s[7] = cvtINT16toShort(event->u.clientMessage.u.s.shorts7);
3431 ev->data.s[8] = cvtINT16toShort(event->u.clientMessage.u.s.shorts8);
3432 ev->data.s[9] = cvtINT16toShort(event->u.clientMessage.u.s.shorts9);
3433 break;
3434 case 32:
3435 ev->message_type = event->u.clientMessage.u.l.type;
3436 ev->data.l[0] = cvtINT32toLong(event->u.clientMessage.u.l.longs0);
3437 ev->data.l[1] = cvtINT32toLong(event->u.clientMessage.u.l.longs1);
3438 ev->data.l[2] = cvtINT32toLong(event->u.clientMessage.u.l.longs2);
3439 ev->data.l[3] = cvtINT32toLong(event->u.clientMessage.u.l.longs3);
3440 ev->data.l[4] = cvtINT32toLong(event->u.clientMessage.u.l.longs4);
3441 break;
3442 default: /* XXX should never occur */
3443 break;
3444 }
3445 }
3446 break;
3447 case MappingNotify:
3448 {
3449 register XMappingEvent *ev = (XMappingEvent *)re;
3450 ev->window = 0;
3451 ev->first_keycode = event->u.mappingNotify.firstKeyCode;
3452 ev->request = event->u.mappingNotify.request;
3453 ev->count = event->u.mappingNotify.count;
3454 }
3455 break;
3456 default:
3457 return(_XUnknownWireEvent(dpy, re, event));
3458 }
3459 return(True);
3460 }
3461
3462 static int
3463 SocketBytesReadable(Display *dpy)
3464 {
3465 int bytes = 0, last_error;
3466 #ifdef WIN32
3467 last_error = WSAGetLastError();
3468 ioctlsocket(ConnectionNumber(dpy), FIONREAD, &bytes);
3469 WSASetLastError(last_error);
3470 #else
3471 last_error = errno;
3472 ioctl(ConnectionNumber(dpy), FIONREAD, &bytes);
3473 errno = last_error;
3474 #endif
3475 return bytes;
3476 }
3477
3478 _X_NORETURN void _XDefaultIOErrorExit(
3479 Display *dpy,
3480 void *user_data)
3481 {
3482 exit(1);
3483 /*NOTREACHED*/
3484 }
3485
3486 /*
3487 * _XDefaultIOError - Default fatal system error reporting routine. Called
3488 * when an X internal system error is encountered.
3489 */
3490 _X_NORETURN int _XDefaultIOError(
3491 Display *dpy)
3492 {
3493 int killed = ECHECK(EPIPE);
3494
3495 /*
3496 * If the socket was closed on the far end, the final recvmsg in
3497 * xcb will have thrown EAGAIN because we're non-blocking. Detect
3498 * this to get the more informative error message.
3499 */
3500 if (ECHECK(EAGAIN) && SocketBytesReadable(dpy) <= 0)
3501 killed = True;
3502
3503 if (killed) {
3504 fprintf (stderr,
3505 "X connection to %s broken (explicit kill or server shutdown).\r\n",
3506 DisplayString (dpy));
3507 } else {
3508 (void) fprintf (stderr,
3509 "XIO: fatal IO error %d (%s) on X server \"%s\"\r\n",
3510 #ifdef WIN32
3511 WSAGetLastError(), strerror(WSAGetLastError()),
3512 #else
3513 errno, strerror (errno),
3514 #endif
3515 DisplayString (dpy));
3516 (void) fprintf (stderr,
3517 " after %lu requests (%lu known processed) with %d events remaining.\r\n",
3518 NextRequest(dpy) - 1, LastKnownRequestProcessed(dpy),
3519 QLength(dpy));
3520
3521 }
3522 #ifdef NX_TRANS_SOCKET
3523 if (_NXHandleDisplayError == 1)
3524 {
3525 #ifdef NX_TRANS_TEST
3526 fprintf(stderr, "_XDefaultIOError: Going to return from the error handler.\n");
3527 #endif
3528 return 0;
3529 }
3530 else
3531 {
3532 #ifdef NX_TRANS_TEST
3533 fprintf(stderr, "_XDefaultIOError: Going to exit from the program.\n");
3534 #endif
3535 #ifdef NX_TRANS_EXIT
3536 NXTransExit(1);
3537 #else
3538 exit(1);
3539 #endif
3540 }
3541 #else
3542 exit(1);
3543 #endif /* #ifdef NX_TRANS_SOCKET */
3544 /*NOTREACHED*/
3545 }
3546
3547
3548 static int _XPrintDefaultError(
3549 Display *dpy,
3550 XErrorEvent *event,
3551 FILE *fp)
3552 {
3553 char buffer[BUFSIZ];
3554 char mesg[BUFSIZ];
3555 char number[32];
3556 const char *mtype = "XlibMessage";
3557 register _XExtension *ext = (_XExtension *)NULL;
3558 _XExtension *bext = (_XExtension *)NULL;
3559 XGetErrorText(dpy, event->error_code, buffer, BUFSIZ);
3560 XGetErrorDatabaseText(dpy, mtype, "XError", "X Error", mesg, BUFSIZ);
3561 (void) fprintf(fp, "%s: %s\n ", mesg, buffer);
3562 XGetErrorDatabaseText(dpy, mtype, "MajorCode", "Request Major code %d",
3563 mesg, BUFSIZ);
3564 (void) fprintf(fp, mesg, event->request_code);
3565 if (event->request_code < 128) {
3566 snprintf(number, sizeof(number), "%d", event->request_code);
3567 XGetErrorDatabaseText(dpy, "XRequest", number, "", buffer, BUFSIZ);
3568 } else {
3569 for (ext = dpy->ext_procs;
3570 ext && (ext->codes.major_opcode != event->request_code);
3571 ext = ext->next)
3572 ;
3573 if (ext) {
3574 strncpy(buffer, ext->name, BUFSIZ);
3575 buffer[BUFSIZ - 1] = '\0';
3576 } else
3577 buffer[0] = '\0';
3578 }
3579 (void) fprintf(fp, " (%s)\n", buffer);
3580 if (event->request_code >= 128) {
3581 XGetErrorDatabaseText(dpy, mtype, "MinorCode", "Request Minor code %d",
3582 mesg, BUFSIZ);
3583 fputs(" ", fp);
3584 (void) fprintf(fp, mesg, event->minor_code);
3585 if (ext) {
3586 snprintf(mesg, sizeof(mesg), "%s.%d", ext->name, event->minor_code);
3587 XGetErrorDatabaseText(dpy, "XRequest", mesg, "", buffer, BUFSIZ);
3588 (void) fprintf(fp, " (%s)", buffer);
3589 }
3590 fputs("\n", fp);
3591 }
3592 if (event->error_code >= 128) {
3593 /* kludge, try to find the extension that caused it */
3594 buffer[0] = '\0';
3595 for (ext = dpy->ext_procs; ext; ext = ext->next) {
3596 if (ext->error_string)
3597 (*ext->error_string)(dpy, event->error_code, &ext->codes,
3598 buffer, BUFSIZ);
3599 if (buffer[0]) {
3600 bext = ext;
3601 break;
3602 }
3603 if (ext->codes.first_error &&
3604 ext->codes.first_error < (int)event->error_code &&
3605 (!bext || ext->codes.first_error > bext->codes.first_error))
3606 bext = ext;
3607 }
3608 if (bext)
3609 snprintf(buffer, sizeof(buffer), "%s.%d", bext->name,
3610 event->error_code - bext->codes.first_error);
3611 else
3612 strcpy(buffer, "Value");
3613 XGetErrorDatabaseText(dpy, mtype, buffer, "", mesg, BUFSIZ);
3614 if (mesg[0]) {
3615 fputs(" ", fp);
3616 (void) fprintf(fp, mesg, event->resourceid);
3617 fputs("\n", fp);
3618 }
3619 /* let extensions try to print the values */
3620 for (ext = dpy->ext_procs; ext; ext = ext->next) {
3621 if (ext->error_values)
3622 (*ext->error_values)(dpy, event, fp);
3623 }
3624 } else if ((event->error_code == BadWindow) ||
3625 (event->error_code == BadPixmap) ||
3626 (event->error_code == BadCursor) ||
3627 (event->error_code == BadFont) ||
3628 (event->error_code == BadDrawable) ||
3629 (event->error_code == BadColor) ||
3630 (event->error_code == BadGC) ||
3631 (event->error_code == BadIDChoice) ||
3632 (event->error_code == BadValue) ||
3633 (event->error_code == BadAtom)) {
3634 if (event->error_code == BadValue)
3635 XGetErrorDatabaseText(dpy, mtype, "Value", "Value 0x%x",
3636 mesg, BUFSIZ);
3637 else if (event->error_code == BadAtom)
3638 XGetErrorDatabaseText(dpy, mtype, "AtomID", "AtomID 0x%x",
3639 mesg, BUFSIZ);
3640 else
3641 XGetErrorDatabaseText(dpy, mtype, "ResourceID", "ResourceID 0x%x",
3642 mesg, BUFSIZ);
3643 fputs(" ", fp);
3644 (void) fprintf(fp, mesg, event->resourceid);
3645 fputs("\n", fp);
3646 }
3647 XGetErrorDatabaseText(dpy, mtype, "ErrorSerial", "Error Serial #%d",
3648 mesg, BUFSIZ);
3649 fputs(" ", fp);
3650 (void) fprintf(fp, mesg, event->serial);
3651 XGetErrorDatabaseText(dpy, mtype, "CurrentSerial", "Current Serial #%lld",
3652 mesg, BUFSIZ);
3653 fputs("\n ", fp);
3654 (void) fprintf(fp, mesg, (unsigned long long)(X_DPY_GET_REQUEST(dpy)));
3655 fputs("\n", fp);
3656 if (event->error_code == BadImplementation) return 0;
3657 return 1;
3658 }
3659
3660 int _XDefaultError(
3661 Display *dpy,
3662 XErrorEvent *event)
3663 {
3664 if (_XPrintDefaultError (dpy, event, stderr) == 0) return 0;
3665
3666 /*
3667 * Store in dpy flags that the client is exiting on an unhandled XError
3668 * (pretend it is an IOError, since the application is dying anyway it
3669 * does not make a difference).
3670 * This is useful for _XReply not to hang if the application makes Xlib
3671 * calls in _fini as part of process termination.
3672 */
3673 dpy->flags |= XlibDisplayIOError;
3674
3675 exit(1);
3676 /*NOTREACHED*/
3677 }
3678
3679 /*ARGSUSED*/
3680 Bool _XDefaultWireError(Display *display, XErrorEvent *he, xError *we)
3681 {
3682 return True;
3683 }
3684
3685 /*
3686 * _XError - upcall internal or user protocol error handler
3687 */
3688 int _XError (
3689 Display *dpy,
3690 register xError *rep)
3691 {
3692 /*
3693 * X_Error packet encountered! We need to unpack the error before
3694 * giving it to the user.
3695 */
3696 XEvent event; /* make it a large event */
3697 register _XAsyncHandler *async, *next;
3698
3699 event.xerror.serial = _XSetLastRequestRead(dpy, (xGenericReply *)rep);
3700
3701 for (async = dpy->async_handlers; async; async = next) {
3702 next = async->next;
3703 if ((*async->handler)(dpy, (xReply *)rep,
3704 (char *)rep, SIZEOF(xError), async->data))
3705 return 0;
3706 }
3707
3708 event.xerror.display = dpy;
3709 event.xerror.type = X_Error;
3710 event.xerror.resourceid = rep->resourceID;
3711 event.xerror.error_code = rep->errorCode;
3712 event.xerror.request_code = rep->majorCode;
3713 event.xerror.minor_code = rep->minorCode;
3714 if (dpy->error_vec &&
3715 !(*dpy->error_vec[rep->errorCode])(dpy, &event.xerror, rep))
3716 return 0;
3717 if (_XErrorFunction != NULL) {
3718 int rtn_val;
3719 #ifdef XTHREADS
3720 struct _XErrorThreadInfo thread_info = {
3721 .error_thread = xthread_self(),
3722 .next = dpy->error_threads
3723 }, **prev;
3724 dpy->error_threads = &thread_info;
3725 if (dpy->lock)
3726 (*dpy->lock->user_lock_display)(dpy);
3727 UnlockDisplay(dpy);
3728 #endif
3729 rtn_val = (*_XErrorFunction)(dpy, (XErrorEvent *)&event); /* upcall */
3730 #ifdef XTHREADS
3731 LockDisplay(dpy);
3732 if (dpy->lock)
3733 (*dpy->lock->user_unlock_display)(dpy);
3734
3735 /* unlink thread_info from the list */
3736 for (prev = &dpy->error_threads; *prev != &thread_info; prev = &(*prev)->next)
3737 ;
3738 *prev = thread_info.next;
3739 #endif
3740 return rtn_val;
3741 } else {
3742 return _XDefaultError(dpy, (XErrorEvent *)&event);
3743 }
3744 }
3745
3746 /*
3747 * _XIOError - call user connection error handler and exit
3748 */
3749 int
3750 _XIOError (
3751 Display *dpy)
3752 {
3753 XIOErrorExitHandler exit_handler;
3754 void *exit_handler_data;
3755
3756 dpy->flags |= XlibDisplayIOError;
3757 #ifdef WIN32
3758 errno = WSAGetLastError();
3759 #endif
3760
3761 /* This assumes that the thread calling exit will call any atexit handlers.
3762 * If this does not hold, then an alternate solution would involve
3763 * registering an atexit handler to take over the lock, which would only
3764 * assume that the same thread calls all the atexit handlers. */
3765 #ifdef XTHREADS
3766 if (dpy->lock)
3767 (*dpy->lock->user_lock_display)(dpy);
3768 #endif
3769 exit_handler = dpy->exit_handler;
3770 exit_handler_data = dpy->exit_handler_data;
3771 UnlockDisplay(dpy);
3772
3773 if (_XIOErrorFunction != NULL)
3774 (*_XIOErrorFunction)(dpy);
3775 else
3776 _XDefaultIOError(dpy);
3777 #ifdef NX_TRANS_SOCKET
3778 /*
3779 * Check if we are supposed to return in the case of a display
3780 * failure. The client which originated the X operation will have
3781 * to check the value of the XlibDisplayIOError flag and handle
3782 * appropriately the display disconnection.
3783 */
3784
3785 if (_NXHandleDisplayError == 0)
3786 {
3787 #ifdef NX_TRANS_EXIT
3788 NXTransExit(1);
3789 #else
3790 exit_handler(dpy, exit_handler_data);
3791 exit(1);
3792 #endif
3793 }
3794
3795 /*
3796 * We are going to return. Reset the display
3797 * buffers. Further writes will be discarded.
3798 */
3799
3800 #ifdef NX_TRANS_TEST
3801 fprintf(stderr, "_XIOError: Resetting the display buffer.\n");
3802 #endif
3803
3804 dpy->bufptr = dpy->buffer;
3805 dpy->last_req = (char *) &_dummy_request;
3806
3807 #ifdef NX_TRANS_TEST
3808 fprintf(stderr, "_XIOError: Resetting the display flags.\n");
3809 #endif
3810
3811 dpy->flags &= ~XlibDisplayProcConni;
3812 dpy->flags &= ~XlibDisplayPrivSync;
3813 dpy->flags &= ~XlibDisplayReadEvents;
3814 dpy->flags &= ~XlibDisplayWriting;
3815 dpy->flags &= ~XlibDisplayReply;
3816 /* shut up the compiler by returning something */
3817 return 0;
3818 #else
3819 exit_handler(dpy, exit_handler_data);
3820 exit (1);
3821 #endif
3822 /*NOTREACHED*/
3823 }
3824
3825
3826 /*
3827 * This routine can be used to (cheaply) get some memory within a single
3828 * Xlib routine for scratch space. A single buffer is reused each time
3829 * if possible. To be MT safe, you can only call this between a call to
3830 * GetReq* and a call to Data* or _XSend*, or in a context when the thread
3831 * is guaranteed to not unlock the display.
3832 */
3833 char *_XAllocScratch(
3834 register Display *dpy,
3835 unsigned long nbytes)
3836 {
3837 if (nbytes > dpy->scratch_length) {
3838 Xfree (dpy->scratch_buffer);
3839 dpy->scratch_buffer = Xmalloc(nbytes);
3840 if (dpy->scratch_buffer)
3841 dpy->scratch_length = nbytes;
3842 else dpy->scratch_length = 0;
3843 }
3844 return (dpy->scratch_buffer);
3845 }
3846
3847 /*
3848 * Scratch space allocator you can call any time, multiple times, and be
3849 * MT safe, but you must hand the buffer back with _XFreeTemp.
3850 */
3851 char *_XAllocTemp(
3852 register Display *dpy,
3853 unsigned long nbytes)
3854 {
3855 char *buf;
3856
3857 buf = _XAllocScratch(dpy, nbytes);
3858 dpy->scratch_buffer = NULL;
3859 dpy->scratch_length = 0;
3860 return buf;
3861 }
3862
3863 void _XFreeTemp(
3864 register Display *dpy,
3865 char *buf,
3866 unsigned long nbytes)
3867 {
3868
3869 Xfree(dpy->scratch_buffer);
3870 dpy->scratch_buffer = buf;
3871 dpy->scratch_length = nbytes;
3872 }
3873
3874 /*
3875 * Given a visual id, find the visual structure for this id on this display.
3876 */
3877 Visual *_XVIDtoVisual(
3878 Display *dpy,
3879 VisualID id)
3880 {
3881 register int i, j, k;
3882 register Screen *sp;
3883 register Depth *dp;
3884 register Visual *vp;
3885 for (i = 0; i < dpy->nscreens; i++) {
3886 sp = &dpy->screens[i];
3887 for (j = 0; j < sp->ndepths; j++) {
3888 dp = &sp->depths[j];
3889 /* if nvisuals == 0 then visuals will be NULL */
3890 for (k = 0; k < dp->nvisuals; k++) {
3891 vp = &dp->visuals[k];
3892 if (vp->visualid == id) return (vp);
3893 }
3894 }
3895 }
3896 return (NULL);
3897 }
3898
3899 int
3900 XFree (void *data)
3901 {
3902 Xfree (data);
3903 return 1;
3904 }
3905
3906 #ifdef _XNEEDBCOPYFUNC
3907 void _Xbcopy(b1, b2, length)
3908 register char *b1, *b2;
3909 register length;
3910 {
3911 if (b1 < b2) {
3912 b2 += length;
3913 b1 += length;
3914 while (length--)
3915 *--b2 = *--b1;
3916 } else {
3917 while (length--)
3918 *b2++ = *b1++;
3919 }
3920 }
3921 #endif
3922
3923 #ifdef DataRoutineIsProcedure
3924 void Data(
3925 Display *dpy,
3926 _Xconst char *data,
3927 long len)
3928 {
3929 if (dpy->bufptr + (len) <= dpy->bufmax) {
3930 memcpy(dpy->bufptr, data, (int)len);
3931 dpy->bufptr += ((len) + 3) & ~3;
3932 } else {
3933 _XSend(dpy, data, len);
3934 }
3935 }
3936 #endif /* DataRoutineIsProcedure */
3937
3938
3939 #ifdef LONG64
3940 int
3941 _XData32(
3942 Display *dpy,
3943 register _Xconst long *data,
3944 unsigned len)
3945 {
3946 register int *buf;
3947 register long i;
3948
3949 while (len) {
3950 buf = (int *)dpy->bufptr;
3951 i = dpy->bufmax - (char *)buf;
3952 if (!i) {
3953 _XFlush(dpy);
3954 continue;
3955 }
3956 if (len < i)
3957 i = len;
3958 dpy->bufptr = (char *)buf + i;
3959 len -= i;
3960 i >>= 2;
3961 while (--i >= 0)
3962 *buf++ = *data++;
3963 }
3964 return 0;
3965 }
3966 #endif /* LONG64 */
3967
3968
3969
3970 /* Make sure this produces the same string as DefineLocal/DefineSelf in xdm.
3971 * Otherwise, Xau will not be able to find your cookies in the Xauthority file.
3972 *
3973 * Note: POSIX says that the ``nodename'' member of utsname does _not_ have
3974 * to have sufficient information for interfacing to the network,
3975 * and so, you may be better off using gethostname (if it exists).
3976 */
3977
3978 #if defined(_POSIX_SOURCE) || defined(SVR4)
3979 #define NEED_UTSNAME
3980 #include <sys/utsname.h>
3981 #else
3982 #ifdef HAVE_UNISTD_H
3983 #include <unistd.h>
3984 #endif
3985 #endif
3986
3987 /*
3988 * _XGetHostname - similar to gethostname but allows special processing.
3989 */
3990 int _XGetHostname (
3991 char *buf,
3992 int maxlen)
3993 {
3994 int len;
3995
3996 #ifdef NEED_UTSNAME
3997 struct utsname name;
3998
3999 if (maxlen <= 0 || buf == NULL)
4000 return 0;
4001
4002 uname (&name);
4003 len = (int) strlen (name.nodename);
4004 if (len >= maxlen) len = maxlen - 1;
4005 strncpy (buf, name.nodename, (size_t) len);
4006 buf[len] = '\0';
4007 #else
4008 if (maxlen <= 0 || buf == NULL)
4009 return 0;
4010
4011 buf[0] = '\0';
4012 (void) gethostname (buf, maxlen);
4013 buf [maxlen - 1] = '\0';
4014 len = (int) strlen(buf);
4015 #endif /* NEED_UTSNAME */
4016 return len;
4017 }
4018
4019
4020 /*
4021 * _XScreenOfWindow - get the Screen of a given window
4022 */
4023
4024 Screen *_XScreenOfWindow(Display *dpy, Window w)
4025 {
4026 register int i;
4027 Window root;
4028 int x, y; /* dummy variables */
4029 unsigned int width, height, bw, depth; /* dummy variables */
4030
4031 if (XGetGeometry (dpy, w, &root, &x, &y, &width, &height,
4032 &bw, &depth) == False) {
4033 return NULL;
4034 }
4035 for (i = 0; i < ScreenCount (dpy); i++) { /* find root from list */
4036 if (root == RootWindow (dpy, i)) {
4037 return ScreenOfDisplay (dpy, i);
4038 }
4039 }
4040 return NULL;
4041 }
4042
4043
4044 /*
4045 * WARNING: This implementation's pre-conditions and post-conditions
4046 * must remain compatible with the old macro-based implementations of
4047 * GetReq, GetReqExtra, GetResReq, and GetEmptyReq. The portions of the
4048 * Display structure affected by those macros are part of libX11's
4049 * ABI.
4050 */
4051 void *_XGetRequest(Display *dpy, CARD8 type, size_t len)
4052 {
4053 xReq *req;
4054
4055 if (dpy->bufptr + len > dpy->bufmax)
4056 _XFlush(dpy);
4057 /* Request still too large, so do not allow it to overflow. */
4058 if (dpy->bufptr + len > dpy->bufmax) {
4059 fprintf(stderr,
4060 "Xlib: request %d length %zd would exceed buffer size.\n",
4061 type, len);
4062 /* Changes failure condition from overflow to NULL dereference. */
4063 return NULL;
4064 }
4065
4066 if (len % 4)
4067 fprintf(stderr,
4068 "Xlib: request %d length %zd not a multiple of 4.\n",
4069 type, len);
4070
4071 dpy->last_req = dpy->bufptr;
4072
4073 req = (xReq*)dpy->bufptr;
4074 req->reqType = type;
4075 req->length = len / 4;
4076 dpy->bufptr += len;
4077 X_DPY_REQUEST_INCREMENT(dpy);
4078 return req;
4079 }
4080
4081 #if defined(WIN32)
4082
4083 /*
4084 * These functions are intended to be used internally to Xlib only.
4085 * These functions will always prefix the path with a DOS drive in the
4086 * form "<drive-letter>:". As such, these functions are only suitable
4087 * for use by Xlib function that supply a root-based path to some
4088 * particular file, e.g. <ProjectRoot>/lib/X11/locale/locale.dir will
4089 * be converted to "C:/usr/X11R6.3/lib/X11/locale/locale.dir".
4090 */
4091
4092 static int access_file (path, pathbuf, len_pathbuf, pathret)
4093 char* path;
4094 char* pathbuf;
4095 int len_pathbuf;
4096 char** pathret;
4097 {
4098 if (access (path, F_OK) == 0) {
4099 if (strlen (path) < len_pathbuf)
4100 *pathret = pathbuf;
4101 else
4102 *pathret = Xmalloc (strlen (path) + 1);
4103 if (*pathret) {
4104 strcpy (*pathret, path);
4105 return 1;
4106 }
4107 }
4108 return 0;
4109 }
4110
4111 static int AccessFile (path, pathbuf, len_pathbuf, pathret)
4112 char* path;
4113 char* pathbuf;
4114 int len_pathbuf;
4115 char** pathret;
4116 {
4117 unsigned long drives;
4118 int i, len;
4119 char* drive;
4120 char buf[MAX_PATH];
4121 char* bufp;
4122
4123 /* just try the "raw" name first and see if it works */
4124 if (access_file (path, pathbuf, len_pathbuf, pathret))
4125 return 1;
4126
4127 /* try the places set in the environment */
4128 drive = getenv ("_XBASEDRIVE");
4129 if (!drive)
4130 drive = "C:";
4131 len = strlen (drive) + strlen (path);
4132 if (len < MAX_PATH) bufp = buf;
4133 else bufp = Xmalloc (len + 1);
4134 strcpy (bufp, drive);
4135 strcat (bufp, path);
4136 if (access_file (bufp, pathbuf, len_pathbuf, pathret)) {
4137 if (bufp != buf) Xfree (bufp);
4138 return 1;
4139 }
4140
4141 /* one last place to look */
4142 drive = getenv ("HOMEDRIVE");
4143 if (drive) {
4144 len = strlen (drive) + strlen (path);
4145 if (len < MAX_PATH) bufp = buf;
4146 else bufp = Xmalloc (len + 1);
4147 strcpy (bufp, drive);
4148 strcat (bufp, path);
4149 if (access_file (bufp, pathbuf, len_pathbuf, pathret)) {
4150 if (bufp != buf) Xfree (bufp);
4151 return 1;
4152 }
4153 }
4154
4155 /* tried everywhere else, go fishing */
4156 #define C_DRIVE ('C' - 'A')
4157 #define Z_DRIVE ('Z' - 'A')
4158 /* does OS/2 (with or with gcc-emx) have getdrives? */
4159 drives = _getdrives ();
4160 for (i = C_DRIVE; i <= Z_DRIVE; i++) { /* don't check on A: or B: */
4161 if ((1 << i) & drives) {
4162 len = 2 + strlen (path);
4163 if (len < MAX_PATH) bufp = buf;
4164 else bufp = Xmalloc (len + 1);
4165 *bufp = 'A' + i;
4166 *(bufp + 1) = ':';
4167 *(bufp + 2) = '\0';
4168 strcat (bufp, path);
4169 if (access_file (bufp, pathbuf, len_pathbuf, pathret)) {
4170 if (bufp != buf) Xfree (bufp);
4171 return 1;
4172 }
4173 }
4174 }
4175 return 0;
4176 }
4177
4178 int _XOpenFile(path, flags)
4179 _Xconst char* path;
4180 int flags;
4181 {
4182 char buf[MAX_PATH];
4183 char* bufp = NULL;
4184 int ret = -1;
4185 UINT olderror = SetErrorMode (SEM_FAILCRITICALERRORS);
4186
4187 if (AccessFile (path, buf, MAX_PATH, &bufp))
4188 ret = open (bufp, flags);
4189
4190 (void) SetErrorMode (olderror);
4191
4192 if (bufp != buf) Xfree (bufp);
4193
4194 return ret;
4195 }
4196
4197 int _XOpenFileMode(path, flags, mode)
4198 _Xconst char* path;
4199 int flags;
4200 mode_t mode;
4201 {
4202 char buf[MAX_PATH];
4203 char* bufp = NULL;
4204 int ret = -1;
4205 UINT olderror = SetErrorMode (SEM_FAILCRITICALERRORS);
4206
4207 if (AccessFile (path, buf, MAX_PATH, &bufp))
4208 ret = open (bufp, flags, mode);
4209
4210 (void) SetErrorMode (olderror);
4211
4212 if (bufp != buf) Xfree (bufp);
4213
4214 return ret;
4215 }
4216
4217 void* _XFopenFile(path, mode)
4218 _Xconst char* path;
4219 _Xconst char* mode;
4220 {
4221 char buf[MAX_PATH];
4222 char* bufp = NULL;
4223 void* ret = NULL;
4224 UINT olderror = SetErrorMode (SEM_FAILCRITICALERRORS);
4225
4226 if (AccessFile (path, buf, MAX_PATH, &bufp))
4227 ret = fopen (bufp, mode);
4228
4229 (void) SetErrorMode (olderror);
4230
4231 if (bufp != buf) Xfree (bufp);
4232
4233 return ret;
4234 }
4235
4236 int _XAccessFile(path)
4237 _Xconst char* path;
4238 {
4239 char buf[MAX_PATH];
4240 char* bufp;
4241 int ret = -1;
4242 UINT olderror = SetErrorMode (SEM_FAILCRITICALERRORS);
4243
4244 ret = AccessFile (path, buf, MAX_PATH, &bufp);
4245
4246 (void) SetErrorMode (olderror);
4247
4248 if (bufp != buf) Xfree (bufp);
4249
4250 return ret;
4251 }
4252
4253 #endif
4254
4255 #ifdef WIN32
4256 #undef _Xdebug
4257 int _Xdebug = 0;
4258 int *_Xdebug_p = &_Xdebug;
4259 void (**_XCreateMutex_fn_p)(LockInfoPtr) = &_XCreateMutex_fn;
4260 void (**_XFreeMutex_fn_p)(LockInfoPtr) = &_XFreeMutex_fn;
4261 void (**_XLockMutex_fn_p)(LockInfoPtr
4262 #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE)
4263 , char * /* file */
4264 , int /* line */
4265 #endif
4266 ) = &_XLockMutex_fn;
4267 void (**_XUnlockMutex_fn_p)(LockInfoPtr
4268 #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE)
4269 , char * /* file */
4270 , int /* line */
4271 #endif
4272 ) = &_XUnlockMutex_fn;
4273 LockInfoPtr *_Xglobal_lock_p = &_Xglobal_lock;
4274 #endif