wayland-client.c 61.4 KB
Newer Older
1
/*
2 3
 * Copyright © 2008-2012 Kristian Høgsberg
 * Copyright © 2010-2012 Intel Corporation
4
 *
5 6 7 8 9 10 11
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
12
 *
13 14 15 16 17 18 19 20 21 22 23 24
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
25 26
 */

27 28
#define _GNU_SOURCE

29 30 31 32
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
33
#include <stdbool.h>
34 35 36 37 38 39
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <ctype.h>
40
#include <assert.h>
41
#include <fcntl.h>
42
#include <poll.h>
43
#include <pthread.h>
44

45
#include "wayland-util.h"
46
#include "wayland-os.h"
47
#include "wayland-client.h"
48
#include "wayland-private.h"
49

50 51
/** \cond */

52 53
enum wl_proxy_flag {
	WL_PROXY_FLAG_ID_DELETED = (1 << 0),
54 55
	WL_PROXY_FLAG_DESTROYED = (1 << 1),
	WL_PROXY_FLAG_WRAPPER = (1 << 2),
56 57
};

58 59 60 61 62
struct wl_zombie {
	int event_count;
	int *fd_count;
};

63
struct wl_proxy {
64
	struct wl_object object;
65
	struct wl_display *display;
66
	struct wl_event_queue *queue;
67 68
	uint32_t flags;
	int refcount;
69
	void *user_data;
70
	wl_dispatcher_func_t dispatcher;
71
	uint32_t version;
72
	const char * const *tag;
73 74
};

75 76
struct wl_event_queue {
	struct wl_list event_list;
77
	struct wl_display *display;
78 79
};

80 81 82
struct wl_display {
	struct wl_proxy proxy;
	struct wl_connection *connection;
83 84

	/* errno of the last wl_display error */
85
	int last_error;
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

	/* When display gets an error event from some object, it stores
	 * information about it here, so that client can get this
	 * information afterwards */
	struct {
		/* Code of the error. It can be compared to
		 * the interface's errors enumeration. */
		uint32_t code;
		/* interface (protocol) in which the error occurred */
		const struct wl_interface *interface;
		/* id of the proxy that caused the error. There's no warranty
		 * that the proxy is still valid. It's up to client how it will
		 * use it */
		uint32_t id;
	} protocol_error;
101
	int fd;
102
	struct wl_map objects;
103
	struct wl_event_queue display_queue;
104
	struct wl_event_queue default_queue;
105
	pthread_mutex_t mutex;
106 107 108 109

	int reader_count;
	uint32_t read_serial;
	pthread_cond_t reader_cond;
110 111
};

112 113
/** \endcond */

114
static int debug_client = 0;
115

116 117 118
/**
 * This helper function wakes up all threads that are
 * waiting for display->reader_cond (i. e. when reading is done,
119
 * canceled, or an error occurred)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
 *
 * NOTE: must be called with display->mutex locked
 */
static void
display_wakeup_threads(struct wl_display *display)
{
	/* Thread can get sleeping only in read_events(). If we're
	 * waking it up, it means that the read completed or was
	 * canceled, so we must increase the read_serial.
	 * This prevents from indefinite sleeping in read_events().
	 */
	++display->read_serial;

	pthread_cond_broadcast(&display->reader_cond);
}

136 137 138 139 140 141 142 143
/**
 * This function is called for local errors (no memory, server hung up)
 *
 * \param display
 * \param error    error value (EINVAL, EFAULT, ...)
 *
 * \note this function is called with display mutex locked
 */
144 145 146 147 148 149 150
static void
display_fatal_error(struct wl_display *display, int error)
{
	if (display->last_error)
		return;

	if (!error)
151
		error = EFAULT;
152 153

	display->last_error = error;
154

155
	display_wakeup_threads(display);
156 157
}

158 159
/**
 * This function is called for error events
160
 * and indicates that in some object an error occurred.
161
 * The difference between this function and display_fatal_error()
162 163 164 165 166 167 168 169
 * is that this one handles errors that will come by wire,
 * whereas display_fatal_error() is called for local errors.
 *
 * \param display
 * \param code    error code
 * \param id      id of the object that generated the error
 * \param intf    protocol interface
 */
170
static void
171 172
display_protocol_error(struct wl_display *display, uint32_t code,
		       uint32_t id, const struct wl_interface *intf)
173
{
174 175 176 177 178 179
	int err;

	if (display->last_error)
		return;

	/* set correct errno */
180
	if (intf && wl_interface_equal(intf, &wl_display_interface)) {
181 182 183 184 185 186 187 188
		switch (code) {
		case WL_DISPLAY_ERROR_INVALID_OBJECT:
		case WL_DISPLAY_ERROR_INVALID_METHOD:
			err = EINVAL;
			break;
		case WL_DISPLAY_ERROR_NO_MEMORY:
			err = ENOMEM;
			break;
189 190 191
		case WL_DISPLAY_ERROR_IMPLEMENTATION:
			err = EPROTO;
			break;
192 193 194 195 196 197 198
		default:
			err = EFAULT;
		}
	} else {
		err = EPROTO;
	}

199
	pthread_mutex_lock(&display->mutex);
200 201 202 203 204 205 206

	display->last_error = err;

	display->protocol_error.code = code;
	display->protocol_error.id = id;
	display->protocol_error.interface = intf;

207
	/*
208
	 * here it is not necessary to wake up threads like in
209 210 211 212 213 214 215 216
	 * display_fatal_error, because this function is called from
	 * an event handler and that means that read_events() is done
	 * and woke up all threads. Since wl_display_prepare_read()
	 * fails when there are events in the queue, no threads
	 * can sleep in read_events() during dispatching
	 * (and therefore during calling this function), so this is safe.
	 */

217 218 219
	pthread_mutex_unlock(&display->mutex);
}

