xcb_io.c 24.4 KB
Newer Older
1
/* Copyright (C) 2003-2006 Jamey Sharp, Josh Triplett
Jamey Sharp's avatar
Jamey Sharp committed
2
3
 * This file is licensed under the MIT license. See the file COPYING. */

4
5
6
7
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

Jamey Sharp's avatar
Jamey Sharp committed
8
#include "Xlibint.h"
9
#include "locking.h"
10
#include "Xprivate.h"
11
#include "Xxcbint.h"
12
#include <xcb/xcbext.h>
Jamey Sharp's avatar
Jamey Sharp committed
13
14

#include <assert.h>
15
#ifdef HAVE_INTTYPES_H
16
#include <inttypes.h>
17
#endif
18
#include <stdio.h>
19
#include <stdint.h>
Jamey Sharp's avatar
Jamey Sharp committed
20
21
#include <stdlib.h>
#include <string.h>
22
#include <limits.h>
23
24
25
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
Jamey Sharp's avatar
Jamey Sharp committed
26

27
28
29
30
31
32
33
34
#define xcb_fail_assert(_message, _var) { \
	unsigned int _var = 1; \
	fprintf(stderr, "[xcb] Aborting, sorry about that.\n"); \
	assert(!_var); \
}

#define throw_thread_fail_assert(_message, _var) { \
	fprintf(stderr, "[xcb] " _message "\n"); \
35
36
37
38
39
40
        if (_Xglobal_lock) { \
            fprintf(stderr, "[xcb] You called XInitThreads, this is not your fault\n"); \
        } else { \
            fprintf(stderr, "[xcb] Most likely this is a multi-threaded client " \
                            "and XInitThreads has not been called\n"); \
        } \
41
42
43
44
45
46
47
48
49
50
51
52
	xcb_fail_assert(_message, _var); \
}

/* XXX: It would probably be most useful if we stored the last-processed
 *      request, so we could find the offender from the message. */
#define throw_extlib_fail_assert(_message, _var) { \
	fprintf(stderr, "[xcb] " _message "\n"); \
	fprintf(stderr, "[xcb] This is most likely caused by a broken X " \
	                "extension library\n"); \
	xcb_fail_assert(_message, _var); \
}

53
54
55
static void return_socket(void *closure)
{
	Display *dpy = closure;
56
	InternalLockDisplay(dpy, /* don't skip user locks */ 0);
57
	_XSend(dpy, NULL, 0);
58
59
60
61
	dpy->bufmax = dpy->buffer;
	UnlockDisplay(dpy);
}

62
static Bool require_socket(Display *dpy)
63
64
65
66
67
68
69
70
71
72
{
	if(dpy->bufmax == dpy->buffer)
	{
		uint64_t sent;
		int flags = 0;
		/* if we don't own the event queue, we have to ask XCB
		 * to set our errors aside for us. */
		if(dpy->xcb->event_owner != XlibOwnsEventQueue)
			flags = XCB_REQUEST_CHECKED;
		if(!xcb_take_socket(dpy->xcb->connection, return_socket, dpy,
73
		                    flags, &sent)) {
74
			_XIOError(dpy);
75
76
			return False;
		}
77
78
		dpy->xcb->last_flushed = sent;
		X_DPY_SET_REQUEST(dpy, sent);
79
80
		dpy->bufmax = dpy->xcb->real_bufmax;
	}
81
	return True;
82
83
}

Jamey Sharp's avatar
Jamey Sharp committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* Call internal connection callbacks for any fds that are currently
 * ready to read. This function will not block unless one of the
 * callbacks blocks.
 *
 * This code borrowed from _XWaitForReadable. Inverse call tree:
 * _XRead
 *  _XWaitForWritable
 *   _XFlush
 *   _XSend
 *  _XEventsQueued
 *  _XReadEvents
 *  _XRead[0-9]+
 *   _XAllocIDs
 *  _XReply
 *  _XEatData
 * _XReadPad
 */
