xcb_io.c revision 88de56cc
1/* Copyright (C) 2003-2006 Jamey Sharp, Josh Triplett
2 * This file is licensed under the MIT license. See the file COPYING. */
3
4#ifdef HAVE_CONFIG_H
5#include <config.h>
6#endif
7
8#include "Xlibint.h"
9#include "locking.h"
10#include "Xprivate.h"
11#include "Xxcbint.h"
12#include <xcb/xcbext.h>
13
14#include <assert.h>
15#ifdef HAVE_INTTYPES_H
16#include <inttypes.h>
17#endif
18#include <stdint.h>
19#include <stdlib.h>
20#include <string.h>
21#ifdef HAVE_SYS_SELECT_H
22#include <sys/select.h>
23#endif
24
25static void return_socket(void *closure)
26{
27	Display *dpy = closure;
28	InternalLockDisplay(dpy, /* don't skip user locks */ 0);
29	_XSend(dpy, NULL, 0);
30	dpy->bufmax = dpy->buffer;
31	UnlockDisplay(dpy);
32}
33
34static void require_socket(Display *dpy)
35{
36	if(dpy->bufmax == dpy->buffer)
37	{
38		uint64_t sent;
39		int flags = 0;
40		/* if we don't own the event queue, we have to ask XCB
41		 * to set our errors aside for us. */
42		if(dpy->xcb->event_owner != XlibOwnsEventQueue)
43			flags = XCB_REQUEST_CHECKED;
44		if(!xcb_take_socket(dpy->xcb->connection, return_socket, dpy,
45		                    flags, &sent))
46			_XIOError(dpy);
47		/* Xlib uses unsigned long for sequence numbers.  XCB
48		 * uses 64-bit internally, but currently exposes an
49		 * unsigned int API.  If these differ, Xlib cannot track
50		 * the full 64-bit sequence number if 32-bit wrap
51		 * happens while Xlib does not own the socket.  A
52		 * complete fix would be to make XCB's public API use
53		 * 64-bit sequence numbers. */
54		assert(!(sizeof(unsigned long) > sizeof(unsigned int)
55		         && dpy->xcb->event_owner == XlibOwnsEventQueue
56		         && (sent - dpy->last_request_read >= (UINT64_C(1) << 32))));
57		dpy->xcb->last_flushed = dpy->request = sent;
58		dpy->bufmax = dpy->xcb->real_bufmax;
59	}
60}
61
62/* Call internal connection callbacks for any fds that are currently
63 * ready to read. This function will not block unless one of the
64 * callbacks blocks.
65 *
66 * This code borrowed from _XWaitForReadable. Inverse call tree:
67 * _XRead
68 *  _XWaitForWritable
69 *   _XFlush
70 *   _XSend
71 *  _XEventsQueued
72 *  _XReadEvents
73 *  _XRead[0-9]+
74 *   _XAllocIDs
75 *  _XReply
76 *  _XEatData
77 * _XReadPad
78 */
79static void check_internal_connections(Display *dpy)
80{
81	struct _XConnectionInfo *ilist;
82	fd_set r_mask;
83	struct timeval tv;
84	int result;
85	int highest_fd = -1;
86
87	if(dpy->flags & XlibDisplayProcConni || !dpy->im_fd_info)
88		return;
89
90	FD_ZERO(&r_mask);
91	for(ilist = dpy->im_fd_info; ilist; ilist = ilist->next)
92	{
93		assert(ilist->fd >= 0);
94		FD_SET(ilist->fd, &r_mask);
95		if(ilist->fd > highest_fd)
96			highest_fd = ilist->fd;
97	}
98	assert(highest_fd >= 0);
99
100	tv.tv_sec = 0;
101	tv.tv_usec = 0;
102	result = select(highest_fd + 1, &r_mask, NULL, NULL, &tv);
103
104	if(result == -1)
105	{
106		if(errno == EINTR)
107			return;
108		_XIOError(dpy);
109	}
110
111	for(ilist = dpy->im_fd_info; result && ilist; ilist = ilist->next)
112		if(FD_ISSET(ilist->fd, &r_mask))
113		{
114			_XProcessInternalConnection(dpy, ilist);
115			--result;
116		}
117}
118
119static PendingRequest *append_pending_request(Display *dpy, unsigned long sequence)
120{
121	PendingRequest *node = malloc(sizeof(PendingRequest));
122	assert(node);
123	node->next = NULL;
124	node->sequence = sequence;
125	node->reply_waiter = 0;
126	if(dpy->xcb->pending_requests_tail)
127	{
128		assert(XLIB_SEQUENCE_COMPARE(dpy->xcb->pending_requests_tail->sequence, <, node->sequence));
129		assert(dpy->xcb->pending_requests_tail->next == NULL);
130		dpy->xcb->pending_requests_tail->next = node;
131	}
132	else
133		dpy->xcb->pending_requests = node;
134	dpy->xcb->pending_requests_tail = node;
135	return node;
136}
137
138static void dequeue_pending_request(Display *dpy, PendingRequest *req)
139{
140	assert(req == dpy->xcb->pending_requests);
141	dpy->xcb->pending_requests = req->next;
142	if(!dpy->xcb->pending_requests)
143	{
144		assert(req == dpy->xcb->pending_requests_tail);
145		dpy->xcb->pending_requests_tail = NULL;
146	}
147	else
148		assert(XLIB_SEQUENCE_COMPARE(req->sequence, <, dpy->xcb->pending_requests->sequence));
149	free(req);
150}
151
152static int handle_error(Display *dpy, xError *err, Bool in_XReply)
153{
154	_XExtension *ext;
155	int ret_code;
156	/* Oddly, Xlib only allows extensions to suppress errors when
157	 * those errors were seen by _XReply. */
158	if(in_XReply)
159		/*
160		 * we better see if there is an extension who may
161		 * want to suppress the error.
162		 */
163		for(ext = dpy->ext_procs; ext; ext = ext->next)
164			if(ext->error && (*ext->error)(dpy, err, &ext->codes, &ret_code))
165				return ret_code;
166	_XError(dpy, err);
167	return 0;
168}
169
170/* Widen a 32-bit sequence number into a native-word-size (unsigned long)
171 * sequence number.  Treating the comparison as a 1 and shifting it avoids a
172 * conditional branch, and shifting by 16 twice avoids a compiler warning when
173 * sizeof(unsigned long) == 4. */
174static void widen(unsigned long *wide, unsigned int narrow)
175{
176	unsigned long new = (*wide & ~0xFFFFFFFFUL) | narrow;
177	*wide = new + ((unsigned long) (new < *wide) << 16 << 16);
178}
179
180/* Thread-safety rules:
181 *
182 * At most one thread can be reading from XCB's event queue at a time.
183 * If you are not the current event-reading thread and you need to find
184 * out if an event is available, you must wait.
185 *
186 * The same rule applies for reading replies.
187 *
188 * A single thread cannot be both the the event-reading and the
189 * reply-reading thread at the same time.
190 *
191 * We always look at both the current event and the first pending reply
192 * to decide which to process next.
193 *
194 * We always process all responses in sequence-number order, which may
195 * mean waiting for another thread (either the event_waiter or the
196 * reply_waiter) to handle an earlier response before we can process or
197 * return a later one. If so, we wait on the corresponding condition
198 * variable for that thread to process the response and wake us up.
199 */
200
201static xcb_generic_reply_t *poll_for_event(Display *dpy)
202{
203	/* Make sure the Display's sequence numbers are valid */
204	require_socket(dpy);
205
206	/* Precondition: This thread can safely get events from XCB. */
207	assert(dpy->xcb->event_owner == XlibOwnsEventQueue && !dpy->xcb->event_waiter);
208
209	if(!dpy->xcb->next_event)
210		dpy->xcb->next_event = xcb_poll_for_event(dpy->xcb->connection);
211
212	if(dpy->xcb->next_event)
213	{
214		PendingRequest *req = dpy->xcb->pending_requests;
215		xcb_generic_event_t *event = dpy->xcb->next_event;
216		unsigned long event_sequence = dpy->last_request_read;
217		widen(&event_sequence, event->full_sequence);
218		if(!req || XLIB_SEQUENCE_COMPARE(event_sequence, <, req->sequence)
219		        || (event->response_type != X_Error && event_sequence == req->sequence))
220		{
221			assert(XLIB_SEQUENCE_COMPARE(event_sequence, <=, dpy->request));
222			dpy->last_request_read = event_sequence;
223			dpy->xcb->next_event = NULL;
224			return (xcb_generic_reply_t *) event;
225		}
226	}
227	return NULL;
228}
229
230static xcb_generic_reply_t *poll_for_response(Display *dpy)
231{
232	void *response;
233	xcb_generic_error_t *error;
234	PendingRequest *req;
235	while(!(response = poll_for_event(dpy)) &&
236	      (req = dpy->xcb->pending_requests) &&
237	      !req->reply_waiter &&
238	      xcb_poll_for_reply(dpy->xcb->connection, req->sequence, &response, &error))
239	{
240		assert(XLIB_SEQUENCE_COMPARE(req->sequence, <=, dpy->request));
241		dpy->last_request_read = req->sequence;
242		if(!response)
243			dequeue_pending_request(dpy, req);
244		if(error)
245			return (xcb_generic_reply_t *) error;
246	}
247	return response;
248}
249
250static void handle_response(Display *dpy, xcb_generic_reply_t *response, Bool in_XReply)
251{
252	_XAsyncHandler *async, *next;
253	switch(response->response_type)
254	{
255	case X_Reply:
256		for(async = dpy->async_handlers; async; async = next)
257		{
258			next = async->next;
259			if(async->handler(dpy, (xReply *) response, (char *) response, sizeof(xReply) + (response->length << 2), async->data))
260				break;
261		}
262		break;
263
264	case X_Error:
265		handle_error(dpy, (xError *) response, in_XReply);
266		break;
267
268	default: /* event */
269		/* GenericEvents may be > 32 bytes. In this case, the
270		 * event struct is trailed by the additional bytes. the
271		 * xcb_generic_event_t struct uses 4 bytes for internal
272		 * numbering, so we need to shift the trailing data to
273		 * be after the first 32 bytes. */
274		if(response->response_type == GenericEvent && ((xcb_ge_event_t *) response)->length)
275		{
276			xcb_ge_event_t *event = (xcb_ge_event_t *) response;
277			memmove(&event->full_sequence, &event[1], event->length * 4);
278		}
279		_XEnq(dpy, (xEvent *) response);
280		break;
281	}
282	free(response);
283}
284
285int _XEventsQueued(Display *dpy, int mode)
286{
287	xcb_generic_reply_t *response;
288	if(dpy->flags & XlibDisplayIOError)
289		return 0;
290	if(dpy->xcb->event_owner != XlibOwnsEventQueue)
291		return 0;
292
293	if(mode == QueuedAfterFlush)
294		_XSend(dpy, NULL, 0);
295	else
296		check_internal_connections(dpy);
297
298	/* If another thread is blocked waiting for events, then we must
299	 * let that thread pick up the next event. Since it blocked, we
300	 * can reasonably claim there are no new events right now. */
301	if(!dpy->xcb->event_waiter)
302	{
303		while((response = poll_for_response(dpy)))
304			handle_response(dpy, response, False);
305		if(xcb_connection_has_error(dpy->xcb->connection))
306			_XIOError(dpy);
307	}
308	return dpy->qlen;
309}
310
311/* _XReadEvents - Flush the output queue,
312 * then read as many events as possible (but at least 1) and enqueue them
313 */
314void _XReadEvents(Display *dpy)
315{
316	xcb_generic_reply_t *response;
317	unsigned long serial;
318
319	if(dpy->flags & XlibDisplayIOError)
320		return;
321	_XSend(dpy, NULL, 0);
322	if(dpy->xcb->event_owner != XlibOwnsEventQueue)
323		return;
324	check_internal_connections(dpy);
325
326	serial = dpy->next_event_serial_num;
327	while(serial == dpy->next_event_serial_num || dpy->qlen == 0)
328	{
329		if(dpy->xcb->event_waiter)
330		{
331			ConditionWait(dpy, dpy->xcb->event_notify);
332			/* Maybe the other thread got us an event. */
333			continue;
334		}
335
336		if(!dpy->xcb->next_event)
337		{
338			xcb_generic_event_t *event;
339			dpy->xcb->event_waiter = 1;
340			UnlockDisplay(dpy);
341			event = xcb_wait_for_event(dpy->xcb->connection);
342			InternalLockDisplay(dpy, /* don't skip user locks */ 0);
343			dpy->xcb->event_waiter = 0;
344			ConditionBroadcast(dpy, dpy->xcb->event_notify);
345			if(!event)
346				_XIOError(dpy);
347			dpy->xcb->next_event = event;
348		}
349
350		/* We've established most of the conditions for
351		 * poll_for_response to return non-NULL. The exceptions
352		 * are connection shutdown, and finding that another
353		 * thread is waiting for the next reply we'd like to
354		 * process. */
355
356		response = poll_for_response(dpy);
357		if(response)
358			handle_response(dpy, response, False);
359		else if(dpy->xcb->pending_requests->reply_waiter)
360		{ /* need braces around ConditionWait */
361			ConditionWait(dpy, dpy->xcb->reply_notify);
362		}
363		else
364			_XIOError(dpy);
365	}
366
367	/* The preceding loop established that there is no
368	 * event_waiter--unless we just called ConditionWait because of
369	 * a reply_waiter, in which case another thread may have become
370	 * the event_waiter while we slept unlocked. */
371	if(!dpy->xcb->event_waiter)
372		while((response = poll_for_response(dpy)))
373			handle_response(dpy, response, False);
374	if(xcb_connection_has_error(dpy->xcb->connection))
375		_XIOError(dpy);
376}
377
378/*
379 * _XSend - Flush the buffer and send the client data. 32 bit word aligned
380 * transmission is used, if size is not 0 mod 4, extra bytes are transmitted.
381 *
382 * Note that the connection must not be read from once the data currently
383 * in the buffer has been written.
384 */
385void _XSend(Display *dpy, const char *data, long size)
386{
387	static const xReq dummy_request;
388	static char const pad[3];
389	struct iovec vec[3];
390	uint64_t requests;
391	_XExtension *ext;
392	xcb_connection_t *c = dpy->xcb->connection;
393	if(dpy->flags & XlibDisplayIOError)
394		return;
395
396	if(dpy->bufptr == dpy->buffer && !size)
397		return;
398
399	/* iff we asked XCB to set aside errors, we must pick those up
400	 * eventually. iff there are async handlers, we may have just
401	 * issued requests that will generate replies. in either case,
402	 * we need to remember to check later. */
403	if(dpy->xcb->event_owner != XlibOwnsEventQueue || dpy->async_handlers)
404	{
405		uint64_t sequence;
406		for(sequence = dpy->xcb->last_flushed + 1; sequence <= dpy->request; ++sequence)
407			append_pending_request(dpy, sequence);
408	}
409	requests = dpy->request - dpy->xcb->last_flushed;
410	dpy->xcb->last_flushed = dpy->request;
411
412	vec[0].iov_base = dpy->buffer;
413	vec[0].iov_len = dpy->bufptr - dpy->buffer;
414	vec[1].iov_base = (caddr_t) data;
415	vec[1].iov_len = size;
416	vec[2].iov_base = (caddr_t) pad;
417	vec[2].iov_len = -size & 3;
418
419	for(ext = dpy->flushes; ext; ext = ext->next_flush)
420	{
421		int i;
422		for(i = 0; i < 3; ++i)
423			if(vec[i].iov_len)
424				ext->before_flush(dpy, &ext->codes, vec[i].iov_base, vec[i].iov_len);
425	}
426
427	if(xcb_writev(c, vec, 3, requests) < 0)
428		_XIOError(dpy);
429	dpy->bufptr = dpy->buffer;
430	dpy->last_req = (char *) &dummy_request;
431
432	check_internal_connections(dpy);
433
434	_XSetSeqSyncFunction(dpy);
435}
436
437/*
438 * _XFlush - Flush the X request buffer.  If the buffer is empty, no
439 * action is taken.
440 */
441void _XFlush(Display *dpy)
442{
443	require_socket(dpy);
444	_XSend(dpy, NULL, 0);
445
446	_XEventsQueued(dpy, QueuedAfterReading);
447}
448
449static const XID inval_id = ~0UL;
450
451void _XIDHandler(Display *dpy)
452{
453	if (dpy->xcb->next_xid == inval_id)
454		_XAllocIDs(dpy, &dpy->xcb->next_xid, 1);
455}
456
457/* _XAllocID - resource ID allocation routine. */
458XID _XAllocID(Display *dpy)
459{
460	XID ret = dpy->xcb->next_xid;
461	assert (ret != inval_id);
462	dpy->xcb->next_xid = inval_id;
463	_XSetPrivSyncFunction(dpy);
464	return ret;
465}
466
467/* _XAllocIDs - multiple resource ID allocation routine. */
468void _XAllocIDs(Display *dpy, XID *ids, int count)
469{
470	int i;
471#ifdef XTHREADS
472	if (dpy->lock)
473		(*dpy->lock->user_lock_display)(dpy);
474	UnlockDisplay(dpy);
475#endif
476	for (i = 0; i < count; i++)
477		ids[i] = xcb_generate_id(dpy->xcb->connection);
478#ifdef XTHREADS
479	InternalLockDisplay(dpy, /* don't skip user locks */ 0);
480	if (dpy->lock)
481		(*dpy->lock->user_unlock_display)(dpy);
482#endif
483}
484
485static void _XFreeReplyData(Display *dpy, Bool force)
486{
487	if(!force && dpy->xcb->reply_consumed < dpy->xcb->reply_length)
488		return;
489	free(dpy->xcb->reply_data);
490	dpy->xcb->reply_data = NULL;
491}
492
493/*
494 * _XReply - Wait for a reply packet and copy its contents into the
495 * specified rep.
496 * extra: number of 32-bit words expected after the reply
497 * discard: should I discard data following "extra" words?
498 */
499Status _XReply(Display *dpy, xReply *rep, int extra, Bool discard)
500{
501	xcb_generic_error_t *error;
502	xcb_connection_t *c = dpy->xcb->connection;
503	char *reply;
504	PendingRequest *current;
505
506	assert(!dpy->xcb->reply_data);
507
508	if(dpy->flags & XlibDisplayIOError)
509		return 0;
510
511	_XSend(dpy, NULL, 0);
512	if(dpy->xcb->pending_requests_tail && dpy->xcb->pending_requests_tail->sequence == dpy->request)
513		current = dpy->xcb->pending_requests_tail;
514	else
515		current = append_pending_request(dpy, dpy->request);
516	/* Don't let any other thread get this reply. */
517	current->reply_waiter = 1;
518
519	while(1)
520	{
521		PendingRequest *req = dpy->xcb->pending_requests;
522		xcb_generic_reply_t *response;
523
524		if(req != current && req->reply_waiter)
525		{
526			ConditionWait(dpy, dpy->xcb->reply_notify);
527			/* Another thread got this reply. */
528			continue;
529		}
530		req->reply_waiter = 1;
531		UnlockDisplay(dpy);
532		response = xcb_wait_for_reply(c, req->sequence, &error);
533		InternalLockDisplay(dpy, /* don't skip user locks */ 0);
534
535		/* We have the response we're looking for. Now, before
536		 * letting anyone else process this sequence number, we
537		 * need to process any events that should have come
538		 * earlier. */
539
540		if(dpy->xcb->event_owner == XlibOwnsEventQueue)
541		{
542			xcb_generic_reply_t *event;
543			/* If some thread is already waiting for events,
544			 * it will get the first one. That thread must
545			 * process that event before we can continue. */
546			/* FIXME: That event might be after this reply,
547			 * and might never even come--or there might be
548			 * multiple threads trying to get events. */
549			while(dpy->xcb->event_waiter)
550			{ /* need braces around ConditionWait */
551				ConditionWait(dpy, dpy->xcb->event_notify);
552			}
553			while((event = poll_for_event(dpy)))
554				handle_response(dpy, event, True);
555		}
556
557		req->reply_waiter = 0;
558		ConditionBroadcast(dpy, dpy->xcb->reply_notify);
559		assert(XLIB_SEQUENCE_COMPARE(req->sequence, <=, dpy->request));
560		dpy->last_request_read = req->sequence;
561		if(!response)
562			dequeue_pending_request(dpy, req);
563
564		if(req == current)
565		{
566			reply = (char *) response;
567			break;
568		}
569
570		if(error)
571			handle_response(dpy, (xcb_generic_reply_t *) error, True);
572		else if(response)
573			handle_response(dpy, response, True);
574	}
575	check_internal_connections(dpy);
576
577	if(dpy->xcb->next_event && dpy->xcb->next_event->response_type == X_Error)
578	{
579		xcb_generic_event_t *event = dpy->xcb->next_event;
580		unsigned long event_sequence = dpy->last_request_read;
581		widen(&event_sequence, event->full_sequence);
582		if(event_sequence == current->sequence)
583		{
584			error = (xcb_generic_error_t *) event;
585			dpy->xcb->next_event = NULL;
586		}
587	}
588
589	if(error)
590	{
591		int ret_code;
592
593		/* Xlib is evil and assumes that even errors will be
594		 * copied into rep. */
595		memcpy(rep, error, 32);
596
597		/* do not die on "no such font", "can't allocate",
598		   "can't grab" failures */
599		switch(error->error_code)
600		{
601			case BadName:
602				switch(error->major_code)
603				{
604					case X_LookupColor:
605					case X_AllocNamedColor:
606						free(error);
607						return 0;
608				}
609				break;
610			case BadFont:
611				if(error->major_code == X_QueryFont) {
612					free(error);
613					return 0;
614				}
615				break;
616			case BadAlloc:
617			case BadAccess:
618				free(error);
619				return 0;
620		}
621
622		ret_code = handle_error(dpy, (xError *) error, True);
623		free(error);
624		return ret_code;
625	}
626
627	/* it's not an error, but we don't have a reply, so it's an I/O
628	 * error. */
629	if(!reply)
630	{
631		_XIOError(dpy);
632		return 0;
633	}
634
635	/* there's no error and we have a reply. */
636	dpy->xcb->reply_data = reply;
637	dpy->xcb->reply_consumed = sizeof(xReply) + (extra * 4);
638	dpy->xcb->reply_length = sizeof(xReply);
639	if(dpy->xcb->reply_data[0] == 1)
640		dpy->xcb->reply_length += (((xcb_generic_reply_t *) dpy->xcb->reply_data)->length * 4);
641
642	/* error: Xlib asks too much. give them what we can anyway. */
643	if(dpy->xcb->reply_length < dpy->xcb->reply_consumed)
644		dpy->xcb->reply_consumed = dpy->xcb->reply_length;
645
646	memcpy(rep, dpy->xcb->reply_data, dpy->xcb->reply_consumed);
647	_XFreeReplyData(dpy, discard);
648	return 1;
649}
650
651int _XRead(Display *dpy, char *data, long size)
652{
653	assert(size >= 0);
654	if(size == 0)
655		return 0;
656	assert(dpy->xcb->reply_data != NULL);
657	assert(dpy->xcb->reply_consumed + size <= dpy->xcb->reply_length);
658	memcpy(data, dpy->xcb->reply_data + dpy->xcb->reply_consumed, size);
659	dpy->xcb->reply_consumed += size;
660	_XFreeReplyData(dpy, False);
661	return 0;
662}
663
664/*
665 * _XReadPad - Read bytes from the socket taking into account incomplete
666 * reads.  If the number of bytes is not 0 mod 4, read additional pad
667 * bytes.
668 */
669void _XReadPad(Display *dpy, char *data, long size)
670{
671	_XRead(dpy, data, size);
672	dpy->xcb->reply_consumed += -size & 3;
673	_XFreeReplyData(dpy, False);
674}
675
676/* Read and discard "n" 8-bit bytes of data */
677void _XEatData(Display *dpy, unsigned long n)
678{
679	dpy->xcb->reply_consumed += n;
680	_XFreeReplyData(dpy, False);
681}
682