220
static void
221
wl_event_queue_init(struct wl_event_queue *queue, struct wl_display *display)
222 223
{
	wl_list_init(&queue->event_list);
224
	queue->display = display;
225 226
}

227 228 229 230 231 232 233 234 235 236 237 238 239
static void
wl_proxy_unref(struct wl_proxy *proxy)
{
	assert(proxy->refcount > 0);
	if (--proxy->refcount > 0)
		return;

	/* If we get here, the client must have explicitly requested
	 * deletion. */
	assert(proxy->flags & WL_PROXY_FLAG_DESTROYED);
	free(proxy);
}

240
static void
241
validate_closure_objects(struct wl_closure *closure)
242 243 244 245 246 247 248 249 250 251 252 253 254 255
{
	const char *signature;
	struct argument_details arg;
	int i, count;
	struct wl_proxy *proxy;

	signature = closure->message->signature;
	count = arg_count_for_signature(signature);
	for (i = 0; i < count; i++) {
		signature = get_next_argument(signature, &arg);
		switch (arg.type) {
		case 'n':
		case 'o':
			proxy = (struct wl_proxy *) closure->args[i].o;
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
			if (proxy && proxy->flags & WL_PROXY_FLAG_DESTROYED)
				closure->args[i].o = NULL;
			break;
		default:
			break;
		}
	}
}

/* Destroys a closure which was demarshaled for dispatch; unrefs all the
 * proxies in its arguments, as well as its own proxy, and destroys the
 * closure itself. */
static void
destroy_queued_closure(struct wl_closure *closure)
{
	const char *signature;
	struct argument_details arg;
	struct wl_proxy *proxy;
	int i, count;

	signature = closure->message->signature;
	count = arg_count_for_signature(signature);
	for (i = 0; i < count; i++) {
		signature = get_next_argument(signature, &arg);
		switch (arg.type) {
		case 'n':
		case 'o':
			proxy = (struct wl_proxy *) closure->args[i].o;
			if (proxy)
285
				wl_proxy_unref(proxy);
286 287 288 289 290
			break;
		default:
			break;
		}
	}
291 292 293

	wl_proxy_unref(closure->proxy);
	wl_closure_destroy(closure);
294 295
}

296 297 298 299 300 301
static void
wl_event_queue_release(struct wl_event_queue *queue)
{
	struct wl_closure *closure;

	while (!wl_list_empty(&queue->event_list)) {
302 303
		closure = wl_container_of(queue->event_list.next,
					  closure, link);
304
		wl_list_remove(&closure->link);
305
		destroy_queued_closure(closure);
306 307 308
	}
}

309 310 311 312 313 314 315
/** Destroy an event queue
 *
 * \param queue The event queue to be destroyed
 *
 * Destroy the given event queue. Any pending event on that queue is
 * discarded.
 *
316 317 318 319
 * The \ref wl_display object used to create the queue should not be
 * destroyed until all event queues created with it are destroyed with
 * this function.
 *
320 321
 * \memberof wl_event_queue
 */
322 323 324
WL_EXPORT void
wl_event_queue_destroy(struct wl_event_queue *queue)
{
325 326 327
	struct wl_display *display = queue->display;

	pthread_mutex_lock(&display->mutex);
328 329
	wl_event_queue_release(queue);
	free(queue);
330
	pthread_mutex_unlock(&display->mutex);
331 332
}

333 334 335
/** Create a new event queue for this display
 *
 * \param display The display context object
336
 * \return A new event queue associated with this display or NULL on
337 338
 * failure.
 *
339
 * \memberof wl_display
340
 */