101
static Bool check_internal_connections(Display *dpy)
Jamey Sharp's avatar
Jamey Sharp committed
102
{
103
	struct _XConnectionInfo *ilist;
Jamey Sharp's avatar
Jamey Sharp committed
104
105
106
107
108
109
	fd_set r_mask;
	struct timeval tv;
	int result;
	int highest_fd = -1;

	if(dpy->flags & XlibDisplayProcConni || !dpy->im_fd_info)
110
		return True;
Jamey Sharp's avatar
Jamey Sharp committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

	FD_ZERO(&r_mask);
	for(ilist = dpy->im_fd_info; ilist; ilist = ilist->next)
	{
		assert(ilist->fd >= 0);
		FD_SET(ilist->fd, &r_mask);
		if(ilist->fd > highest_fd)
			highest_fd = ilist->fd;
	}
	assert(highest_fd >= 0);

	tv.tv_sec = 0;
	tv.tv_usec = 0;
	result = select(highest_fd + 1, &r_mask, NULL, NULL, &tv);

	if(result == -1)
	{
128
129
130
131
132
133
		if(errno != EINTR) {
			_XIOError(dpy);
			return False;
		}

		return True;
Jamey Sharp's avatar
Jamey Sharp committed
134
135
136
137
138
139
140
141
	}

	for(ilist = dpy->im_fd_info; result && ilist; ilist = ilist->next)
		if(FD_ISSET(ilist->fd, &r_mask))
		{
			_XProcessInternalConnection(dpy, ilist);
			--result;
		}
142
143

	return True;
Jamey Sharp's avatar
Jamey Sharp committed
144
145
}

146
static PendingRequest *append_pending_request(Display *dpy, uint64_t sequence)
147
148
149
150
151
{
	PendingRequest *node = malloc(sizeof(PendingRequest));
	assert(node);
	node->next = NULL;
	node->sequence = sequence;
152
	node->reply_waiter = 0;
153
154
	if(dpy->xcb->pending_requests_tail)
	{
155
156
157
158
159
160
161
162
163
		if (XLIB_SEQUENCE_COMPARE(dpy->xcb->pending_requests_tail->sequence,
		                          >=, node->sequence))
			throw_thread_fail_assert("Unknown sequence number "
			                         "while appending request",
			                         xcb_xlib_unknown_seq_number);
		if (dpy->xcb->pending_requests_tail->next != NULL)
			throw_thread_fail_assert("Unknown request in queue "
			                         "while appending request",
			                         xcb_xlib_unknown_req_pending);
164
165
166
167
168
169
170
171
172
173
		dpy->xcb->pending_requests_tail->next = node;
	}
	else
		dpy->xcb->pending_requests = node;
	dpy->xcb->pending_requests_tail = node;
	return node;
}

static void dequeue_pending_request(Display *dpy, PendingRequest *req)
{
174
175
176
177
178
	if (req != dpy->xcb->pending_requests)
		throw_thread_fail_assert("Unknown request in queue while "
		                         "dequeuing",
		                         xcb_xlib_unknown_req_in_deq);

179
180
181
	dpy->xcb->pending_requests = req->next;
	if(!dpy->xcb->pending_requests)
	{
182
183
184
185
		if (req != dpy->xcb->pending_requests_tail)
			throw_thread_fail_assert("Unknown request in queue "
			                         "while dequeuing",
			                         xcb_xlib_unknown_req_in_deq);
186
187
		dpy->xcb->pending_requests_tail = NULL;
	}
188
189
190
191
192
193
	else if (XLIB_SEQUENCE_COMPARE(req->sequence, >=,
	                               dpy->xcb->pending_requests->sequence))
		throw_thread_fail_assert("Unknown sequence number while "
		                         "dequeuing request",
		                         xcb_xlib_threads_sequence_lost);

194
195
196
	free(req);
}

197
static int handle_error(Display *dpy, xError *err, Bool in_XReply)
198
199
200
{
	_XExtension *ext;
	int ret_code;
201
202
203
204
205
206
207
208
209
210
	/* Oddly, Xlib only allows extensions to suppress errors when
	 * those errors were seen by _XReply. */
	if(in_XReply)
		/*
		 * we better see if there is an extension who may
		 * want to suppress the error.
		 */
		for(ext = dpy->ext_procs; ext; ext = ext->next)
			if(ext->error && (*ext->error)(dpy, err, &ext->codes, &ret_code))
				return ret_code;
211
212
213
214
	_XError(dpy, err);
	return 0;
}

215
216
217
218
/* Widen a 32-bit sequence number into a 64bit (uint64_t) sequence number.
 * Treating the comparison as a 1 and shifting it avoids a conditional branch.
 */
static void widen(uint64_t *wide, unsigned int narrow)
219
{
220
	uint64_t new = (*wide & ~((uint64_t)0xFFFFFFFFUL)) | narrow;
221
222
223
224
225
226
	/* If just copying the upper dword of *wide makes the number
	 * go down by more than 2^31, then it means that the lower
	 * dword has wrapped (or we have skipped 2^31 requests, which
	 * is hopefully improbable), so we add a carry. */
	uint64_t wraps = new + (1UL << 31) < *wide;
	*wide = new + (wraps << 32);
227
228
}

229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/* Thread-safety rules:
 *
 * At most one thread can be reading from XCB's event queue at a time.
 * If you are not the current event-reading thread and you need to find
 * out if an event is available, you must wait.
 *
 * The same rule applies for reading replies.
 *
 * A single thread cannot be both the the event-reading and the
 * reply-reading thread at the same time.
 *
 * We always look at both the current event and the first pending reply
 * to decide which to process next.
 *
 * We always process all responses in sequence-number order, which may
 * mean waiting for another thread (either the event_waiter or the
 * reply_waiter) to handle an earlier response before we can process or
 * return a later one. If so, we wait on the corresponding condition
 * variable for that thread to process the response and wake us up.
 */
249

250
static xcb_generic_reply_t *poll_for_event(Display *dpy, Bool queued_only)
251
252
{
	/* Make sure the Display's sequence numbers are valid */
253
254
	if (!require_socket(dpy))
		return NULL;
255

256
257
258
	/* Precondition: This thread can safely get events from XCB. */
	assert(dpy->xcb->event_owner == XlibOwnsEventQueue && !dpy->xcb->event_waiter);

259
260
261
262
263
264
	if(!dpy->xcb->next_event) {
		if(queued_only)
			dpy->xcb->next_event = xcb_poll_for_queued_event(dpy->xcb->connection);
		else
			dpy->xcb->next_event = xcb_poll_for_event(dpy->xcb->connection);
	}
265
266

	if(dpy->xcb->next_event)
267
	{
268
		PendingRequest *req = dpy->xcb->pending_requests;
269
		xcb_generic_event_t *event = dpy->xcb->next_event;
270
		uint64_t event_sequence = X_DPY_GET_LAST_REQUEST_READ(dpy);
271
272
273
		widen(&event_sequence, event->full_sequence);
		if(!req || XLIB_SEQUENCE_COMPARE(event_sequence, <, req->sequence)
		        || (event->response_type != X_Error && event_sequence == req->sequence))
274
		{
275
276
			uint64_t request = X_DPY_GET_REQUEST(dpy);
			if (XLIB_SEQUENCE_COMPARE(event_sequence, >, request))
277
278
279
280
281
282
			{
				throw_thread_fail_assert("Unknown sequence "
				                         "number while "
							 "processing queue",
				                xcb_xlib_threads_sequence_lost);
			}
283
			X_DPY_SET_LAST_REQUEST_READ(dpy, event_sequence);
284
285
			dpy->xcb->next_event = NULL;
			return (xcb_generic_reply_t *) event;
286
		}
287
288
289
290
291
292
293
	}
	return NULL;
}

static xcb_generic_reply_t *poll_for_response(Display *dpy)
{
	void *response;
294
	xcb_generic_reply_t *event;
295
	PendingRequest *req;
296
297

	while(1)
298
	{
299
		xcb_generic_error_t *error = NULL;
300
		uint64_t request;
301
		Bool poll_queued_only = dpy->xcb->next_response != NULL;
302

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
		/* Step 1: is there an event in our queue before the next
		 * reply/error? Return that first.
		 *
		 * If we don't have a reply/error saved from an earlier
		 * invocation we check incoming events too, otherwise only
		 * the ones already queued.
		 */
		response = poll_for_event(dpy, poll_queued_only);
		if(response)
			break;

		/* Step 2:
		 * Response is NULL, i.e. we have no events.
		 * If we are not waiting for a reply or some other thread
		 * had dibs on the next reply, exit.
		 */
		req = dpy->xcb->pending_requests;
		if(!req || req->reply_waiter)
321
			break;
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367

		/* Step 3:
		 * We have some response (error or reply) related to req
		 * saved from an earlier invocation of this function. Let's
		 * use that one.
		 */
		if(dpy->xcb->next_response)
		{
			if (((xcb_generic_reply_t*)dpy->xcb->next_response)->response_type == X_Error)
			{
				error = dpy->xcb->next_response;
				response = NULL;
			}
			else
			{
				response = dpy->xcb->next_response;
				error = NULL;
			}
			dpy->xcb->next_response = NULL;
		}
		else
		{
			/* Step 4: pull down the next response from the wire. This
			 * should be the 99% case.
			 * xcb_poll_for_reply64() may also pull down events that
			 * happened before the reply.
			 */
			if(!xcb_poll_for_reply64(dpy->xcb->connection, req->sequence,
						 &response, &error)) {
				/* if there is no reply/error, xcb_poll_for_reply64
				 * may have read events. Return that. */
				response = poll_for_event(dpy, True);
				break;
			}

			/* Step 5: we have a new response, but we may also have some
			 * events that happened before that response. Return those
			 * first and save our reply/error for the next invocation.
			 */
			event = poll_for_event(dpy, True);
			if(event)
			{
				dpy->xcb->next_response = error ? error : response;
				response = event;
				break;
			}
368
369
		}

370
		/* Step 6: actually handle the reply/error now... */
371
		request = X_DPY_GET_REQUEST(dpy);
372
		if(XLIB_SEQUENCE_COMPARE(req->sequence, >, request))
373
374
375
376
377
		{
			throw_thread_fail_assert("Unknown sequence number "
			                         "while awaiting reply",
			                        xcb_xlib_threads_sequence_lost);
		}
378
		X_DPY_SET_LAST_REQUEST_READ(dpy, req->sequence);
379
380
381
		if(response)
			break;
		dequeue_pending_request(dpy, req);
382
383
384
		if(error)
			return (xcb_generic_reply_t *) error;
	}
385
	return response;
386
387
388
389
390
391
392
393
394
}