341 342 343 344 345 346 347 348 349
WL_EXPORT struct wl_event_queue *
wl_display_create_queue(struct wl_display *display)
{
	struct wl_event_queue *queue;

	queue = malloc(sizeof *queue);
	if (queue == NULL)
		return NULL;

350 351
	wl_event_queue_init(queue, display);

352 353 354
	return queue;
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
static int
message_count_fds(const char *signature)
{
	unsigned int count, i, fds = 0;
	struct argument_details arg;

	count = arg_count_for_signature(signature);
	for (i = 0; i < count; i++) {
		signature = get_next_argument(signature, &arg);
		if (arg.type == 'h')
			fds++;
	}

	return fds;
}

static struct wl_zombie *
prepare_zombie(struct wl_proxy *proxy)
{
	const struct wl_interface *interface = proxy->object.interface;
	const struct wl_message *message;
	int i, count;
	struct wl_zombie *zombie = NULL;

	/* If we hit an event with an FD, ensure we have a zombie object and
	 * fill the fd_count slot for that event with the number of FDs for
	 * that event. Interfaces with no events containing FDs will not have
	 * zombie objects created. */
	for (i = 0; i < interface->event_count; i++) {
		message = &interface->events[i];
		count = message_count_fds(message->signature);

		if (!count)
			continue;

		if (!zombie) {
			zombie = zalloc(sizeof(*zombie) +
				        (interface->event_count * sizeof(int)));
			if (!zombie)
				return NULL;

			zombie->event_count = interface->event_count;
			zombie->fd_count = (int *) &zombie[1];
		}

		zombie->fd_count[i] = count;
	}

	return zombie;
}

static enum wl_iterator_result
free_zombies(void *element, void *data, uint32_t flags)
{
	if (flags & WL_MAP_ENTRY_ZOMBIE)
		free(element);

	return WL_ITERATOR_CONTINUE;
}

415
static struct wl_proxy *
416 417
proxy_create(struct wl_proxy *factory, const struct wl_interface *interface,
	     uint32_t version)
418 419 420 421
{
	struct wl_proxy *proxy;
	struct wl_display *display = factory->display;

422
	proxy = zalloc(sizeof *proxy);
423 424 425 426 427 428 429
	if (proxy == NULL)
		return NULL;

	proxy->object.interface = interface;
	proxy->display = display;
	proxy->queue = factory->queue;
	proxy->refcount = 1;
430
	proxy->version = version;
431 432 433 434 435 436

	proxy->object.id = wl_map_insert_new(&display->objects, 0, proxy);

	return proxy;
}

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
/** Create a proxy object with a given interface
 *
 * \param factory Factory proxy object
 * \param interface Interface the proxy object should use
 * \return A newly allocated proxy object or NULL on failure
 *
 * This function creates a new proxy object with the supplied interface. The
 * proxy object will have an id assigned from the client id space. The id
 * should be created on the compositor side by sending an appropriate request
 * with \ref wl_proxy_marshal().
 *
 * The proxy will inherit the display and event queue of the factory object.
 *
 * \note This should not normally be used by non-generated code.
 *
 * \sa wl_display, wl_event_queue, wl_proxy_marshal()
453 454 455
 *
 * \memberof wl_proxy
 */
456
WL_EXPORT struct wl_proxy *
457
wl_proxy_create(struct wl_proxy *factory, const struct wl_interface *interface)
458
{
459
	struct wl_display *display = factory->display;
460
	struct wl_proxy *proxy;
461 462

	pthread_mutex_lock(&display->mutex);
463
	proxy = proxy_create(factory, interface, factory->version);
464
	pthread_mutex_unlock(&display->mutex);
465 466 467 468

	return proxy;
}

469 470
/* The caller should hold the display lock */
static struct wl_proxy *
471 472 473 474 475 476
wl_proxy_create_for_id(struct wl_proxy *factory,
		       uint32_t id, const struct wl_interface *interface)
{
	struct wl_proxy *proxy;
	struct wl_display *display = factory->display;

477
	proxy = zalloc(sizeof *proxy);
478 479 480 481
	if (proxy == NULL)
		return NULL;

	proxy->object.interface = interface;
482
	proxy->object.id = id;
483
	proxy->display = display;
484
	proxy->queue = factory->queue;
485
	proxy->refcount = 1;
486
	proxy->version = factory->version;
487

488
	wl_map_insert_at(&display->objects, 0, id, proxy);
489 490 491 492

	return proxy;
}

493
static void
494
proxy_destroy(struct wl_proxy *proxy)
495
{
496
	if (proxy->flags & WL_PROXY_FLAG_ID_DELETED) {
497
		wl_map_remove(&proxy->display->objects, proxy->object.id);
498
	} else if (proxy->object.id < WL_SERVER_ID_START) {
499 500 501 502
		struct wl_zombie *zombie = prepare_zombie(proxy);

		/* The map now contains the zombie entry, until the delete_id
		 * event arrives. */
503 504 505
		wl_map_insert_at(&proxy->display->objects,
				 WL_MAP_ENTRY_ZOMBIE,
				 proxy->object.id,
506
				 zombie);
507
	} else {
508
		wl_map_insert_at(&proxy->display->objects, 0,
509
				 proxy->object.id, NULL);
510
	}
511

512 513
	proxy->flags |= WL_PROXY_FLAG_DESTROYED;

514
	wl_proxy_unref(proxy);
515
}
516

517 518 519 520
/** Destroy a proxy object
 *
 * \param proxy The proxy to be destroyed
 *
521 522
 * \c proxy must not be a proxy wrapper.
 *
523 524 525 526 527 528 529
 * \memberof wl_proxy
 */
WL_EXPORT void
wl_proxy_destroy(struct wl_proxy *proxy)
{
	struct wl_display *display = proxy->display;

530 531 532
	if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
		wl_abort("Tried to destroy wrapper with wl_proxy_destroy()\n");

533 534
	pthread_mutex_lock(&display->mutex);
	proxy_destroy(proxy);
535
	pthread_mutex_unlock(&display->mutex);
536 537
}

538 539 540 541 542 543 544 545
/** Set a proxy's listener
 *
 * \param proxy The proxy object
 * \param implementation The listener to be added to proxy
 * \param data User data to be associated with the proxy
 * \return 0 on success or -1 on failure
 *
 * Set proxy's listener to \c implementation and its user data to
Tiago Vignatti's avatar
Tiago Vignatti committed
546
 * \c data. If a listener has already been set, this function
547 548 549
 * fails and nothing is changed.
 *
 * \c implementation is a vector of function pointers. For an opcode
Tiago Vignatti's avatar
Tiago Vignatti committed
550
 * \c n, \c implementation[n] should point to the handler of \c n for
551 552
 * the given object.
 *
553 554
 * \c proxy must not be a proxy wrapper.
 *
555 556
 * \memberof wl_proxy
 */
557
WL_EXPORT int
558 559
wl_proxy_add_listener(struct wl_proxy *proxy,
		      void (**implementation)(void), void *data)
560
{
561 562 563
	if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
		wl_abort("Proxy %p is a wrapper\n", proxy);

564
	if (proxy->object.implementation || proxy->dispatcher) {
565
		wl_log("proxy %p already has listener\n", proxy);
566
		return -1;
567
	}
568

569 570
	proxy->object.implementation = implementation;
	proxy->user_data = data;
571 572 573 574

	return 0;
}

575 576 577 578 579 580 581 582
/** Get a proxy's listener
 *
 * \param proxy The proxy object
 * \return The address of the proxy's listener or NULL if no listener is set
 *
 * Gets the address to the proxy's listener; which is the listener set with
 * \ref wl_proxy_add_listener.
 *
583 584
 * This function is useful in clients with multiple listeners on the same
 * interface to allow the identification of which code to execute.
585 586 587 588 589 590 591 592 593
 *
 * \memberof wl_proxy
 */
WL_EXPORT const void *
wl_proxy_get_listener(struct wl_proxy *proxy)
{
	return proxy->object.implementation;
}

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
/** Set a proxy's listener (with dispatcher)
 *
 * \param proxy The proxy object
 * \param dispatcher The dispatcher to be used for this proxy
 * \param implementation The dispatcher-specific listener implementation
 * \param data User data to be associated with the proxy
 * \return 0 on success or -1 on failure
 *
 * Set proxy's listener to use \c dispatcher_func as its dispatcher and \c
 * dispatcher_data as its dispatcher-specific implementation and its user data
 * to \c data. If a listener has already been set, this function
 * fails and nothing is changed.
 *
 * The exact details of dispatcher_data depend on the dispatcher used.  This
 * function is intended to be used by language bindings, not user code.
 *
610 611
 * \c proxy must not be a proxy wrapper.
 *
612 613 614 615 616 617 618
 * \memberof wl_proxy
 */
WL_EXPORT int
wl_proxy_add_dispatcher(struct wl_proxy *proxy,
			wl_dispatcher_func_t dispatcher,
			const void *implementation, void *data)
{
619 620 621
	if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
		wl_abort("Proxy %p is a wrapper\n", proxy);

622
	if (proxy->object.implementation || proxy->dispatcher) {
623
		wl_log("proxy %p already has listener\n", proxy);
624 625 626 627 628 629 630 631 632 633
		return -1;
	}

	proxy->object.implementation = implementation;
	proxy->dispatcher = dispatcher;
	proxy->user_data = data;

	return 0;
}

634 635 636
static struct wl_proxy *
create_outgoing_proxy(struct wl_proxy *proxy, const struct wl_message *message,
		      union wl_argument *args,
637
		      const struct wl_interface *interface, uint32_t version)
638 639 640 641 642 643 644 645 646 647 648 649 650
{
	int i, count;
	const char *signature;
	struct argument_details arg;
	struct wl_proxy *new_proxy = NULL;

	signature = message->signature;
	count = arg_count_for_signature(signature);
	for (i = 0; i < count; i++) {
		signature = get_next_argument(signature, &arg);

		switch (arg.type) {
		case 'n':
651
			new_proxy = proxy_create(proxy, interface, version);
652 653 654 655 656 657 658 659 660 661 662
			if (new_proxy == NULL)
				return NULL;

			args[i].o = &new_proxy->object;
			break;
		}
	}

	return new_proxy;
}

663 664 665 666
/** Prepare a request to be sent to the compositor
 *
 * \param proxy The proxy object
 * \param opcode Opcode of the request to be sent
667
 * \param args Extra arguments for the given request
668
 * \param interface The interface to use for the new proxy
669
 *
670 671 672
 * This function translates a request given an opcode, an interface and a
 * wl_argument array to the wire format and writes it to the connection
 * buffer.
673 674 675
 *
 * For new-id arguments, this function will allocate a new wl_proxy
 * and send the ID to the server.  The new wl_proxy will be returned
Eric Engestrom's avatar
Eric Engestrom committed
676
 * on success or NULL on error with errno set accordingly.  The newly
677
 * created proxy will inherit their version from their parent.
678 679 680 681 682 683 684 685 686 687 688 689
 *
 * \note This is intended to be used by language bindings and not in
 * non-generated code.
 *
 * \sa wl_proxy_marshal()
 *
 * \memberof wl_proxy
 */
WL_EXPORT struct wl_proxy *
wl_proxy_marshal_array_constructor(struct wl_proxy *proxy,
				   uint32_t opcode, union wl_argument *args,
				   const struct wl_interface *interface)
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
{
	return wl_proxy_marshal_array_constructor_versioned(proxy, opcode,
							    args, interface,
							    proxy->version);
}


/** Prepare a request to be sent to the compositor
 *
 * \param proxy The proxy object
 * \param opcode Opcode of the request to be sent
 * \param args Extra arguments for the given request
 * \param interface The interface to use for the new proxy
 * \param version The protocol object version for the new proxy
 *
 * Translates the request given by opcode and the extra arguments into the
 * wire format and write it to the connection buffer.  This version takes an
 * array of the union type wl_argument.
 *
 * For new-id arguments, this function will allocate a new wl_proxy
 * and send the ID to the server.  The new wl_proxy will be returned
Eric Engestrom's avatar
Eric Engestrom committed
711
 * on success or NULL on error with errno set accordingly.  The newly
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
 * created proxy will have the version specified.
 *
 * \note This is intended to be used by language bindings and not in
 * non-generated code.
 *
 * \sa wl_proxy_marshal()
 *
 * \memberof wl_proxy
 */
WL_EXPORT struct wl_proxy *
wl_proxy_marshal_array_constructor_versioned(struct wl_proxy *proxy,
					     uint32_t opcode,
					     union wl_argument *args,
					     const struct wl_interface *interface,
					     uint32_t version)
727 728 729 730 731 732 733 734 735 736
{
	struct wl_closure *closure;
	struct wl_proxy *new_proxy = NULL;
	const struct wl_message *message;

	pthread_mutex_lock(&proxy->display->mutex);

	message = &proxy->object.interface->methods[opcode];
	if (interface) {
		new_proxy = create_outgoing_proxy(proxy, message,
737 738
						  args, interface,
						  version);
739 740 741 742 743
		if (new_proxy == NULL)
			goto err_unlock;
	}

	closure = wl_closure_marshal(&proxy->object, opcode, args, message);
744 745
	if (closure == NULL)
		wl_abort("Error marshalling request: %s\n", strerror(errno));
746

747
	if (debug_client)
748 749
		wl_closure_print(closure, &proxy->object, true);

750 751
	if (wl_closure_send(closure, proxy->display->connection))
		wl_abort("Error sending request: %s\n", strerror(errno));
752 753 754 755 756 757 758 759 760 761 762

	wl_closure_destroy(closure);

 err_unlock:
	pthread_mutex_unlock(&proxy->display->mutex);

	return new_proxy;
}


/** Prepare a request to be sent to the compositor
763
 *
764 765 766
 * \param proxy The proxy object
 * \param opcode Opcode of the request to be sent
 * \param ... Extra arguments for the given request
767
 *
768 769
 * This function is similar to wl_proxy_marshal_constructor(), except
 * it doesn't create proxies for new-id arguments.
770 771 772 773
 *
 * \note This should not normally be used by non-generated code.
 *
 * \sa wl_proxy_create()
774 775 776
 *
 * \memberof wl_proxy
 */
777
WL_EXPORT void
778 779
wl_proxy_marshal(struct wl_proxy *proxy, uint32_t opcode, ...)
{
780
	union wl_argument args[WL_CLOSURE_MAX_ARGS];
781 782 783
	va_list ap;

	va_start(ap, opcode);
784 785
	wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
				 args, WL_CLOSURE_MAX_ARGS, ap);
786
	va_end(ap);
787

788
	wl_proxy_marshal_array_constructor(proxy, opcode, args, NULL);
789 790 791 792 793 794
}