static void handle_response(Display *dpy, xcb_generic_reply_t *response, Bool in_XReply)
{
	_XAsyncHandler *async, *next;
	switch(response->response_type)
	{
	case X_Reply:
		for(async = dpy->async_handlers; async; async = next)
395
		{
396
397
398
			next = async->next;
			if(async->handler(dpy, (xReply *) response, (char *) response, sizeof(xReply) + (response->length << 2), async->data))
				break;
399
		}
400
401
402
403
404
405
406
407
408
409
410
411
412
		break;

	case X_Error:
		handle_error(dpy, (xError *) response, in_XReply);
		break;

	default: /* event */
		/* GenericEvents may be > 32 bytes. In this case, the
		 * event struct is trailed by the additional bytes. the
		 * xcb_generic_event_t struct uses 4 bytes for internal
		 * numbering, so we need to shift the trailing data to
		 * be after the first 32 bytes. */
		if(response->response_type == GenericEvent && ((xcb_ge_event_t *) response)->length)
413
		{
414
415
			xcb_ge_event_t *event = (xcb_ge_event_t *) response;
			memmove(&event->full_sequence, &event[1], event->length * 4);
416
		}
417
418
		_XEnq(dpy, (xEvent *) response);
		break;
419
	}
420
	free(response);
421
422
423
424
}

int _XEventsQueued(Display *dpy, int mode)
{
425
	xcb_generic_reply_t *response;
426
427
	if(dpy->flags & XlibDisplayIOError)
		return 0;
428
	if(dpy->xcb->event_owner != XlibOwnsEventQueue)
Jamey Sharp's avatar
Jamey Sharp committed
429
430
431
		return 0;

	if(mode == QueuedAfterFlush)
432
		_XSend(dpy, NULL, 0);
433
434
	else if (!check_internal_connections(dpy))
		return 0;
435
436
437
438
439
440
441
442

	/* If another thread is blocked waiting for events, then we must
	 * let that thread pick up the next event. Since it blocked, we
	 * can reasonably claim there are no new events right now. */
	if(!dpy->xcb->event_waiter)
	{
		while((response = poll_for_response(dpy)))
			handle_response(dpy, response, False);
443
		if(xcb_connection_has_error(dpy->xcb->connection)) {
444
			_XIOError(dpy);
445
446
			return 0;
		}
447
	}
Jamey Sharp's avatar
Jamey Sharp committed
448
449
450
451
452
453
454
455
	return dpy->qlen;
}

/* _XReadEvents - Flush the output queue,
 * then read as many events as possible (but at least 1) and enqueue them
 */
void _XReadEvents(Display *dpy)
{
456
457
458
	xcb_generic_reply_t *response;
	unsigned long serial;

459
460
	if(dpy->flags & XlibDisplayIOError)
		return;
461
	_XSend(dpy, NULL, 0);
462
	if(dpy->xcb->event_owner != XlibOwnsEventQueue)
Jamey Sharp's avatar
Jamey Sharp committed
463
		return;
464
465
	if (!check_internal_connections(dpy))
		return;
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482

	serial = dpy->next_event_serial_num;
	while(serial == dpy->next_event_serial_num || dpy->qlen == 0)
	{
		if(dpy->xcb->event_waiter)
		{
			ConditionWait(dpy, dpy->xcb->event_notify);
			/* Maybe the other thread got us an event. */
			continue;
		}

		if(!dpy->xcb->next_event)
		{
			xcb_generic_event_t *event;
			dpy->xcb->event_waiter = 1;
			UnlockDisplay(dpy);
			event = xcb_wait_for_event(dpy->xcb->connection);
483
484
485
486
487
488
489
490
491
			/* It appears that classic Xlib respected user
			 * locks when waking up after waiting for
			 * events. However, if this thread did not have
			 * any user locks, and another thread takes a
			 * user lock and tries to read events, then we'd
			 * deadlock. So we'll choose to let the thread
			 * that got in first consume events, despite the
			 * later thread's user locks. */
			InternalLockDisplay(dpy, /* ignore user locks */ 1);
492
493
494
			dpy->xcb->event_waiter = 0;
			ConditionBroadcast(dpy, dpy->xcb->event_notify);
			if(!event)
495
			{
496
				_XIOError(dpy);
497
498
				return;
			}
499
500
501
502
503
504
505
506
507
508
509
510
			dpy->xcb->next_event = event;
		}

		/* We've established most of the conditions for
		 * poll_for_response to return non-NULL. The exceptions
		 * are connection shutdown, and finding that another
		 * thread is waiting for the next reply we'd like to
		 * process. */

		response = poll_for_response(dpy);
		if(response)
			handle_response(dpy, response, False);
511
		else if(dpy->xcb->pending_requests->reply_waiter)
512
513
514
515
		{ /* need braces around ConditionWait */
			ConditionWait(dpy, dpy->xcb->reply_notify);
		}
		else
516
517
518
519
		{
		        _XIOError(dpy);
		        return;
		}
520
521
522
523
524
525
526
527
528
529
530
	}

	/* The preceding loop established that there is no
	 * event_waiter--unless we just called ConditionWait because of
	 * a reply_waiter, in which case another thread may have become
	 * the event_waiter while we slept unlocked. */
	if(!dpy->xcb->event_waiter)
		while((response = poll_for_response(dpy)))
			handle_response(dpy, response, False);
	if(xcb_connection_has_error(dpy->xcb->connection))
		_XIOError(dpy);
Jamey Sharp's avatar
Jamey Sharp committed
531
532
533
534
535
536
537
538
539
540
541
}

/*
 * _XSend - Flush the buffer and send the client data. 32 bit word aligned
 * transmission is used, if size is not 0 mod 4, extra bytes are transmitted.
 *
 * Note that the connection must not be read from once the data currently
 * in the buffer has been written.
 */
void _XSend(Display *dpy, const char *data, long size)
{
542
543
544
545
	static const xReq dummy_request;
	static char const pad[3];
	struct iovec vec[3];
	uint64_t requests;
546
	uint64_t dpy_request;
547
	_XExtension *ext;
548
	xcb_connection_t *c = dpy->xcb->connection;
549
550
	if(dpy->flags & XlibDisplayIOError)
		return;
Jamey Sharp's avatar
Jamey Sharp committed
551

552
553
554
	if(dpy->bufptr == dpy->buffer && !size)
		return;

555
556
557
558
	/* append_pending_request does not alter the dpy request number
	 * therefore we can get it outside of the loop and the if
	 */
	dpy_request = X_DPY_GET_REQUEST(dpy);
559
560
561
562
563
564
	/* iff we asked XCB to set aside errors, we must pick those up
	 * eventually. iff there are async handlers, we may have just
	 * issued requests that will generate replies. in either case,
	 * we need to remember to check later. */
	if(dpy->xcb->event_owner != XlibOwnsEventQueue || dpy->async_handlers)
	{
565
		uint64_t sequence;
566
		for(sequence = dpy->xcb->last_flushed + 1; sequence <= dpy_request; ++sequence)
567
			append_pending_request(dpy, sequence);
568
	}
569
570
	requests = dpy_request - dpy->xcb->last_flushed;
	dpy->xcb->last_flushed = dpy_request;
Jamey Sharp's avatar
Jamey Sharp committed
571

572
573
	vec[0].iov_base = dpy->buffer;
	vec[0].iov_len = dpy->bufptr - dpy->buffer;
Jon Turney's avatar
Jon Turney committed
574
	vec[1].iov_base = (char *)data;
575
	vec[1].iov_len = size;
Jon Turney's avatar
Jon Turney committed
576
	vec[2].iov_base = (char *)pad;
577
	vec[2].iov_len = -size & 3;
Jamey Sharp's avatar
Jamey Sharp committed
578

579
580
581
582
583
584
585
	for(ext = dpy->flushes; ext; ext = ext->next_flush)
	{
		int i;
		for(i = 0; i < 3; ++i)
			if(vec[i].iov_len)
				ext->before_flush(dpy, &ext->codes, vec[i].iov_base, vec[i].iov_len);
	}
Jamey Sharp's avatar
Jamey Sharp committed
586

587
	if(xcb_writev(c, vec, 3, requests) < 0) {
588
		_XIOError(dpy);
589
590
		return;
	}
591
592
	dpy->bufptr = dpy->buffer;
	dpy->last_req = (char *) &dummy_request;
Jamey Sharp's avatar
Jamey Sharp committed
593

594
595
	if (!check_internal_connections(dpy))
		return;
Jamey Sharp's avatar
Jamey Sharp committed
596

597
	_XSetSeqSyncFunction(dpy);
Jamey Sharp's avatar
Jamey Sharp committed
598
599
600
601
602
603
604
605
}