/** Prepare a request to be sent to the compositor
 *
 * \param proxy The proxy object
 * \param opcode Opcode of the request to be sent
795
 * \param interface The interface to use for the new proxy
796 797
 * \param ... Extra arguments for the given request
 * \return A new wl_proxy for the new_id argument or NULL on error
798
 *
799 800 801 802
 * This function translates a request given an opcode, an interface and extra
 * arguments to the wire format and writes it to the connection buffer. The
 * types of the extra arguments must correspond to the argument types of the
 * method associated with the opcode in the interface.
803 804 805
 *
 * For new-id arguments, this function will allocate a new wl_proxy
 * and send the ID to the server.  The new wl_proxy will be returned
Eric Engestrom's avatar
Eric Engestrom committed
806
 * on success or NULL on error with errno set accordingly.  The newly
807
 * created proxy will inherit their version from their parent.
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
 *
 * \note This should not normally be used by non-generated code.
 *
 * \memberof wl_proxy
 */
WL_EXPORT struct wl_proxy *
wl_proxy_marshal_constructor(struct wl_proxy *proxy, uint32_t opcode,
			     const struct wl_interface *interface, ...)
{
	union wl_argument args[WL_CLOSURE_MAX_ARGS];
	va_list ap;

	va_start(ap, interface);
	wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
				 args, WL_CLOSURE_MAX_ARGS, ap);
	va_end(ap);

	return wl_proxy_marshal_array_constructor(proxy, opcode,
						  args, interface);
}

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843

/** Prepare a request to be sent to the compositor
 *
 * \param proxy The proxy object
 * \param opcode Opcode of the request to be sent
 * \param interface The interface to use for the new proxy
 * \param version The protocol object version of the new proxy
 * \param ... Extra arguments for the given request
 * \return A new wl_proxy for the new_id argument or NULL on error
 *
 * Translates the request given by opcode and the extra arguments into the
 * wire format and write it to the connection buffer.
 *
 * For new-id arguments, this function will allocate a new wl_proxy
 * and send the ID to the server.  The new wl_proxy will be returned
Eric Engestrom's avatar
Eric Engestrom committed
844
 * on success or NULL on error with errno set accordingly.  The newly
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
 * created proxy will have the version specified.
 *
 * \note This should not normally be used by non-generated code.
 *
 * \memberof wl_proxy
 */
WL_EXPORT struct wl_proxy *
wl_proxy_marshal_constructor_versioned(struct wl_proxy *proxy, uint32_t opcode,
				       const struct wl_interface *interface,
				       uint32_t version, ...)
{
	union wl_argument args[WL_CLOSURE_MAX_ARGS];
	va_list ap;

	va_start(ap, version);
	wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
				 args, WL_CLOSURE_MAX_ARGS, ap);
	va_end(ap);

	return wl_proxy_marshal_array_constructor_versioned(proxy, opcode,
							    args, interface,
							    version);
}

869 870 871 872 873 874 875 876
/** Prepare a request to be sent to the compositor
 *
 * \param proxy The proxy object
 * \param opcode Opcode of the request to be sent
 * \param args Extra arguments for the given request
 *
 * This function is similar to wl_proxy_marshal_array_constructor(), except
 * it doesn't create proxies for new-id arguments.
877 878 879 880 881 882 883 884 885 886 887 888
 *
 * \note This is intended to be used by language bindings and not in
 * non-generated code.
 *
 * \sa wl_proxy_marshal()
 *
 * \memberof wl_proxy
 */
WL_EXPORT void
wl_proxy_marshal_array(struct wl_proxy *proxy, uint32_t opcode,
		       union wl_argument *args)
{
889
	wl_proxy_marshal_array_constructor(proxy, opcode, args, NULL);
890 891
}

892
static void
893
display_handle_error(void *data,
894
		     struct wl_display *display, void *object,
895
		     uint32_t code, const char *message)
896
{
897
	struct wl_proxy *proxy = object;
898 899
	uint32_t object_id;
	const struct wl_interface *interface;
900

901 902 903 904 905
	if (proxy) {
		wl_log("%s@%u: error %d: %s\n",
		       proxy->object.interface->name,
		       proxy->object.id,
		       code, message);
906

907 908 909 910 911 912 913 914 915 916 917
		object_id = proxy->object.id;
		interface = proxy->object.interface;
	} else {
		wl_log("[destroyed object]: error %d: %s\n",
		       code, message);

		object_id = 0;
		interface = NULL;
	}

	display_protocol_error(display, code, object_id, interface);
918 919
}