/*
 * _XFlush - Flush the X request buffer.  If the buffer is empty, no
 * action is taken.
 */
void _XFlush(Display *dpy)
{
606
607
608
	if (!require_socket(dpy))
		return;

609
	_XSend(dpy, NULL, 0);
Jamey Sharp's avatar
Jamey Sharp committed
610
611
612
613

	_XEventsQueued(dpy, QueuedAfterReading);
}

614
615
static const XID inval_id = ~0UL;

616
void _XIDHandler(Display *dpy)
617
{
618
619
	if (dpy->xcb->next_xid == inval_id)
		_XAllocIDs(dpy, &dpy->xcb->next_xid, 1);
620
621
}

Jamey Sharp's avatar
Jamey Sharp committed
622
623
624
/* _XAllocID - resource ID allocation routine. */
XID _XAllocID(Display *dpy)
{
625
	XID ret = dpy->xcb->next_xid;
626
627
628
	assert (ret != inval_id);
	dpy->xcb->next_xid = inval_id;
	_XSetPrivSyncFunction(dpy);
629
	return ret;
Jamey Sharp's avatar
Jamey Sharp committed
630
631
632
633
634
635
}

/* _XAllocIDs - multiple resource ID allocation routine. */
void _XAllocIDs(Display *dpy, XID *ids, int count)
{
	int i;
636
637
638
639
640
#ifdef XTHREADS
	if (dpy->lock)
		(*dpy->lock->user_lock_display)(dpy);
	UnlockDisplay(dpy);
#endif
Jamey Sharp's avatar
Jamey Sharp committed
641
	for (i = 0; i < count; i++)
642
		ids[i] = xcb_generate_id(dpy->xcb->connection);
643
#ifdef XTHREADS
644
	InternalLockDisplay(dpy, /* don't skip user locks */ 0);
645
646
647
	if (dpy->lock)
		(*dpy->lock->user_unlock_display)(dpy);
#endif
Jamey Sharp's avatar
Jamey Sharp committed
648
649
650
651
}

static void _XFreeReplyData(Display *dpy, Bool force)
{
652
	if(!force && dpy->xcb->reply_consumed < dpy->xcb->reply_length)
Jamey Sharp's avatar
Jamey Sharp committed
653
		return;
654
	free(dpy->xcb->reply_data);
655
	dpy->xcb->reply_data = NULL;
Jamey Sharp's avatar
Jamey Sharp committed
656
657
658
659
660
661
662
663
664
665
}

/*
 * _XReply - Wait for a reply packet and copy its contents into the
 * specified rep.
 * extra: number of 32-bit words expected after the reply
 * discard: should I discard data following "extra" words?
 */