920 921 922 923 924
static void
display_handle_delete_id(void *data, struct wl_display *display, uint32_t id)
{
	struct wl_proxy *proxy;

925 926
	pthread_mutex_lock(&display->mutex);

927
	proxy = wl_map_lookup(&display->objects, id);
928

929 930 931 932
	if (wl_object_is_zombie(&display->objects, id)) {
		/* For zombie objects, the 'proxy' is actually the zombie
		 * event-information structure, which we can free. */
		free(proxy);
933
		wl_map_remove(&display->objects, id);
934
	} else if (proxy) {
935
		proxy->flags |= WL_PROXY_FLAG_ID_DELETED;
936
	} else {
937
		wl_log("error: received delete_id for unknown id (%u)\n", id);
938
	}
939 940

	pthread_mutex_unlock(&display->mutex);
941 942
}

943
static const struct wl_display_listener display_listener = {
944
	display_handle_error,
945
	display_handle_delete_id
946 947
};

948
static int
949
connect_to_socket(const char *name)
950
{
951
	struct sockaddr_un addr;
952
	socklen_t size;
953
	const char *runtime_dir;
954
	int name_size, fd;
955 956 957 958 959 960 961 962
	bool path_is_absolute;

	if (name == NULL)
		name = getenv("WAYLAND_DISPLAY");
	if (name == NULL)
		name = "wayland-0";

	path_is_absolute = name[0] == '/';
963

964
	runtime_dir = getenv("XDG_RUNTIME_DIR");
965
	if (!runtime_dir && !path_is_absolute) {
966
		wl_log("error: XDG_RUNTIME_DIR not set in the environment.\n");
967 968 969 970
		/* to prevent programs reporting
		 * "failed to create display: Success" */
		errno = ENOENT;
		return -1;
971 972
	}

973 974
	fd = wl_os_socket_cloexec(PF_LOCAL, SOCK_STREAM, 0);
	if (fd < 0)
975 976
		return -1;

977
	memset(&addr, 0, sizeof addr);
978
	addr.sun_family = AF_LOCAL;
979 980 981 982 983 984 985 986 987 988
	if (!path_is_absolute) {
		name_size =
			snprintf(addr.sun_path, sizeof addr.sun_path,
			         "%s/%s", runtime_dir, name) + 1;
	} else {
		/* absolute path */
		name_size =
			snprintf(addr.sun_path, sizeof addr.sun_path,
			         "%s", name) + 1;
	}
989

990 991
	assert(name_size > 0);
	if (name_size > (int)sizeof addr.sun_path) {
992 993 994 995 996 997 998
		if (!path_is_absolute) {
			wl_log("error: socket path \"%s/%s\" plus null terminator"
			       " exceeds %i bytes\n", runtime_dir, name, (int) sizeof(addr.sun_path));
		} else {
			wl_log("error: socket path \"%s\" plus null terminator"
			       " exceeds %i bytes\n", name, (int) sizeof(addr.sun_path));
		}
999
		close(fd);
1000 1001 1002 1003 1004 1005
		/* to prevent programs reporting
		 * "failed to add socket: Success" */
		errno = ENAMETOOLONG;
		return -1;
	};

1006
	size = offsetof (struct sockaddr_un, sun_path) + name_size;
1007

1008 1009
	if (connect(fd, (struct sockaddr *) &addr, size) < 0) {
		close(fd);
1010 1011 1012
		return -1;
	}

1013
	return fd;
1014 1015
}

1016 1017 1018 1019 1020
/** Connect to Wayland display on an already open fd
 *
 * \param fd The fd to use for the connection
 * \return A \ref wl_display object or \c NULL on failure
 *
1021 1022 1023 1024
 * The wl_display takes ownership of the fd and will close it when the
 * display is destroyed.  The fd will also be closed in case of
 * failure.
 *
1025 1026
 * \memberof wl_display
 */
1027
WL_EXPORT struct wl_display *
1028
wl_display_connect_to_fd(int fd)
1029 1030 1031 1032 1033
{
	struct wl_display *display;
	const char *debug;

	debug = getenv("WAYLAND_DEBUG");
1034
	if (debug && (strstr(debug, "client") || strstr(debug, "1")))
1035
		debug_client = 1;
1036

1037
	display = zalloc(sizeof *display);
1038 1039
	if (display == NULL) {
		close(fd);
1040
		return NULL;
1041
	}
1042

1043
	display->fd = fd;
1044
	wl_map_init(&display->objects, WL_MAP_CLIENT_SIDE);
1045
	wl_event_queue_init(&display->default_queue, display);
1046
	wl_event_queue_init(&display->display_queue, display);
1047
	pthread_mutex_init(&display->mutex, NULL);
1048 1049
	pthread_cond_init(&display->reader_cond, NULL);
	display->reader_count = 0;
1050

1051
	wl_map_insert_new(&display->objects, 0, NULL);
1052

1053
	display->proxy.object.interface = &wl_display_interface;
1054
	display->proxy.object.id =
1055
		wl_map_insert_new(&display->objects, 0, display);
1056
	display->proxy.display = display;
1057
	display->proxy.object.implementation = (void(**)(void)) &display_listener;
1058
	display->proxy.user_data = display;
1059
	display->proxy.queue = &display->default_queue;
1060 1061
	display->proxy.flags = 0;
	display->proxy.refcount = 1;
1062

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	/* We set this version to 0 for backwards compatibility.
	 *
	 * If a client is using old versions of protocol headers,
	 * it will use unversioned API to create proxies.  Those
	 * proxies will inherit this 0.
	 *
	 * A client could be passing these proxies into library
	 * code newer than the headers that checks proxy
	 * versions.  When the proxy version is reported as 0
	 * the library will know that it can't reliably determine
	 * the proxy version, and should do whatever fallback is
	 * required.
	 *
	 * This trick forces wl_display to always report 0, but
	 * since it's a special object that we can't bind
	 * specific versions of anyway, this should be fine.
	 */
	display->proxy.version = 0;

1082
	display->connection = wl_connection_create(display->fd);
1083 1084
	if (display->connection == NULL)
		goto err_connection;
1085

1086
	return display;
1087 1088 1089 1090 1091 1092 1093 1094 1095

 err_connection:
	pthread_mutex_destroy(&display->mutex);
	pthread_cond_destroy(&display->reader_cond);
	wl_map_release(&display->objects);
	close(display->fd);
	free(display);

	return NULL;
1096 1097
}

1098 1099 1100 1101 1102 1103
/** Connect to a Wayland display
 *
 * \param name Name of the Wayland display to connect to
 * \return A \ref wl_display object or \c NULL on failure
 *
 * Connect to the Wayland display named \c name. If \c name is \c NULL,
1104 1105
 * its value will be replaced with the WAYLAND_DISPLAY environment
 * variable if it is set, otherwise display "wayland-0" will be used.
1106
 *
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
 * If \c name is an absolute path, then that path is used as-is for
 * the location of the socket at which the Wayland server is listening;
 * no qualification inside XDG_RUNTIME_DIR is attempted.
 *
 * If \c name is \c NULL and the WAYLAND_DISPLAY environment variable
 * is set to an absolute pathname, then that pathname is used as-is
 * for the socket in the same manner as if \c name held an absolute
 * path. Support for absolute paths in \c name and WAYLAND_DISPLAY
 * is present since Wayland version 1.15.
 *
1117 1118
 * \memberof wl_display
 */
1119 1120 1121 1122 1123 1124 1125 1126
WL_EXPORT struct wl_display *
wl_display_connect(const char *name)
{
	char *connection, *end;
	int flags, fd;

	connection = getenv("WAYLAND_SOCKET");
	if (connection) {
1127 1128
		int prev_errno = errno;
		errno = 0;
1129
		fd = strtol(connection, &end, 10);
1130
		if (errno != 0 || connection == end || *end != '\0')
1131
			return NULL;
1132
		errno = prev_errno;
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143

		flags = fcntl(fd, F_GETFD);
		if (flags != -1)
			fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
		unsetenv("WAYLAND_SOCKET");
	} else {
		fd = connect_to_socket(name);
		if (fd < 0)
			return NULL;
	}

1144
	return wl_display_connect_to_fd(fd);
1145 1146
}

1147 1148 1149 1150 1151 1152 1153 1154 1155
/** Close a connection to a Wayland display
 *
 * \param display The display context object
 *
 * Close the connection to \c display and free all resources associated
 * with it.
 *
 * \memberof wl_display
 */
1156
WL_EXPORT void
1157
wl_display_disconnect(struct wl_display *display)
1158
{
1159
	wl_connection_destroy(display->connection);
1160
	wl_map_for_each(&display->objects, free_zombies, NULL);
1161
	wl_map_release(&display->objects);
1162
	wl_event_queue_release(&display->default_queue);
1163
	wl_event_queue_release(&display->display_queue);
1164
	pthread_mutex_destroy(&display->mutex);
1165
	pthread_cond_destroy(&display->reader_cond);
1166
	close(display->fd);
1167

1168
	free(display);
1169 1170
}

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
/** Get a display context's file descriptor
 *
 * \param display The display context object
 * \return Display object file descriptor
 *
 * Return the file descriptor associated with a display so it can be
 * integrated into the client's main loop.
 *
 * \memberof wl_display
 */
1181
WL_EXPORT int
1182
wl_display_get_fd(struct wl_display *display)
1183
{
1184
	return display->fd;
1185 1186
}

1187
static void
1188
sync_callback(void *data, struct wl_callback *callback, uint32_t serial)
1189
{
1190
	int *done = data;
1191

1192 1193
	*done = 1;
	wl_callback_destroy(callback);
1194 1195
}

1196 1197 1198
static const struct wl_callback_listener sync_listener = {
	sync_callback
};
1199

1200 1201 1202
/** Block until all pending request are processed by the server
 *
 * \param display The display context object
1203
 * \param queue The queue on which to run the roundtrip
1204
 * \return The number of dispatched events on success or -1 on failure
1205
 *
1206 1207 1208 1209
 * This function blocks until the server has processed all currently issued
 * requests by sending a request to the display server and waiting for a
 * reply before returning.
 *
1210 1211 1212 1213
 * This function uses wl_display_dispatch_queue() internally. It is not allowed
 * to call this function while the thread is being prepared for reading events,
 * and doing so will cause a dead lock.
 *
1214 1215
 * \note This function may dispatch other events being received on the given
 * queue.
1216
 *
1217
 * \sa wl_display_roundtrip()
1218
 * \memberof wl_display
1219
 */
1220
WL_EXPORT int
1221
wl_display_roundtrip_queue(struct wl_display *display, struct wl_event_queue *queue)
1222
{
1223
	struct wl_display *display_wrapper;
1224
	struct wl_callback *callback;
1225
	int done, ret = 0;
1226 1227

	done = 0;
1228 1229 1230 1231 1232 1233 1234 1235 1236

	display_wrapper = wl_proxy_create_wrapper(display);
	if (!display_wrapper)
		return -1;

	wl_proxy_set_queue((struct wl_proxy *) display_wrapper, queue);
	callback = wl_display_sync(display_wrapper);
	wl_proxy_wrapper_destroy(display_wrapper);

1237 1238
	if (callback == NULL)
		return -1;
1239

1240
	wl_callback_add_listener(callback, &sync_listener, &done);
1241
	while (!done && ret >= 0)
1242
		ret = wl_display_dispatch_queue(display, queue);
1243

1244 1245 1246
	if (ret == -1 && !done)
		wl_callback_destroy(callback);

1247
	return ret;
1248 1249
}

1250 1251 1252 1253 1254
/** Block until all pending request are processed by the server
 *
 * \param display The display context object
 * \return The number of dispatched events on success or -1 on failure
 *
1255 1256 1257 1258
 * This function blocks until the server has processed all currently issued
 * requests by sending a request to the display server and waiting for a reply
 * before returning.
 *
1259 1260 1261 1262
 * This function uses wl_display_dispatch_queue() internally. It is not allowed
 * to call this function while the thread is being prepared for reading events,
 * and doing so will cause a dead lock.
 *
1263 1264
 * \note This function may dispatch other events being received on the default
 * queue.
1265 1266 1267 1268 1269 1270 1271 1272 1273
 *
 * \memberof wl_display
 */