Status _XReply(Display *dpy, xReply *rep, int extra, Bool discard)
{
Ian Osgood's avatar
Ian Osgood committed
666
	xcb_generic_error_t *error;
667
	xcb_connection_t *c = dpy->xcb->connection;
Jamey Sharp's avatar
Jamey Sharp committed
668
	char *reply;
669
	PendingRequest *current;
670
	uint64_t dpy_request;
Jamey Sharp's avatar
Jamey Sharp committed
671

672
673
674
	if (dpy->xcb->reply_data)
		throw_extlib_fail_assert("Extra reply data still left in queue",
		                         xcb_xlib_extra_reply_data_left);
Jamey Sharp's avatar
Jamey Sharp committed
675

676
677
678
	if(dpy->flags & XlibDisplayIOError)
		return 0;

679
	_XSend(dpy, NULL, 0);
680
681
682
	dpy_request = X_DPY_GET_REQUEST(dpy);
	if(dpy->xcb->pending_requests_tail
	   && dpy->xcb->pending_requests_tail->sequence == dpy_request)
683
684
		current = dpy->xcb->pending_requests_tail;
	else
685
		current = append_pending_request(dpy, dpy_request);
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
	/* Don't let any other thread get this reply. */
	current->reply_waiter = 1;

	while(1)
	{
		PendingRequest *req = dpy->xcb->pending_requests;
		xcb_generic_reply_t *response;

		if(req != current && req->reply_waiter)
		{
			ConditionWait(dpy, dpy->xcb->reply_notify);
			/* Another thread got this reply. */
			continue;
		}
		req->reply_waiter = 1;
		UnlockDisplay(dpy);
702
		response = xcb_wait_for_reply64(c, req->sequence, &error);
703
		/* Any user locks on another thread must have been taken
704
		 * while we slept in xcb_wait_for_reply64. Classic Xlib
705
706
		 * ignored those user locks in this case, so we do too. */
		InternalLockDisplay(dpy, /* ignore user locks */ 1);
707
708
709
710
711
712
713
714
715

		/* We have the response we're looking for. Now, before
		 * letting anyone else process this sequence number, we
		 * need to process any events that should have come
		 * earlier. */

		if(dpy->xcb->event_owner == XlibOwnsEventQueue)
		{
			xcb_generic_reply_t *event;
Tatu Frisk's avatar
Tatu Frisk committed
716
717
718
719
720
721
722
723

			/* Assume event queue is empty if another thread is blocking
			 * waiting for event. */
			if(!dpy->xcb->event_waiter)
			{
				while((event = poll_for_response(dpy)))
					handle_response(dpy, event, True);
                        }
724
		}
Jamey Sharp's avatar
Jamey Sharp committed
725

726
727
		req->reply_waiter = 0;
		ConditionBroadcast(dpy, dpy->xcb->reply_notify);
728
729
		dpy_request = X_DPY_GET_REQUEST(dpy);
		if(XLIB_SEQUENCE_COMPARE(req->sequence, >, dpy_request)) {
730
731
732
733
			throw_thread_fail_assert("Unknown sequence number "
			                         "while processing reply",
			                        xcb_xlib_threads_sequence_lost);
		}
734
		X_DPY_SET_LAST_REQUEST_READ(dpy, req->sequence);
735
736
737
738
739
740
741
742
743
744
745
746
747
748
		if(!response)
			dequeue_pending_request(dpy, req);

		if(req == current)
		{
			reply = (char *) response;
			break;
		}

		if(error)
			handle_response(dpy, (xcb_generic_reply_t *) error, True);
		else if(response)
			handle_response(dpy, response, True);
	}
749
750
	if (!check_internal_connections(dpy))
		return 0;
751
752
753
754

	if(dpy->xcb->next_event && dpy->xcb->next_event->response_type == X_Error)
	{
		xcb_generic_event_t *event = dpy->xcb->next_event;
755
756
		uint64_t last_request_read = X_DPY_GET_LAST_REQUEST_READ(dpy);
		uint64_t event_sequence = last_request_read;
757
		widen(&event_sequence, event->full_sequence);
758
		if(event_sequence == last_request_read)
759
760
761
762
763
		{
			error = (xcb_generic_error_t *) event;
			dpy->xcb->next_event = NULL;
		}
	}
764

Jamey Sharp's avatar
Jamey Sharp committed
765
766
767
768
769
770
771
772
773
774
	if(error)
	{
		int ret_code;

		/* Xlib is evil and assumes that even errors will be
		 * copied into rep. */
		memcpy(rep, error, 32);

		/* do not die on "no such font", "can't allocate",
		   "can't grab" failures */
775
		switch(error->error_code)
Jamey Sharp's avatar
Jamey Sharp committed
776
777
		{
			case BadName:
778
				switch(error->major_code)
Jamey Sharp's avatar
Jamey Sharp committed
779
780
781
				{
					case X_LookupColor:
					case X_AllocNamedColor:
782
						free(error);
Jamey Sharp's avatar
Jamey Sharp committed
783
784
785
786
						return 0;
				}
				break;
			case BadFont:
787
				if(error->major_code == X_QueryFont) {
788
					free(error);
Jamey Sharp's avatar
Jamey Sharp committed
789
					return 0;
790
				}
Jamey Sharp's avatar
Jamey Sharp committed
791
792
793
				break;
			case BadAlloc:
			case BadAccess:
794
				free(error);
Jamey Sharp's avatar
Jamey Sharp committed
795
796
797
				return 0;
		}

798
		ret_code = handle_error(dpy, (xError *) error, True);
799
		free(error);
800
		return ret_code;
Jamey Sharp's avatar
Jamey Sharp committed
801
802
803
804
	}

	/* it's not an error, but we don't have a reply, so it's an I/O
	 * error. */
805
	if(!reply) {
Jamey Sharp's avatar
Jamey Sharp committed
806
		_XIOError(dpy);
807
808
		return 0;
	}
Jamey Sharp's avatar
Jamey Sharp committed
809
810

	/* there's no error and we have a reply. */
811
812
813
814
815
	dpy->xcb->reply_data = reply;
	dpy->xcb->reply_consumed = sizeof(xReply) + (extra * 4);
	dpy->xcb->reply_length = sizeof(xReply);
	if(dpy->xcb->reply_data[0] == 1)
		dpy->xcb->reply_length += (((xcb_generic_reply_t *) dpy->xcb->reply_data)->length * 4);
Jamey Sharp's avatar
Jamey Sharp committed
816
817

	/* error: Xlib asks too much. give them what we can anyway. */
818
819
	if(dpy->xcb->reply_length < dpy->xcb->reply_consumed)
		dpy->xcb->reply_consumed = dpy->xcb->reply_length;
Jamey Sharp's avatar
Jamey Sharp committed
820

821
	memcpy(rep, dpy->xcb->reply_data, dpy->xcb->reply_consumed);
Jamey Sharp's avatar
Jamey Sharp committed
822
823
824
825
826
827
828
829
830
	_XFreeReplyData(dpy, discard);
	return 1;
}