WL_EXPORT int
wl_display_roundtrip(struct wl_display *display)
{
	return wl_display_roundtrip_queue(display, &display->default_queue);
}

1274
static int
1275
create_proxies(struct wl_proxy *sender, struct wl_closure *closure)
1276 1277 1278
{
	struct wl_proxy *proxy;
	const char *signature;
Daniel Stone's avatar
Daniel Stone committed
1279
	struct argument_details arg;
1280 1281
	uint32_t id;
	int i;
Daniel Stone's avatar
Daniel Stone committed
1282
	int count;
1283 1284

	signature = closure->message->signature;
1285 1286
	count = arg_count_for_signature(signature);
	for (i = 0; i < count; i++) {
Daniel Stone's avatar
Daniel Stone committed
1287 1288
		signature = get_next_argument(signature, &arg);
		switch (arg.type) {
1289
		case 'n':
1290
			id = closure->args[i].n;
Daniel Stone's avatar
Daniel Stone committed
1291
			if (id == 0) {
1292
				closure->args[i].o = NULL;
Daniel Stone's avatar
Daniel Stone committed
1293 1294
				break;
			}
1295
			proxy = wl_proxy_create_for_id(sender, id,
1296
						       closure->message->types[i]);
1297 1298
			if (proxy == NULL)
				return -1;
1299
			closure->args[i].o = (struct wl_object *)proxy;
Daniel Stone's avatar
Daniel Stone committed
1300 1301
			break;
		default:
1302 1303 1304 1305 1306 1307 1308
			break;
		}
	}

	return 0;
}

1309 1310 1311 1312 1313 1314 1315 1316 1317
static void
increase_closure_args_refcount(struct wl_closure *closure)
{
	const char *signature;
	struct argument_details arg;
	int i, count;
	struct wl_proxy *proxy;

	signature = closure->message->signature;
1318 1319
	count = arg_count_for_signature(signature);
	for (i = 0; i < count; i++) {
1320 1321 1322 1323
		signature = get_next_argument(signature, &arg);
		switch (arg.type) {
		case 'n':
		case 'o':
1324
			proxy = (struct wl_proxy *) closure->args[i].o;
1325 1326 1327 1328 1329 1330 1331
			if (proxy)
				proxy->refcount++;
			break;
		default:
			break;
		}
	}
1332 1333

	closure->proxy->refcount++;
1334 1335
}

1336
static int
1337
queue_event(struct wl_display *display, int len)
1338
{
1339 1340
	uint32_t p[2], id;
	int opcode, size;
1341
	struct wl_proxy *proxy;
1342
	struct wl_closure *closure;
1343
	const struct wl_message *message;
1344
	struct wl_event_queue *queue;
1345

1346 1347 1348 1349 1350 1351
	wl_connection_copy(display->connection, p, sizeof p);
	id = p[0];
	opcode = p[1] & 0xffff;
	size = p[1] >> 16;
	if (len < size)
		return 0;
1352

1353 1354
	/* If our proxy is gone or a zombie, just eat the event (and any FDs,
	 * if applicable). */
1355
	proxy = wl_map_lookup(&display->objects, id);
1356
	if (!proxy || wl_object_is_zombie(&display->objects, id)) {
1357 1358
		struct wl_zombie *zombie = wl_map_lookup(&display->objects, id);

1359
		if (zombie && zombie->fd_count[opcode])
1360 1361 1362
			wl_connection_close_fds_in(display->connection,
						   zombie->fd_count[opcode]);

1363
		wl_connection_consume(display->connection, size);
1364
		return size;
1365 1366
	}

1367
	message = &proxy->object.interface->events[opcode];
1368 1369
	closure = wl_connection_demarshal(display->connection, size,
					  &display->objects, message);
1370 1371
	if (!closure)
		return -1;
1372

1373 1374 1375
	if (create_proxies(proxy, closure) < 0) {
		wl_closure_destroy(closure);
		return -1;
1376 1377
	}

1378 1379 1380 1381 1382 1383
	if (wl_closure_lookup_objects(closure, &display->objects) != 0) {
		wl_closure_destroy(closure);
		return -1;
	}

	closure->proxy = proxy;
1384
	increase_closure_args_refcount(closure);
1385

1386 1387 1388 1389 1390 1391
	if (proxy == &display->proxy)
		queue = &display->display_queue;
	else
		queue = proxy->queue;

	wl_list_insert(queue->event_list.prev, &closure->link);
1392 1393 1394 1395 1396

	return size;
}

static void
1397
dispatch_event(struct wl_display *display, struct wl_event_queue *queue)
1398
{
1399
	struct wl_closure *closure;
1400
	struct wl_proxy *proxy;
1401 1402
	int opcode;
	bool proxy_destroyed;
1403

1404
	closure = wl_container_of(queue->event_list.next, closure, link);
1405
	wl_list_remove(&closure->link);
1406
	opcode = closure->opcode;
1407

1408 1409
	/* Verify that the receiving object is still valid by checking if has
	 * been destroyed by the application. */
1410
	validate_closure_objects(closure);
1411 1412
	proxy = closure->proxy;
	proxy_destroyed = !!(proxy->flags & WL_PROXY_FLAG_DESTROYED);
1413
	if (proxy_destroyed) {
1414
		destroy_queued_closure(closure);
1415 1416
		return;
	}
1417

1418
	pthread_mutex_unlock(&display->mutex);
1419

1420
	if (proxy->dispatcher) {
1421
		if (debug_client)
1422 1423 1424 1425