int _XRead(Display *dpy, char *data, long size)
{
	assert(size >= 0);
	if(size == 0)
		return 0;
831
832
833
834
	if(dpy->xcb->reply_data == NULL ||
	   dpy->xcb->reply_consumed + size > dpy->xcb->reply_length)
		throw_extlib_fail_assert("Too much data requested from _XRead",
		                         xcb_xlib_too_much_data_requested);
835
836
	memcpy(data, dpy->xcb->reply_data + dpy->xcb->reply_consumed, size);
	dpy->xcb->reply_consumed += size;
Jamey Sharp's avatar
Jamey Sharp committed
837
838
839
840
841
842
843
844
845
846
847
848
	_XFreeReplyData(dpy, False);
	return 0;
}

/*
 * _XReadPad - Read bytes from the socket taking into account incomplete
 * reads.  If the number of bytes is not 0 mod 4, read additional pad
 * bytes.
 */
void _XReadPad(Display *dpy, char *data, long size)
{
	_XRead(dpy, data, size);
849
	dpy->xcb->reply_consumed += -size & 3;
Jamey Sharp's avatar
Jamey Sharp committed
850
851
852
853
854
855
	_XFreeReplyData(dpy, False);
}

/* Read and discard "n" 8-bit bytes of data */
void _XEatData(Display *dpy, unsigned long n)
{
856
	dpy->xcb->reply_consumed += n;
Jamey Sharp's avatar
Jamey Sharp committed
857
858
	_XFreeReplyData(dpy, False);
}
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874

/*
 * Read and discard "n" 32-bit words of data
 * Matches the units of the length field in X protocol replies, and provides
 * a single implementation of overflow checking to avoid having to replicate
 * those checks in every caller.
 */
void _XEatDataWords(Display *dpy, unsigned long n)
{
	if (n < ((INT_MAX - dpy->xcb->reply_consumed) >> 2))
		dpy->xcb->reply_consumed += (n << 2);
	else
		/* Overflow would happen, so just eat the rest of the reply */
		dpy->xcb->reply_consumed = dpy->xcb->reply_length;
	_XFreeReplyData(dpy, False);
}
875
876
877
878
879
880
881
882
883
884
885

unsigned long
_XNextRequest(Display *dpy)
{
    /* This will update dpy->request. The assumption is that the next thing
     * that the application will do is make a request so there's little
     * overhead.
     */
    require_socket(dpy);
    return NextRequest(dpy);
}