1 /*
2  * Copyright © 2008-2012 Kristian Høgsberg
3  * Copyright © 2010-2012 Intel Corporation
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the
14  * next paragraph) shall be included in all copies or substantial
15  * portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24  * SOFTWARE.
25  */
26 
27 #define _GNU_SOURCE
28 
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <stddef.h>
32 #include <stdio.h>
33 #include <stdbool.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #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 /** \cond */
51 
52 enum wl_proxy_flag {
53 	WL_PROXY_FLAG_ID_DELETED = (1 << 0),
54 	WL_PROXY_FLAG_DESTROYED = (1 << 1),
55 	WL_PROXY_FLAG_WRAPPER = (1 << 2),
56 };
57 
58 struct wl_zombie {
59 	int event_count;
60 	int *fd_count;
61 };
62 
63 struct wl_proxy {
64 	struct wl_object object;
65 	struct wl_display *display;
66 	struct wl_event_queue *queue;
67 	uint32_t flags;
68 	int refcount;
69 	void *user_data;
70 	wl_dispatcher_func_t dispatcher;
71 	uint32_t version;
72 	const char * const *tag;
73 };
74 
75 struct wl_event_queue {
76 	struct wl_list event_list;
77 	struct wl_display *display;
78 };
79 
80 struct wl_display {
81 	struct wl_proxy proxy;
82 	struct wl_connection *connection;
83 
84 	/* errno of the last wl_display error */
85 	int last_error;
86 
87 	/* When display gets an error event from some object, it stores
88 	 * information about it here, so that client can get this
89 	 * information afterwards */
90 	struct {
91 		/* Code of the error. It can be compared to
92 		 * the interface's errors enumeration. */
93 		uint32_t code;
94 		/* interface (protocol) in which the error occurred */
95 		const struct wl_interface *interface;
96 		/* id of the proxy that caused the error. There's no warranty
97 		 * that the proxy is still valid. It's up to client how it will
98 		 * use it */
99 		uint32_t id;
100 	} 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 	int reader_count;
108 	uint32_t read_serial;
109 	pthread_cond_t reader_cond;
110 
111 	struct wl_list protocol_loggers;
112 };
113 
114 /** \endcond */
115 
116 struct wl_protocol_logger_client {
117 	struct wl_list link;
118 	wl_protocol_logger_client_func_t func;
119 	void *user_data;
120 };
121 
122 static int debug_client = 0;
123 
124 static void
log_closure(struct wl_closure * closure,struct wl_proxy * proxy,int send)125 log_closure(struct wl_closure *closure, struct wl_proxy* proxy, int send)
126 {
127 	struct wl_display *display = proxy->display;
128 	struct wl_protocol_logger_client *protocol_logger;
129 	struct wl_protocol_logger_client_message message;
130 
131 	if (debug_client)
132 		wl_closure_print(closure, &proxy->object, send);
133 
134 	if (!wl_list_empty(&display->protocol_loggers)) {
135 		message.proxy = proxy;
136 		message.message_opcode = closure->opcode;
137 		message.message = closure->message;
138 		message.arguments_count = closure->count;
139 		message.arguments = closure->args;
140 		wl_list_for_each(protocol_logger, &display->protocol_loggers,
141 				 link) {
142 			protocol_logger->func(
143 				protocol_logger->user_data,
144 				send ? WL_PROTOCOL_LOGGER_CLIENT_REQUEST :
145 				       WL_PROTOCOL_LOGGER_CLIENT_EVENT,
146 				&message);
147 		}
148 	}
149 }
150 
151 /**
152  * This helper function wakes up all threads that are
153  * waiting for display->reader_cond (i. e. when reading is done,
154  * canceled, or an error occurred)
155  *
156  * NOTE: must be called with display->mutex locked
157  */
158 static void
display_wakeup_threads(struct wl_display * display)159 display_wakeup_threads(struct wl_display *display)
160 {
161 	/* Thread can get sleeping only in read_events(). If we're
162 	 * waking it up, it means that the read completed or was
163 	 * canceled, so we must increase the read_serial.
164 	 * This prevents from indefinite sleeping in read_events().
165 	 */
166 	++display->read_serial;
167 
168 	pthread_cond_broadcast(&display->reader_cond);
169 }
170 
171 /**
172  * This function is called for local errors (no memory, server hung up)
173  *
174  * \param display
175  * \param error    error value (EINVAL, EFAULT, ...)
176  *
177  * \note this function is called with display mutex locked
178  */
179 static void
display_fatal_error(struct wl_display * display,int error)180 display_fatal_error(struct wl_display *display, int error)
181 {
182 	if (display->last_error)
183 		return;
184 
185 	if (!error)
186 		error = EFAULT;
187 
188 	display->last_error = error;
189 
190 	display_wakeup_threads(display);
191 }
192 
193 /**
194  * This function is called for error events
195  * and indicates that in some object an error occurred.
196  * The difference between this function and display_fatal_error()
197  * is that this one handles errors that will come by wire,
198  * whereas display_fatal_error() is called for local errors.
199  *
200  * \param display
201  * \param code    error code
202  * \param id      id of the object that generated the error
203  * \param intf    protocol interface
204  */
205 static void
display_protocol_error(struct wl_display * display,uint32_t code,uint32_t id,const struct wl_interface * intf)206 display_protocol_error(struct wl_display *display, uint32_t code,
207 		       uint32_t id, const struct wl_interface *intf)
208 {
209 	int err;
210 
211 	if (display->last_error)
212 		return;
213 
214 	/* set correct errno */
215 	if (intf && wl_interface_equal(intf, &wl_display_interface)) {
216 		switch (code) {
217 		case WL_DISPLAY_ERROR_INVALID_OBJECT:
218 		case WL_DISPLAY_ERROR_INVALID_METHOD:
219 			err = EINVAL;
220 			break;
221 		case WL_DISPLAY_ERROR_NO_MEMORY:
222 			err = ENOMEM;
223 			break;
224 		case WL_DISPLAY_ERROR_IMPLEMENTATION:
225 			err = EPROTO;
226 			break;
227 		default:
228 			err = EFAULT;
229 		}
230 	} else {
231 		err = EPROTO;
232 	}
233 
234 	pthread_mutex_lock(&display->mutex);
235 
236 	display->last_error = err;
237 
238 	display->protocol_error.code = code;
239 	display->protocol_error.id = id;
240 	display->protocol_error.interface = intf;
241 
242 	/*
243 	 * here it is not necessary to wake up threads like in
244 	 * display_fatal_error, because this function is called from
245 	 * an event handler and that means that read_events() is done
246 	 * and woke up all threads. Since wl_display_prepare_read()
247 	 * fails when there are events in the queue, no threads
248 	 * can sleep in read_events() during dispatching
249 	 * (and therefore during calling this function), so this is safe.
250 	 */
251 
252 	pthread_mutex_unlock(&display->mutex);
253 }
254 
255 static void
wl_event_queue_init(struct wl_event_queue * queue,struct wl_display * display)256 wl_event_queue_init(struct wl_event_queue *queue, struct wl_display *display)
257 {
258 	wl_list_init(&queue->event_list);
259 	queue->display = display;
260 }
261 
262 static void
wl_proxy_unref(struct wl_proxy * proxy)263 wl_proxy_unref(struct wl_proxy *proxy)
264 {
265 	assert(proxy->refcount > 0);
266 	if (--proxy->refcount > 0)
267 		return;
268 
269 	/* If we get here, the client must have explicitly requested
270 	 * deletion. */
271 	assert(proxy->flags & WL_PROXY_FLAG_DESTROYED);
272 	free(proxy);
273 }
274 
275 static void
validate_closure_objects(struct wl_closure * closure)276 validate_closure_objects(struct wl_closure *closure)
277 {
278 	const char *signature;
279 	struct argument_details arg;
280 	int i, count;
281 	struct wl_proxy *proxy;
282 
283 	signature = closure->message->signature;
284 	count = arg_count_for_signature(signature);
285 	for (i = 0; i < count; i++) {
286 		signature = get_next_argument(signature, &arg);
287 		switch (arg.type) {
288 		case 'n':
289 		case 'o':
290 			proxy = (struct wl_proxy *) closure->args[i].o;
291 			if (proxy && proxy->flags & WL_PROXY_FLAG_DESTROYED)
292 				closure->args[i].o = NULL;
293 			break;
294 		default:
295 			break;
296 		}
297 	}
298 }
299 
300 /* Destroys a closure which was demarshaled for dispatch; unrefs all the
301  * proxies in its arguments, as well as its own proxy, and destroys the
302  * closure itself. */
303 static void
destroy_queued_closure(struct wl_closure * closure)304 destroy_queued_closure(struct wl_closure *closure)
305 {
306 	const char *signature;
307 	struct argument_details arg;
308 	struct wl_proxy *proxy;
309 	int i, count;
310 
311 	signature = closure->message->signature;
312 	count = arg_count_for_signature(signature);
313 	for (i = 0; i < count; i++) {
314 		signature = get_next_argument(signature, &arg);
315 		switch (arg.type) {
316 		case 'n':
317 		case 'o':
318 			proxy = (struct wl_proxy *) closure->args[i].o;
319 			if (proxy)
320 				wl_proxy_unref(proxy);
321 			break;
322 		default:
323 			break;
324 		}
325 	}
326 
327 	wl_proxy_unref(closure->proxy);
328 	wl_closure_destroy(closure);
329 }
330 
331 static void
wl_event_queue_release(struct wl_event_queue * queue)332 wl_event_queue_release(struct wl_event_queue *queue)
333 {
334 	struct wl_closure *closure;
335 
336 	while (!wl_list_empty(&queue->event_list)) {
337 		closure = wl_container_of(queue->event_list.next,
338 					  closure, link);
339 		wl_list_remove(&closure->link);
340 		destroy_queued_closure(closure);
341 	}
342 }
343 
344 /** Destroy an event queue
345  *
346  * \param queue The event queue to be destroyed
347  *
348  * Destroy the given event queue. Any pending event on that queue is
349  * discarded.
350  *
351  * The \ref wl_display object used to create the queue should not be
352  * destroyed until all event queues created with it are destroyed with
353  * this function.
354  *
355  * \memberof wl_event_queue
356  */
357 WL_EXPORT void
wl_event_queue_destroy(struct wl_event_queue * queue)358 wl_event_queue_destroy(struct wl_event_queue *queue)
359 {
360 	struct wl_display *display = queue->display;
361 
362 	pthread_mutex_lock(&display->mutex);
363 	wl_event_queue_release(queue);
364 	free(queue);
365 	pthread_mutex_unlock(&display->mutex);
366 }
367 
368 /** Create a new event queue for this display
369  *
370  * \param display The display context object
371  * \return A new event queue associated with this display or NULL on
372  * failure.
373  *
374  * \memberof wl_display
375  */
376 WL_EXPORT struct wl_event_queue *
wl_display_create_queue(struct wl_display * display)377 wl_display_create_queue(struct wl_display *display)
378 {
379 	struct wl_event_queue *queue;
380 
381 	queue = malloc(sizeof *queue);
382 	if (queue == NULL)
383 		return NULL;
384 
385 	wl_event_queue_init(queue, display);
386 
387 	return queue;
388 }
389 
390 static int
message_count_fds(const char * signature)391 message_count_fds(const char *signature)
392 {
393 	unsigned int count, i, fds = 0;
394 	struct argument_details arg;
395 
396 	count = arg_count_for_signature(signature);
397 	for (i = 0; i < count; i++) {
398 		signature = get_next_argument(signature, &arg);
399 		if (arg.type == 'h')
400 			fds++;
401 	}
402 
403 	return fds;
404 }
405 
406 static struct wl_zombie *
prepare_zombie(struct wl_proxy * proxy)407 prepare_zombie(struct wl_proxy *proxy)
408 {
409 	const struct wl_interface *interface = proxy->object.interface;
410 	const struct wl_message *message;
411 	int i, count;
412 	struct wl_zombie *zombie = NULL;
413 
414 	/* If we hit an event with an FD, ensure we have a zombie object and
415 	 * fill the fd_count slot for that event with the number of FDs for
416 	 * that event. Interfaces with no events containing FDs will not have
417 	 * zombie objects created. */
418 	for (i = 0; i < interface->event_count; i++) {
419 		message = &interface->events[i];
420 		count = message_count_fds(message->signature);
421 
422 		if (!count)
423 			continue;
424 
425 		if (!zombie) {
426 			zombie = zalloc(sizeof(*zombie) +
427 				        (interface->event_count * sizeof(int)));
428 			if (!zombie)
429 				return NULL;
430 
431 			zombie->event_count = interface->event_count;
432 			zombie->fd_count = (int *) &zombie[1];
433 		}
434 
435 		zombie->fd_count[i] = count;
436 	}
437 
438 	return zombie;
439 }
440 
441 static enum wl_iterator_result
free_zombies(void * element,void * data,uint32_t flags)442 free_zombies(void *element, void *data, uint32_t flags)
443 {
444 	if (flags & WL_MAP_ENTRY_ZOMBIE)
445 		free(element);
446 
447 	return WL_ITERATOR_CONTINUE;
448 }
449 
450 static struct wl_proxy *
proxy_create(struct wl_proxy * factory,const struct wl_interface * interface,uint32_t version)451 proxy_create(struct wl_proxy *factory, const struct wl_interface *interface,
452 	     uint32_t version)
453 {
454 	struct wl_proxy *proxy;
455 	struct wl_display *display = factory->display;
456 
457 	proxy = zalloc(sizeof *proxy);
458 	if (proxy == NULL)
459 		return NULL;
460 
461 	proxy->object.interface = interface;
462 	proxy->display = display;
463 	proxy->queue = factory->queue;
464 	proxy->refcount = 1;
465 	proxy->version = version;
466 
467 	proxy->object.id = wl_map_insert_new(&display->objects, 0, proxy);
468 
469 	return proxy;
470 }
471 
472 /** Create a proxy object with a given interface
473  *
474  * \param factory Factory proxy object
475  * \param interface Interface the proxy object should use
476  * \return A newly allocated proxy object or NULL on failure
477  *
478  * This function creates a new proxy object with the supplied interface. The
479  * proxy object will have an id assigned from the client id space. The id
480  * should be created on the compositor side by sending an appropriate request
481  * with \ref wl_proxy_marshal().
482  *
483  * The proxy will inherit the display and event queue of the factory object.
484  *
485  * \note This should not normally be used by non-generated code.
486  *
487  * \sa wl_display, wl_event_queue, wl_proxy_marshal()
488  *
489  * \memberof wl_proxy
490  */
491 WL_EXPORT struct wl_proxy *
wl_proxy_create(struct wl_proxy * factory,const struct wl_interface * interface)492 wl_proxy_create(struct wl_proxy *factory, const struct wl_interface *interface)
493 {
494 	struct wl_display *display = factory->display;
495 	struct wl_proxy *proxy;
496 
497 	pthread_mutex_lock(&display->mutex);
498 	proxy = proxy_create(factory, interface, factory->version);
499 	pthread_mutex_unlock(&display->mutex);
500 
501 	return proxy;
502 }
503 
504 /* The caller should hold the display lock */
505 static struct wl_proxy *
wl_proxy_create_for_id(struct wl_proxy * factory,uint32_t id,const struct wl_interface * interface)506 wl_proxy_create_for_id(struct wl_proxy *factory,
507 		       uint32_t id, const struct wl_interface *interface)
508 {
509 	struct wl_proxy *proxy;
510 	struct wl_display *display = factory->display;
511 
512 	proxy = zalloc(sizeof *proxy);
513 	if (proxy == NULL)
514 		return NULL;
515 
516 	proxy->object.interface = interface;
517 	proxy->object.id = id;
518 	proxy->display = display;
519 	proxy->queue = factory->queue;
520 	proxy->refcount = 1;
521 	proxy->version = factory->version;
522 
523 	wl_map_insert_at(&display->objects, 0, id, proxy);
524 
525 	return proxy;
526 }
527 
528 static void
proxy_destroy(struct wl_proxy * proxy)529 proxy_destroy(struct wl_proxy *proxy)
530 {
531 	if (proxy->flags & WL_PROXY_FLAG_ID_DELETED) {
532 		wl_map_remove(&proxy->display->objects, proxy->object.id);
533 	} else if (proxy->object.id < WL_SERVER_ID_START) {
534 		struct wl_zombie *zombie = prepare_zombie(proxy);
535 
536 		/* The map now contains the zombie entry, until the delete_id
537 		 * event arrives. */
538 		wl_map_insert_at(&proxy->display->objects,
539 				 WL_MAP_ENTRY_ZOMBIE,
540 				 proxy->object.id,
541 				 zombie);
542 	} else {
543 		wl_map_insert_at(&proxy->display->objects, 0,
544 				 proxy->object.id, NULL);
545 	}
546 
547 	proxy->flags |= WL_PROXY_FLAG_DESTROYED;
548 
549 	wl_proxy_unref(proxy);
550 }
551 
552 /** Destroy a proxy object
553  *
554  * \param proxy The proxy to be destroyed
555  *
556  * \c proxy must not be a proxy wrapper.
557  *
558  * \memberof wl_proxy
559  */
560 WL_EXPORT void
wl_proxy_destroy(struct wl_proxy * proxy)561 wl_proxy_destroy(struct wl_proxy *proxy)
562 {
563 	struct wl_display *display = proxy->display;
564 
565 	if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
566 		wl_abort("Tried to destroy wrapper with wl_proxy_destroy()\n");
567 
568 	pthread_mutex_lock(&display->mutex);
569 	proxy_destroy(proxy);
570 	pthread_mutex_unlock(&display->mutex);
571 }
572 
573 /** Set a proxy's listener
574  *
575  * \param proxy The proxy object
576  * \param implementation The listener to be added to proxy
577  * \param data User data to be associated with the proxy
578  * \return 0 on success or -1 on failure
579  *
580  * Set proxy's listener to \c implementation and its user data to
581  * \c data. If a listener has already been set, this function
582  * fails and nothing is changed.
583  *
584  * \c implementation is a vector of function pointers. For an opcode
585  * \c n, \c implementation[n] should point to the handler of \c n for
586  * the given object.
587  *
588  * \c proxy must not be a proxy wrapper.
589  *
590  * \memberof wl_proxy
591  */
592 WL_EXPORT int
wl_proxy_add_listener(struct wl_proxy * proxy,void (** implementation)(void),void * data)593 wl_proxy_add_listener(struct wl_proxy *proxy,
594 		      void (**implementation)(void), void *data)
595 {
596 	if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
597 		wl_abort("Proxy %p is a wrapper\n", proxy);
598 
599 	if (proxy->object.implementation || proxy->dispatcher) {
600 		wl_log("proxy %p already has listener\n", proxy);
601 		return -1;
602 	}
603 
604 	proxy->object.implementation = implementation;
605 	proxy->user_data = data;
606 
607 	return 0;
608 }
609 
610 /** Get a proxy's listener
611  *
612  * \param proxy The proxy object
613  * \return The address of the proxy's listener or NULL if no listener is set
614  *
615  * Gets the address to the proxy's listener; which is the listener set with
616  * \ref wl_proxy_add_listener.
617  *
618  * This function is useful in clients with multiple listeners on the same
619  * interface to allow the identification of which code to execute.
620  *
621  * \memberof wl_proxy
622  */
623 WL_EXPORT const void *
wl_proxy_get_listener(struct wl_proxy * proxy)624 wl_proxy_get_listener(struct wl_proxy *proxy)
625 {
626 	return proxy->object.implementation;
627 }
628 
629 /** Set a proxy's listener (with dispatcher)
630  *
631  * \param proxy The proxy object
632  * \param dispatcher The dispatcher to be used for this proxy
633  * \param implementation The dispatcher-specific listener implementation
634  * \param data User data to be associated with the proxy
635  * \return 0 on success or -1 on failure
636  *
637  * Set proxy's listener to use \c dispatcher_func as its dispatcher and \c
638  * dispatcher_data as its dispatcher-specific implementation and its user data
639  * to \c data. If a listener has already been set, this function
640  * fails and nothing is changed.
641  *
642  * The exact details of dispatcher_data depend on the dispatcher used.  This
643  * function is intended to be used by language bindings, not user code.
644  *
645  * \c proxy must not be a proxy wrapper.
646  *
647  * \memberof wl_proxy
648  */
649 WL_EXPORT int
wl_proxy_add_dispatcher(struct wl_proxy * proxy,wl_dispatcher_func_t dispatcher,const void * implementation,void * data)650 wl_proxy_add_dispatcher(struct wl_proxy *proxy,
651 			wl_dispatcher_func_t dispatcher,
652 			const void *implementation, void *data)
653 {
654 	if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
655 		wl_abort("Proxy %p is a wrapper\n", proxy);
656 
657 	if (proxy->object.implementation || proxy->dispatcher) {
658 		wl_log("proxy %p already has listener\n", proxy);
659 		return -1;
660 	}
661 
662 	proxy->object.implementation = implementation;
663 	proxy->dispatcher = dispatcher;
664 	proxy->user_data = data;
665 
666 	return 0;
667 }
668 
669 static struct wl_proxy *
create_outgoing_proxy(struct wl_proxy * proxy,const struct wl_message * message,union wl_argument * args,const struct wl_interface * interface,uint32_t version)670 create_outgoing_proxy(struct wl_proxy *proxy, const struct wl_message *message,
671 		      union wl_argument *args,
672 		      const struct wl_interface *interface, uint32_t version)
673 {
674 	int i, count;
675 	const char *signature;
676 	struct argument_details arg;
677 	struct wl_proxy *new_proxy = NULL;
678 
679 	signature = message->signature;
680 	count = arg_count_for_signature(signature);
681 	for (i = 0; i < count; i++) {
682 		signature = get_next_argument(signature, &arg);
683 
684 		switch (arg.type) {
685 		case 'n':
686 			new_proxy = proxy_create(proxy, interface, version);
687 			if (new_proxy == NULL)
688 				return NULL;
689 
690 			args[i].o = &new_proxy->object;
691 			break;
692 		}
693 	}
694 
695 	return new_proxy;
696 }
697 
698 /** Prepare a request to be sent to the compositor
699  *
700  * \param proxy The proxy object
701  * \param opcode Opcode of the request to be sent
702  * \param args Extra arguments for the given request
703  * \param interface The interface to use for the new proxy
704  *
705  * This function translates a request given an opcode, an interface and a
706  * wl_argument array to the wire format and writes it to the connection
707  * buffer.
708  *
709  * For new-id arguments, this function will allocate a new wl_proxy
710  * and send the ID to the server.  The new wl_proxy will be returned
711  * on success or NULL on error with errno set accordingly.  The newly
712  * created proxy will inherit their version from their parent.
713  *
714  * \note This is intended to be used by language bindings and not in
715  * non-generated code.
716  *
717  * \sa wl_proxy_marshal()
718  *
719  * \memberof wl_proxy
720  */
721 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)722 wl_proxy_marshal_array_constructor(struct wl_proxy *proxy,
723 				   uint32_t opcode, union wl_argument *args,
724 				   const struct wl_interface *interface)
725 {
726 	return wl_proxy_marshal_array_constructor_versioned(proxy, opcode,
727 							    args, interface,
728 							    proxy->version);
729 }
730 
731 
732 /** Prepare a request to be sent to the compositor
733  *
734  * \param proxy The proxy object
735  * \param opcode Opcode of the request to be sent
736  * \param args Extra arguments for the given request
737  * \param interface The interface to use for the new proxy
738  * \param version The protocol object version for the new proxy
739  *
740  * Translates the request given by opcode and the extra arguments into the
741  * wire format and write it to the connection buffer.  This version takes an
742  * array of the union type wl_argument.
743  *
744  * For new-id arguments, this function will allocate a new wl_proxy
745  * and send the ID to the server.  The new wl_proxy will be returned
746  * on success or NULL on error with errno set accordingly.  The newly
747  * created proxy will have the version specified.
748  *
749  * \note This is intended to be used by language bindings and not in
750  * non-generated code.
751  *
752  * \sa wl_proxy_marshal()
753  *
754  * \memberof wl_proxy
755  */
756 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)757 wl_proxy_marshal_array_constructor_versioned(struct wl_proxy *proxy,
758 					     uint32_t opcode,
759 					     union wl_argument *args,
760 					     const struct wl_interface *interface,
761 					     uint32_t version)
762 {
763 	struct wl_closure *closure;
764 	struct wl_proxy *new_proxy = NULL;
765 	const struct wl_message *message;
766 
767 	pthread_mutex_lock(&proxy->display->mutex);
768 
769 	message = &proxy->object.interface->methods[opcode];
770 	if (interface) {
771 		new_proxy = create_outgoing_proxy(proxy, message,
772 						  args, interface,
773 						  version);
774 		if (new_proxy == NULL)
775 			goto err_unlock;
776 	}
777 
778 	if (proxy->display->last_error) {
779 		goto err_unlock;
780 	}
781 
782 	closure = wl_closure_marshal(&proxy->object, opcode, args, message);
783 	if (closure == NULL) {
784 		wl_log("Error marshalling request: %s\n", strerror(errno));
785 		display_fatal_error(proxy->display, errno);
786 		goto err_unlock;
787 	}
788 
789 	log_closure(closure, proxy, true);
790 
791 	if (wl_closure_send(closure, proxy->display->connection)) {
792 		wl_log("Error sending request: %s\n", strerror(errno));
793 		display_fatal_error(proxy->display, errno);
794 	}
795 
796 	wl_closure_destroy(closure);
797 
798  err_unlock:
799 	pthread_mutex_unlock(&proxy->display->mutex);
800 
801 	return new_proxy;
802 }
803 
804 
805 /** Prepare a request to be sent to the compositor
806  *
807  * \param proxy The proxy object
808  * \param opcode Opcode of the request to be sent
809  * \param ... Extra arguments for the given request
810  *
811  * This function is similar to wl_proxy_marshal_constructor(), except
812  * it doesn't create proxies for new-id arguments.
813  *
814  * \note This should not normally be used by non-generated code.
815  *
816  * \sa wl_proxy_create()
817  *
818  * \memberof wl_proxy
819  */
820 WL_EXPORT void
wl_proxy_marshal(struct wl_proxy * proxy,uint32_t opcode,...)821 wl_proxy_marshal(struct wl_proxy *proxy, uint32_t opcode, ...)
822 {
823 	union wl_argument args[WL_CLOSURE_MAX_ARGS];
824 	va_list ap;
825 
826 	va_start(ap, opcode);
827 	wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
828 				 args, WL_CLOSURE_MAX_ARGS, ap);
829 	va_end(ap);
830 
831 	wl_proxy_marshal_array_constructor(proxy, opcode, args, NULL);
832 }
833 
834 /** Prepare a request to be sent to the compositor
835  *
836  * \param proxy The proxy object
837  * \param opcode Opcode of the request to be sent
838  * \param interface The interface to use for the new proxy
839  * \param ... Extra arguments for the given request
840  * \return A new wl_proxy for the new_id argument or NULL on error
841  *
842  * This function translates a request given an opcode, an interface and extra
843  * arguments to the wire format and writes it to the connection buffer. The
844  * types of the extra arguments must correspond to the argument types of the
845  * method associated with the opcode in the interface.
846  *
847  * For new-id arguments, this function will allocate a new wl_proxy
848  * and send the ID to the server.  The new wl_proxy will be returned
849  * on success or NULL on error with errno set accordingly.  The newly
850  * created proxy will inherit their version from their parent.
851  *
852  * \note This should not normally be used by non-generated code.
853  *
854  * \memberof wl_proxy
855  */
856 WL_EXPORT struct wl_proxy *
wl_proxy_marshal_constructor(struct wl_proxy * proxy,uint32_t opcode,const struct wl_interface * interface,...)857 wl_proxy_marshal_constructor(struct wl_proxy *proxy, uint32_t opcode,
858 			     const struct wl_interface *interface, ...)
859 {
860 	union wl_argument args[WL_CLOSURE_MAX_ARGS];
861 	va_list ap;
862 
863 	va_start(ap, interface);
864 	wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
865 				 args, WL_CLOSURE_MAX_ARGS, ap);
866 	va_end(ap);
867 
868 	return wl_proxy_marshal_array_constructor(proxy, opcode,
869 						  args, interface);
870 }
871 
872 
873 /** Prepare a request to be sent to the compositor
874  *
875  * \param proxy The proxy object
876  * \param opcode Opcode of the request to be sent
877  * \param interface The interface to use for the new proxy
878  * \param version The protocol object version of the new proxy
879  * \param ... Extra arguments for the given request
880  * \return A new wl_proxy for the new_id argument or NULL on error
881  *
882  * Translates the request given by opcode and the extra arguments into the
883  * wire format and write it to the connection buffer.
884  *
885  * For new-id arguments, this function will allocate a new wl_proxy
886  * and send the ID to the server.  The new wl_proxy will be returned
887  * on success or NULL on error with errno set accordingly.  The newly
888  * created proxy will have the version specified.
889  *
890  * \note This should not normally be used by non-generated code.
891  *
892  * \memberof wl_proxy
893  */
894 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,...)895 wl_proxy_marshal_constructor_versioned(struct wl_proxy *proxy, uint32_t opcode,
896 				       const struct wl_interface *interface,
897 				       uint32_t version, ...)
898 {
899 	union wl_argument args[WL_CLOSURE_MAX_ARGS];
900 	va_list ap;
901 
902 	va_start(ap, version);
903 	wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
904 				 args, WL_CLOSURE_MAX_ARGS, ap);
905 	va_end(ap);
906 
907 	return wl_proxy_marshal_array_constructor_versioned(proxy, opcode,
908 							    args, interface,
909 							    version);
910 }
911 
912 /** Prepare a request to be sent to the compositor
913  *
914  * \param proxy The proxy object
915  * \param opcode Opcode of the request to be sent
916  * \param args Extra arguments for the given request
917  *
918  * This function is similar to wl_proxy_marshal_array_constructor(), except
919  * it doesn't create proxies for new-id arguments.
920  *
921  * \note This is intended to be used by language bindings and not in
922  * non-generated code.
923  *
924  * \sa wl_proxy_marshal()
925  *
926  * \memberof wl_proxy
927  */
928 WL_EXPORT void
wl_proxy_marshal_array(struct wl_proxy * proxy,uint32_t opcode,union wl_argument * args)929 wl_proxy_marshal_array(struct wl_proxy *proxy, uint32_t opcode,
930 		       union wl_argument *args)
931 {
932 	wl_proxy_marshal_array_constructor(proxy, opcode, args, NULL);
933 }
934 
935 static void
display_handle_error(void * data,struct wl_display * display,void * object,uint32_t code,const char * message)936 display_handle_error(void *data,
937 		     struct wl_display *display, void *object,
938 		     uint32_t code, const char *message)
939 {
940 	struct wl_proxy *proxy = object;
941 	uint32_t object_id;
942 	const struct wl_interface *interface;
943 
944 	if (proxy) {
945 		wl_log("%s@%u: error %d: %s\n",
946 		       proxy->object.interface->name,
947 		       proxy->object.id,
948 		       code, message);
949 
950 		object_id = proxy->object.id;
951 		interface = proxy->object.interface;
952 	} else {
953 		wl_log("[destroyed object]: error %d: %s\n",
954 		       code, message);
955 
956 		object_id = 0;
957 		interface = NULL;
958 	}
959 
960 	display_protocol_error(display, code, object_id, interface);
961 }
962 
963 static void
display_handle_delete_id(void * data,struct wl_display * display,uint32_t id)964 display_handle_delete_id(void *data, struct wl_display *display, uint32_t id)
965 {
966 	struct wl_proxy *proxy;
967 
968 	pthread_mutex_lock(&display->mutex);
969 
970 	proxy = wl_map_lookup(&display->objects, id);
971 
972 	if (wl_object_is_zombie(&display->objects, id)) {
973 		/* For zombie objects, the 'proxy' is actually the zombie
974 		 * event-information structure, which we can free. */
975 		free(proxy);
976 		wl_map_remove(&display->objects, id);
977 	} else if (proxy) {
978 		proxy->flags |= WL_PROXY_FLAG_ID_DELETED;
979 	} else {
980 		wl_log("error: received delete_id for unknown id (%u)\n", id);
981 	}
982 
983 	pthread_mutex_unlock(&display->mutex);
984 }
985 
986 static const struct wl_display_listener display_listener = {
987 	display_handle_error,
988 	display_handle_delete_id
989 };
990 
991 static int
connect_to_socket(const char * name)992 connect_to_socket(const char *name)
993 {
994 	struct sockaddr_un addr;
995 	socklen_t size;
996 	const char *runtime_dir;
997 	int name_size, fd;
998 	bool path_is_absolute;
999 
1000 	if (name == NULL)
1001 		name = getenv("WAYLAND_DISPLAY");
1002 	if (name == NULL)
1003 		name = "wayland-0";
1004 
1005 	path_is_absolute = name[0] == '/';
1006 
1007 	runtime_dir = getenv("XDG_RUNTIME_DIR");
1008 	if (!runtime_dir && !path_is_absolute) {
1009 		wl_log("error: XDG_RUNTIME_DIR not set in the environment.\n");
1010 		/* to prevent programs reporting
1011 		 * "failed to create display: Success" */
1012 		errno = ENOENT;
1013 		return -1;
1014 	}
1015 
1016 	fd = wl_os_socket_cloexec(PF_LOCAL, SOCK_STREAM, 0);
1017 	if (fd < 0)
1018 		return -1;
1019 
1020 	memset(&addr, 0, sizeof addr);
1021 	addr.sun_family = AF_LOCAL;
1022 	if (!path_is_absolute) {
1023 		name_size =
1024 			snprintf(addr.sun_path, sizeof addr.sun_path,
1025 			         "%s/%s", runtime_dir, name) + 1;
1026 	} else {
1027 		/* absolute path */
1028 		name_size =
1029 			snprintf(addr.sun_path, sizeof addr.sun_path,
1030 			         "%s", name) + 1;
1031 	}
1032 
1033 	assert(name_size > 0);
1034 	if (name_size > (int)sizeof addr.sun_path) {
1035 		if (!path_is_absolute) {
1036 			wl_log("error: socket path \"%s/%s\" plus null terminator"
1037 			       " exceeds %i bytes\n", runtime_dir, name, (int) sizeof(addr.sun_path));
1038 		} else {
1039 			wl_log("error: socket path \"%s\" plus null terminator"
1040 			       " exceeds %i bytes\n", name, (int) sizeof(addr.sun_path));
1041 		}
1042 		close(fd);
1043 		/* to prevent programs reporting
1044 		 * "failed to add socket: Success" */
1045 		errno = ENAMETOOLONG;
1046 		return -1;
1047 	};
1048 
1049 	size = offsetof (struct sockaddr_un, sun_path) + name_size;
1050 
1051 	if (connect(fd, (struct sockaddr *) &addr, size) < 0) {
1052 		close(fd);
1053 		return -1;
1054 	}
1055 
1056 	return fd;
1057 }
1058 
1059 /** Connect to Wayland display on an already open fd
1060  *
1061  * \param fd The fd to use for the connection
1062  * \return A \ref wl_display object or \c NULL on failure
1063  *
1064  * The wl_display takes ownership of the fd and will close it when the
1065  * display is destroyed.  The fd will also be closed in case of
1066  * failure.
1067  *
1068  * \memberof wl_display
1069  */
1070 WL_EXPORT struct wl_display *
wl_display_connect_to_fd(int fd)1071 wl_display_connect_to_fd(int fd)
1072 {
1073 	struct wl_display *display;
1074 	const char *debug;
1075 
1076 	debug = getenv("WAYLAND_DEBUG");
1077 	if (debug && (strstr(debug, "client") || strstr(debug, "1")))
1078 		debug_client = 1;
1079 
1080 	display = zalloc(sizeof *display);
1081 	if (display == NULL) {
1082 		close(fd);
1083 		return NULL;
1084 	}
1085 
1086 	display->fd = fd;
1087 	wl_map_init(&display->objects, WL_MAP_CLIENT_SIDE);
1088 	wl_event_queue_init(&display->default_queue, display);
1089 	wl_event_queue_init(&display->display_queue, display);
1090 	pthread_mutex_init(&display->mutex, NULL);
1091 	pthread_cond_init(&display->reader_cond, NULL);
1092 	display->reader_count = 0;
1093 	wl_list_init(&display->protocol_loggers);
1094 
1095 	wl_map_insert_new(&display->objects, 0, NULL);
1096 
1097 	display->proxy.object.interface = &wl_display_interface;
1098 	display->proxy.object.id =
1099 		wl_map_insert_new(&display->objects, 0, display);
1100 	display->proxy.display = display;
1101 	display->proxy.object.implementation = (void(**)(void)) &display_listener;
1102 	display->proxy.user_data = display;
1103 	display->proxy.queue = &display->default_queue;
1104 	display->proxy.flags = 0;
1105 	display->proxy.refcount = 1;
1106 
1107 	/* We set this version to 0 for backwards compatibility.
1108 	 *
1109 	 * If a client is using old versions of protocol headers,
1110 	 * it will use unversioned API to create proxies.  Those
1111 	 * proxies will inherit this 0.
1112 	 *
1113 	 * A client could be passing these proxies into library
1114 	 * code newer than the headers that checks proxy
1115 	 * versions.  When the proxy version is reported as 0
1116 	 * the library will know that it can't reliably determine
1117 	 * the proxy version, and should do whatever fallback is
1118 	 * required.
1119 	 *
1120 	 * This trick forces wl_display to always report 0, but
1121 	 * since it's a special object that we can't bind
1122 	 * specific versions of anyway, this should be fine.
1123 	 */
1124 	display->proxy.version = 0;
1125 
1126 	display->connection = wl_connection_create(display->fd);
1127 	if (display->connection == NULL)
1128 		goto err_connection;
1129 
1130 	return display;
1131 
1132  err_connection:
1133 	pthread_mutex_destroy(&display->mutex);
1134 	pthread_cond_destroy(&display->reader_cond);
1135 	wl_map_release(&display->objects);
1136 	close(display->fd);
1137 	free(display);
1138 
1139 	return NULL;
1140 }
1141 
1142 /** Connect to a Wayland display
1143  *
1144  * \param name Name of the Wayland display to connect to
1145  * \return A \ref wl_display object or \c NULL on failure
1146  *
1147  * Connect to the Wayland display named \c name. If \c name is \c NULL,
1148  * its value will be replaced with the WAYLAND_DISPLAY environment
1149  * variable if it is set, otherwise display "wayland-0" will be used.
1150  *
1151  * If WAYLAND_SOCKET is set, it's interpreted as a file descriptor number
1152  * referring to an already opened socket. In this case, the socket is used
1153  * as-is and \c name is ignored.
1154  *
1155  * If \c name is a relative path, then the socket is opened relative to
1156  * the XDG_RUNTIME_DIR directory.
1157  *
1158  * If \c name is an absolute path, then that path is used as-is for
1159  * the location of the socket at which the Wayland server is listening;
1160  * no qualification inside XDG_RUNTIME_DIR is attempted.
1161  *
1162  * If \c name is \c NULL and the WAYLAND_DISPLAY environment variable
1163  * is set to an absolute pathname, then that pathname is used as-is
1164  * for the socket in the same manner as if \c name held an absolute
1165  * path. Support for absolute paths in \c name and WAYLAND_DISPLAY
1166  * is present since Wayland version 1.15.
1167  *
1168  * \memberof wl_display
1169  */
1170 WL_EXPORT struct wl_display *
wl_display_connect(const char * name)1171 wl_display_connect(const char *name)
1172 {
1173 	char *connection, *end;
1174 	int flags, fd;
1175 
1176 	connection = getenv("WAYLAND_SOCKET");
1177 	if (connection) {
1178 		int prev_errno = errno;
1179 		errno = 0;
1180 		fd = strtol(connection, &end, 10);
1181 		if (errno != 0 || connection == end || *end != '\0')
1182 			return NULL;
1183 		errno = prev_errno;
1184 
1185 		flags = fcntl(fd, F_GETFD);
1186 		if (flags != -1)
1187 			fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
1188 		unsetenv("WAYLAND_SOCKET");
1189 	} else {
1190 		fd = connect_to_socket(name);
1191 		if (fd < 0)
1192 			return NULL;
1193 	}
1194 
1195 	return wl_display_connect_to_fd(fd);
1196 }
1197 
1198 /** Close a connection to a Wayland display
1199  *
1200  * \param display The display context object
1201  *
1202  * Close the connection to \c display and free all resources associated
1203  * with it.
1204  *
1205  * \memberof wl_display
1206  */
1207 WL_EXPORT void
wl_display_disconnect(struct wl_display * display)1208 wl_display_disconnect(struct wl_display *display)
1209 {
1210 	wl_connection_destroy(display->connection);
1211 	wl_map_for_each(&display->objects, free_zombies, NULL);
1212 	wl_map_release(&display->objects);
1213 	wl_event_queue_release(&display->default_queue);
1214 	wl_event_queue_release(&display->display_queue);
1215 	wl_list_remove(&display->protocol_loggers);
1216 	pthread_mutex_destroy(&display->mutex);
1217 	pthread_cond_destroy(&display->reader_cond);
1218 	close(display->fd);
1219 
1220 	free(display);
1221 }
1222 
1223 /** Get a display context's file descriptor
1224  *
1225  * \param display The display context object
1226  * \return Display object file descriptor
1227  *
1228  * Return the file descriptor associated with a display so it can be
1229  * integrated into the client's main loop.
1230  *
1231  * \memberof wl_display
1232  */
1233 WL_EXPORT int
wl_display_get_fd(struct wl_display * display)1234 wl_display_get_fd(struct wl_display *display)
1235 {
1236 	return display->fd;
1237 }
1238 
1239 static void
sync_callback(void * data,struct wl_callback * callback,uint32_t serial)1240 sync_callback(void *data, struct wl_callback *callback, uint32_t serial)
1241 {
1242 	int *done = data;
1243 
1244 	*done = 1;
1245 	wl_callback_destroy(callback);
1246 }
1247 
1248 static const struct wl_callback_listener sync_listener = {
1249 	sync_callback
1250 };
1251 
1252 /** Block until all pending request are processed by the server
1253  *
1254  * \param display The display context object
1255  * \param queue The queue on which to run the roundtrip
1256  * \return The number of dispatched events on success or -1 on failure
1257  *
1258  * This function blocks until the server has processed all currently issued
1259  * requests by sending a request to the display server and waiting for a
1260  * reply before returning.
1261  *
1262  * This function uses wl_display_dispatch_queue() internally. It is not allowed
1263  * to call this function while the thread is being prepared for reading events,
1264  * and doing so will cause a dead lock.
1265  *
1266  * \note This function may dispatch other events being received on the given
1267  * queue.
1268  *
1269  * \sa wl_display_roundtrip()
1270  * \memberof wl_display
1271  */
1272 WL_EXPORT int
wl_display_roundtrip_queue(struct wl_display * display,struct wl_event_queue * queue)1273 wl_display_roundtrip_queue(struct wl_display *display, struct wl_event_queue *queue)
1274 {
1275 	struct wl_display *display_wrapper;
1276 	struct wl_callback *callback;
1277 	int done, ret = 0;
1278 
1279 	done = 0;
1280 
1281 	display_wrapper = wl_proxy_create_wrapper(display);
1282 	if (!display_wrapper)
1283 		return -1;
1284 
1285 	wl_proxy_set_queue((struct wl_proxy *) display_wrapper, queue);
1286 	callback = wl_display_sync(display_wrapper);
1287 	wl_proxy_wrapper_destroy(display_wrapper);
1288 
1289 	if (callback == NULL)
1290 		return -1;
1291 
1292 	wl_callback_add_listener(callback, &sync_listener, &done);
1293 	while (!done && ret >= 0)
1294 		ret = wl_display_dispatch_queue(display, queue);
1295 
1296 	if (ret == -1 && !done)
1297 		wl_callback_destroy(callback);
1298 
1299 	return ret;
1300 }
1301 
1302 /** Block until all pending request are processed by the server
1303  *
1304  * \param display The display context object
1305  * \return The number of dispatched events on success or -1 on failure
1306  *
1307  * This function blocks until the server has processed all currently issued
1308  * requests by sending a request to the display server and waiting for a reply
1309  * before returning.
1310  *
1311  * This function uses wl_display_dispatch_queue() internally. It is not allowed
1312  * to call this function while the thread is being prepared for reading events,
1313  * and doing so will cause a dead lock.
1314  *
1315  * \note This function may dispatch other events being received on the default
1316  * queue.
1317  *
1318  * \memberof wl_display
1319  */
1320 WL_EXPORT int
wl_display_roundtrip(struct wl_display * display)1321 wl_display_roundtrip(struct wl_display *display)
1322 {
1323 	return wl_display_roundtrip_queue(display, &display->default_queue);
1324 }
1325 
1326 static int
create_proxies(struct wl_proxy * sender,struct wl_closure * closure)1327 create_proxies(struct wl_proxy *sender, struct wl_closure *closure)
1328 {
1329 	struct wl_proxy *proxy;
1330 	const char *signature;
1331 	struct argument_details arg;
1332 	uint32_t id;
1333 	int i;
1334 	int count;
1335 
1336 	signature = closure->message->signature;
1337 	count = arg_count_for_signature(signature);
1338 	for (i = 0; i < count; i++) {
1339 		signature = get_next_argument(signature, &arg);
1340 		switch (arg.type) {
1341 		case 'n':
1342 			id = closure->args[i].n;
1343 			if (id == 0) {
1344 				closure->args[i].o = NULL;
1345 				break;
1346 			}
1347 			proxy = wl_proxy_create_for_id(sender, id,
1348 						       closure->message->types[i]);
1349 			if (proxy == NULL)
1350 				return -1;
1351 			closure->args[i].o = (struct wl_object *)proxy;
1352 			break;
1353 		default:
1354 			break;
1355 		}
1356 	}
1357 
1358 	return 0;
1359 }
1360 
1361 static void
increase_closure_args_refcount(struct wl_closure * closure)1362 increase_closure_args_refcount(struct wl_closure *closure)
1363 {
1364 	const char *signature;
1365 	struct argument_details arg;
1366 	int i, count;
1367 	struct wl_proxy *proxy;
1368 
1369 	signature = closure->message->signature;
1370 	count = arg_count_for_signature(signature);
1371 	for (i = 0; i < count; i++) {
1372 		signature = get_next_argument(signature, &arg);
1373 		switch (arg.type) {
1374 		case 'n':
1375 		case 'o':
1376 			proxy = (struct wl_proxy *) closure->args[i].o;
1377 			if (proxy)
1378 				proxy->refcount++;
1379 			break;
1380 		default:
1381 			break;
1382 		}
1383 	}
1384 
1385 	closure->proxy->refcount++;
1386 }
1387 
1388 static int
queue_event(struct wl_display * display,int len)1389 queue_event(struct wl_display *display, int len)
1390 {
1391 	uint32_t p[2], id;
1392 	int opcode, size;
1393 	struct wl_proxy *proxy;
1394 	struct wl_closure *closure;
1395 	const struct wl_message *message;
1396 	struct wl_event_queue *queue;
1397 
1398 	wl_connection_copy(display->connection, p, sizeof p);
1399 	id = p[0];
1400 	opcode = p[1] & 0xffff;
1401 	size = p[1] >> 16;
1402 	if (len < size)
1403 		return 0;
1404 
1405 	/* If our proxy is gone or a zombie, just eat the event (and any FDs,
1406 	 * if applicable). */
1407 	proxy = wl_map_lookup(&display->objects, id);
1408 	if (!proxy || wl_object_is_zombie(&display->objects, id)) {
1409 		struct wl_zombie *zombie = wl_map_lookup(&display->objects, id);
1410 
1411 		if (zombie && zombie->fd_count[opcode])
1412 			wl_connection_close_fds_in(display->connection,
1413 						   zombie->fd_count[opcode]);
1414 
1415 		wl_connection_consume(display->connection, size);
1416 		return size;
1417 	}
1418 
1419 	if (opcode >= proxy->object.interface->event_count) {
1420 		wl_log("interface '%s' has no event %u\n",
1421 		       proxy->object.interface->name, opcode);
1422 		return -1;
1423 	}
1424 
1425 	message = &proxy->object.interface->events[opcode];
1426 	closure = wl_connection_demarshal(display->connection, size,
1427 					  &display->objects, message);
1428 	if (!closure)
1429 		return -1;
1430 
1431 	if (create_proxies(proxy, closure) < 0) {
1432 		wl_closure_destroy(closure);
1433 		return -1;
1434 	}
1435 
1436 	if (wl_closure_lookup_objects(closure, &display->objects) != 0) {
1437 		wl_closure_destroy(closure);
1438 		return -1;
1439 	}
1440 
1441 	closure->proxy = proxy;
1442 	increase_closure_args_refcount(closure);
1443 
1444 	if (proxy == &display->proxy)
1445 		queue = &display->display_queue;
1446 	else
1447 		queue = proxy->queue;
1448 
1449 	wl_list_insert(queue->event_list.prev, &closure->link);
1450 
1451 	return size;
1452 }
1453 
1454 static void
dispatch_event(struct wl_display * display,struct wl_event_queue * queue)1455 dispatch_event(struct wl_display *display, struct wl_event_queue *queue)
1456 {
1457 	struct wl_closure *closure;
1458 	struct wl_proxy *proxy;
1459 	int opcode;
1460 	bool proxy_destroyed;
1461 
1462 	closure = wl_container_of(queue->event_list.next, closure, link);
1463 	wl_list_remove(&closure->link);
1464 	opcode = closure->opcode;
1465 
1466 	/* Verify that the receiving object is still valid by checking if has
1467 	 * been destroyed by the application. */
1468 	validate_closure_objects(closure);
1469 	proxy = closure->proxy;
1470 	proxy_destroyed = !!(proxy->flags & WL_PROXY_FLAG_DESTROYED);
1471 	if (proxy_destroyed) {
1472 		destroy_queued_closure(closure);
1473 		return;
1474 	}
1475 
1476 	pthread_mutex_unlock(&display->mutex);
1477 
1478 	log_closure(closure, proxy, false);
1479 
1480 	if (proxy->dispatcher) {
1481 		wl_closure_dispatch(closure, proxy->dispatcher,
1482 				    &proxy->object, opcode);
1483 	} else if (proxy->object.implementation) {
1484 		wl_closure_invoke(closure, WL_CLOSURE_INVOKE_CLIENT,
1485 				  &proxy->object, opcode, proxy->user_data);
1486 	}
1487 
1488 	pthread_mutex_lock(&display->mutex);
1489 
1490 	destroy_queued_closure(closure);
1491 }
1492 
1493 static int
read_events(struct wl_display * display)1494 read_events(struct wl_display *display)
1495 {
1496 	int total, rem, size;
1497 	uint32_t serial;
1498 
1499 	display->reader_count--;
1500 	if (display->reader_count == 0) {
1501 		total = wl_connection_read(display->connection);
1502 		if (total == -1) {
1503 			if (errno == EAGAIN) {
1504 				/* we must wake up threads whenever
1505 				 * the reader_count dropped to 0 */
1506 				display_wakeup_threads(display);
1507 
1508 				return 0;
1509 			}
1510 
1511 			display_fatal_error(display, errno);
1512 			return -1;
1513 		} else if (total == 0) {
1514 			/* The compositor has closed the socket. This
1515 			 * should be considered an error so we'll fake
1516 			 * an errno */
1517 			errno = EPIPE;
1518 			display_fatal_error(display, errno);
1519 			return -1;
1520 		}
1521 
1522 		for (rem = total; rem >= 8; rem -= size) {
1523 			size = queue_event(display, rem);
1524 			if (size == -1) {
1525 				display_fatal_error(display, errno);
1526 				return -1;
1527 			} else if (size == 0) {
1528 				break;
1529 			}
1530 		}
1531 
1532 		display_wakeup_threads(display);
1533 	} else {
1534 		serial = display->read_serial;
1535 		while (display->read_serial == serial)
1536 			pthread_cond_wait(&display->reader_cond,
1537 					  &display->mutex);
1538 
1539 		if (display->last_error) {
1540 			errno = display->last_error;
1541 			return -1;
1542 		}
1543 	}
1544 
1545 	return 0;
1546 }
1547 
1548 static void
cancel_read(struct wl_display * display)1549 cancel_read(struct wl_display *display)
1550 {
1551 	display->reader_count--;
1552 	if (display->reader_count == 0)
1553 		display_wakeup_threads(display);
1554 }
1555 
1556 /** Read events from display file descriptor
1557  *
1558  * \param display The display context object
1559  * \return 0 on success or -1 on error.  In case of error errno will
1560  * be set accordingly
1561  *
1562  * Calling this function will result in data available on the display file
1563  * descriptor being read and read events will be queued on their corresponding
1564  * event queues.
1565  *
1566  * Before calling this function, depending on what thread it is to be called
1567  * from, wl_display_prepare_read_queue() or wl_display_prepare_read() needs to
1568  * be called. See wl_display_prepare_read_queue() for more details.
1569  *
1570  * When being called at a point where other threads have been prepared to read
1571  * (using wl_display_prepare_read_queue() or wl_display_prepare_read()) this
1572  * function will sleep until all other prepared threads have either been
1573  * cancelled (using wl_display_cancel_read()) or them self entered this
1574  * function. The last thread that calls this function will then read and queue
1575  * events on their corresponding event queues, and finally wake up all other
1576  * wl_display_read_events() calls causing them to return.
1577  *
1578  * If a thread cancels a read preparation when all other threads that have
1579  * prepared to read has either called wl_display_cancel_read() or
1580  * wl_display_read_events(), all reader threads will return without having read
1581  * any data.
1582  *
1583  * To dispatch events that may have been queued, call
1584  * wl_display_dispatch_pending() or wl_display_dispatch_queue_pending().
1585  *
1586  * \sa wl_display_prepare_read(), wl_display_cancel_read(),
1587  * wl_display_dispatch_pending(), wl_display_dispatch()
1588  *
1589  * \memberof wl_display
1590  */
1591 WL_EXPORT int
wl_display_read_events(struct wl_display * display)1592 wl_display_read_events(struct wl_display *display)
1593 {
1594 	int ret;
1595 
1596 	pthread_mutex_lock(&display->mutex);
1597 
1598 	if (display->last_error) {
1599 		cancel_read(display);
1600 		pthread_mutex_unlock(&display->mutex);
1601 
1602 		errno = display->last_error;
1603 		return -1;
1604 	}
1605 
1606 	ret = read_events(display);
1607 
1608 	pthread_mutex_unlock(&display->mutex);
1609 
1610 	return ret;
1611 }
1612 
1613 static int
dispatch_queue(struct wl_display * display,struct wl_event_queue * queue)1614 dispatch_queue(struct wl_display *display, struct wl_event_queue *queue)
1615 {
1616 	int count;
1617 
1618 	if (display->last_error)
1619 		goto err;
1620 
1621 	count = 0;
1622 	while (!wl_list_empty(&display->display_queue.event_list)) {
1623 		dispatch_event(display, &display->display_queue);
1624 		if (display->last_error)
1625 			goto err;
1626 		count++;
1627 	}
1628 
1629 	while (!wl_list_empty(&queue->event_list)) {
1630 		dispatch_event(display, queue);
1631 		if (display->last_error)
1632 			goto err;
1633 		count++;
1634 	}
1635 
1636 	return count;
1637 
1638 err:
1639 	errno = display->last_error;
1640 
1641 	return -1;
1642 }
1643 
1644 /** Prepare to read events from the display's file descriptor to a queue
1645  *
1646  * \param display The display context object
1647  * \param queue The event queue to use
1648  * \return 0 on success or -1 if event queue was not empty
1649  *
1650  * This function (or wl_display_prepare_read()) must be called before reading
1651  * from the file descriptor using wl_display_read_events(). Calling
1652  * wl_display_prepare_read_queue() announces the calling thread's intention to
1653  * read and ensures that until the thread is ready to read and calls
1654  * wl_display_read_events(), no other thread will read from the file descriptor.
1655  * This only succeeds if the event queue is empty, and if not -1 is returned and
1656  * errno set to EAGAIN.
1657  *
1658  * If a thread successfully calls wl_display_prepare_read_queue(), it must
1659  * either call wl_display_read_events() when it's ready or cancel the read
1660  * intention by calling wl_display_cancel_read().
1661  *
1662  * Use this function before polling on the display fd or integrate the fd into a
1663  * toolkit event loop in a race-free way. A correct usage would be (with most
1664  * error checking left out):
1665  *
1666  * \code
1667  * while (wl_display_prepare_read_queue(display, queue) != 0)
1668  *         wl_display_dispatch_queue_pending(display, queue);
1669  * wl_display_flush(display);
1670  *
1671  * ret = poll(fds, nfds, -1);
1672  * if (has_error(ret))
1673  *         wl_display_cancel_read(display);
1674  * else
1675  *         wl_display_read_events(display);
1676  *
1677  * wl_display_dispatch_queue_pending(display, queue);
1678  * \endcode
1679  *
1680  * Here we call wl_display_prepare_read_queue(), which ensures that between
1681  * returning from that call and eventually calling wl_display_read_events(), no
1682  * other thread will read from the fd and queue events in our queue. If the call
1683  * to wl_display_prepare_read_queue() fails, we dispatch the pending events and
1684  * try again until we're successful.
1685  *
1686  * The wl_display_prepare_read_queue() function doesn't acquire exclusive access
1687  * to the display's fd. It only registers that the thread calling this function
1688  * has intention to read from fd. When all registered readers call
1689  * wl_display_read_events(), only one (at random) eventually reads and queues
1690  * the events and the others are sleeping meanwhile. This way we avoid races and
1691  * still can read from more threads.
1692  *
1693  * \sa wl_display_cancel_read(), wl_display_read_events(),
1694  * wl_display_prepare_read()
1695  *
1696  * \memberof wl_display
1697  */
1698 WL_EXPORT int
wl_display_prepare_read_queue(struct wl_display * display,struct wl_event_queue * queue)1699 wl_display_prepare_read_queue(struct wl_display *display,
1700 			      struct wl_event_queue *queue)
1701 {
1702 	int ret;
1703 
1704 	pthread_mutex_lock(&display->mutex);
1705 
1706 	if (!wl_list_empty(&queue->event_list)) {
1707 		errno = EAGAIN;
1708 		ret = -1;
1709 	} else {
1710 		display->reader_count++;
1711 		ret = 0;
1712 	}
1713 
1714 	pthread_mutex_unlock(&display->mutex);
1715 
1716 	return ret;
1717 }
1718 
1719 /** Prepare to read events from the display's file descriptor
1720  *
1721  * \param display The display context object
1722  * \return 0 on success or -1 if event queue was not empty
1723  *
1724  * This function does the same thing as wl_display_prepare_read_queue()
1725  * with the default queue passed as the queue.
1726  *
1727  * \sa wl_display_prepare_read_queue
1728  * \memberof wl_display
1729  */
1730 WL_EXPORT int
wl_display_prepare_read(struct wl_display * display)1731 wl_display_prepare_read(struct wl_display *display)
1732 {
1733 	return wl_display_prepare_read_queue(display, &display->default_queue);
1734 }
1735 
1736 /** Cancel read intention on display's fd
1737  *
1738  * \param display The display context object
1739  *
1740  * After a thread successfully called wl_display_prepare_read() it must
1741  * either call wl_display_read_events() or wl_display_cancel_read().
1742  * If the threads do not follow this rule it will lead to deadlock.
1743  *
1744  * \sa wl_display_prepare_read(), wl_display_read_events()
1745  *
1746  * \memberof wl_display
1747  */
1748 WL_EXPORT void
wl_display_cancel_read(struct wl_display * display)1749 wl_display_cancel_read(struct wl_display *display)
1750 {
1751 	pthread_mutex_lock(&display->mutex);
1752 
1753 	cancel_read(display);
1754 
1755 	pthread_mutex_unlock(&display->mutex);
1756 }
1757 
1758 static int
wl_display_poll(struct wl_display * display,short int events)1759 wl_display_poll(struct wl_display *display, short int events)
1760 {
1761 	int ret;
1762 	struct pollfd pfd[1];
1763 
1764 	pfd[0].fd = display->fd;
1765 	pfd[0].events = events;
1766 	do {
1767 		ret = poll(pfd, 1, -1);
1768 	} while (ret == -1 && errno == EINTR);
1769 
1770 	return ret;
1771 }
1772 
1773 /** Dispatch events in an event queue
1774  *
1775  * \param display The display context object
1776  * \param queue The event queue to dispatch
1777  * \return The number of dispatched events on success or -1 on failure
1778  *
1779  * Dispatch events on the given event queue.
1780  *
1781  * If the given event queue is empty, this function blocks until there are
1782  * events to be read from the display fd. Events are read and queued on
1783  * the appropriate event queues. Finally, events on given event queue are
1784  * dispatched. On failure -1 is returned and errno set appropriately.
1785  *
1786  * In a multi threaded environment, do not manually wait using poll() (or
1787  * equivalent) before calling this function, as doing so might cause a dead
1788  * lock. If external reliance on poll() (or equivalent) is required, see
1789  * wl_display_prepare_read_queue() of how to do so.
1790  *
1791  * This function is thread safe as long as it dispatches the right queue on the
1792  * right thread. It is also compatible with the multi thread event reading
1793  * preparation API (see wl_display_prepare_read_queue()), and uses the
1794  * equivalent functionality internally. It is not allowed to call this function
1795  * while the thread is being prepared for reading events, and doing so will
1796  * cause a dead lock.
1797  *
1798  * It can be used as a helper function to ease the procedure of reading and
1799  * dispatching events.
1800  *
1801  * \note Since Wayland 1.5 the display has an extra queue
1802  * for its own events (i. e. delete_id). This queue is dispatched always,
1803  * no matter what queue we passed as an argument to this function.
1804  * That means that this function can return non-0 value even when it
1805  * haven't dispatched any event for the given queue.
1806  *
1807  * \sa wl_display_dispatch(), wl_display_dispatch_pending(),
1808  * wl_display_dispatch_queue_pending(), wl_display_prepare_read_queue()
1809  *
1810  * \memberof wl_display
1811  */
1812 WL_EXPORT int
wl_display_dispatch_queue(struct wl_display * display,struct wl_event_queue * queue)1813 wl_display_dispatch_queue(struct wl_display *display,
1814 			  struct wl_event_queue *queue)
1815 {
1816 	int ret;
1817 
1818 	if (wl_display_prepare_read_queue(display, queue) == -1)
1819 		return wl_display_dispatch_queue_pending(display, queue);
1820 
1821 	while (true) {
1822 		ret = wl_display_flush(display);
1823 
1824 		if (ret != -1 || errno != EAGAIN)
1825 			break;
1826 
1827 		if (wl_display_poll(display, POLLOUT) == -1) {
1828 			wl_display_cancel_read(display);
1829 			return -1;
1830 		}
1831 	}
1832 
1833 	/* Don't stop if flushing hits an EPIPE; continue so we can read any
1834 	 * protocol error that may have triggered it. */
1835 	if (ret < 0 && errno != EPIPE) {
1836 		wl_display_cancel_read(display);
1837 		return -1;
1838 	}
1839 
1840 	if (wl_display_poll(display, POLLIN) == -1) {
1841 		wl_display_cancel_read(display);
1842 		return -1;
1843 	}
1844 
1845 	if (wl_display_read_events(display) == -1)
1846 		return -1;
1847 
1848 	return wl_display_dispatch_queue_pending(display, queue);
1849 }
1850 
1851 /** Dispatch pending events in an event queue
1852  *
1853  * \param display The display context object
1854  * \param queue The event queue to dispatch
1855  * \return The number of dispatched events on success or -1 on failure
1856  *
1857  * Dispatch all incoming events for objects assigned to the given
1858  * event queue. On failure -1 is returned and errno set appropriately.
1859  * If there are no events queued, this function returns immediately.
1860  *
1861  * \memberof wl_display
1862  * \since 1.0.2
1863  */
1864 WL_EXPORT int
wl_display_dispatch_queue_pending(struct wl_display * display,struct wl_event_queue * queue)1865 wl_display_dispatch_queue_pending(struct wl_display *display,
1866 				  struct wl_event_queue *queue)
1867 {
1868 	int ret;
1869 
1870 	pthread_mutex_lock(&display->mutex);
1871 
1872 	ret = dispatch_queue(display, queue);
1873 
1874 	pthread_mutex_unlock(&display->mutex);
1875 
1876 	return ret;
1877 }
1878 
1879 /** Process incoming events
1880  *
1881  * \param display The display context object
1882  * \return The number of dispatched events on success or -1 on failure
1883  *
1884  * Dispatch events on the default event queue.
1885  *
1886  * If the default event queue is empty, this function blocks until there are
1887  * events to be read from the display fd. Events are read and queued on
1888  * the appropriate event queues. Finally, events on the default event queue
1889  * are dispatched. On failure -1 is returned and errno set appropriately.
1890  *
1891  * In a multi threaded environment, do not manually wait using poll() (or
1892  * equivalent) before calling this function, as doing so might cause a dead
1893  * lock. If external reliance on poll() (or equivalent) is required, see
1894  * wl_display_prepare_read_queue() of how to do so.
1895  *
1896  * This function is thread safe as long as it dispatches the right queue on the
1897  * right thread. It is also compatible with the multi thread event reading
1898  * preparation API (see wl_display_prepare_read_queue()), and uses the
1899  * equivalent functionality internally. It is not allowed to call this function
1900  * while the thread is being prepared for reading events, and doing so will
1901  * cause a dead lock.
1902  *
1903  * \note It is not possible to check if there are events on the queue
1904  * or not. For dispatching default queue events without blocking, see \ref
1905  * wl_display_dispatch_pending().
1906  *
1907  * \sa wl_display_dispatch_pending(), wl_display_dispatch_queue(),
1908  * wl_display_read_events()
1909  *
1910  * \memberof wl_display
1911  */
1912 WL_EXPORT int
wl_display_dispatch(struct wl_display * display)1913 wl_display_dispatch(struct wl_display *display)
1914 {
1915 	return wl_display_dispatch_queue(display, &display->default_queue);
1916 }
1917 
1918 /** Dispatch default queue events without reading from the display fd
1919  *
1920  * \param display The display context object
1921  * \return The number of dispatched events or -1 on failure
1922  *
1923  * This function dispatches events on the main event queue. It does not
1924  * attempt to read the display fd and simply returns zero if the main
1925  * queue is empty, i.e., it doesn't block.
1926  *
1927  * \sa wl_display_dispatch(), wl_display_dispatch_queue(),
1928  * wl_display_flush()
1929  *
1930  * \memberof wl_display
1931  */
1932 WL_EXPORT int
wl_display_dispatch_pending(struct wl_display * display)1933 wl_display_dispatch_pending(struct wl_display *display)
1934 {
1935 	return wl_display_dispatch_queue_pending(display,
1936 						 &display->default_queue);
1937 }
1938 
1939 /** Retrieve the last error that occurred on a display
1940  *
1941  * \param display The display context object
1942  * \return The last error that occurred on \c display or 0 if no error occurred
1943  *
1944  * Return the last error that occurred on the display. This may be an error sent
1945  * by the server or caused by the local client.
1946  *
1947  * \note Errors are \b fatal. If this function returns non-zero the display
1948  * can no longer be used.
1949  *
1950  * \memberof wl_display
1951  */
1952 WL_EXPORT int
wl_display_get_error(struct wl_display * display)1953 wl_display_get_error(struct wl_display *display)
1954 {
1955 	int ret;
1956 
1957 	pthread_mutex_lock(&display->mutex);
1958 
1959 	ret = display->last_error;
1960 
1961 	pthread_mutex_unlock(&display->mutex);
1962 
1963 	return ret;
1964 }
1965 
1966 /** Retrieves the information about a protocol error:
1967  *
1968  * \param display    The Wayland display
1969  * \param interface  if not NULL, stores the interface where the error occurred,
1970  *                   or NULL, if unknown.
1971  * \param id         if not NULL, stores the object id that generated
1972  *                   the error, or 0, if the object id is unknown. There's no
1973  *                   guarantee the object is still valid; the client must know
1974  *                   if it deleted the object.
1975  * \return           The error code as defined in the interface specification.
1976  *
1977  * \code
1978  * int err = wl_display_get_error(display);
1979  *
1980  * if (err == EPROTO) {
1981  *        code = wl_display_get_protocol_error(display, &interface, &id);
1982  *        handle_error(code, interface, id);
1983  * }
1984  *
1985  * ...
1986  * \endcode
1987  * \memberof wl_display
1988  */
1989 WL_EXPORT uint32_t
wl_display_get_protocol_error(struct wl_display * display,const struct wl_interface ** interface,uint32_t * id)1990 wl_display_get_protocol_error(struct wl_display *display,
1991 			      const struct wl_interface **interface,
1992 			      uint32_t *id)
1993 {
1994 	uint32_t ret;
1995 
1996 	pthread_mutex_lock(&display->mutex);
1997 
1998 	ret = display->protocol_error.code;
1999 
2000 	if (interface)
2001 		*interface = display->protocol_error.interface;
2002 	if (id)
2003 		*id = display->protocol_error.id;
2004 
2005 	pthread_mutex_unlock(&display->mutex);
2006 
2007 	return ret;
2008 }
2009 
2010 
2011 /** Send all buffered requests on the display to the server
2012  *
2013  * \param display The display context object
2014  * \return The number of bytes sent on success or -1 on failure
2015  *
2016  * Send all buffered data on the client side to the server. Clients should
2017  * always call this function before blocking on input from the display fd.
2018  * On success, the number of bytes sent to the server is returned. On
2019  * failure, this function returns -1 and errno is set appropriately.
2020  *
2021  * wl_display_flush() never blocks.  It will write as much data as
2022  * possible, but if all data could not be written, errno will be set
2023  * to EAGAIN and -1 returned.  In that case, use poll on the display
2024  * file descriptor to wait for it to become writable again.
2025  *
2026  * \memberof wl_display
2027  */
2028 WL_EXPORT int
wl_display_flush(struct wl_display * display)2029 wl_display_flush(struct wl_display *display)
2030 {
2031 	int ret;
2032 
2033 	pthread_mutex_lock(&display->mutex);
2034 
2035 	if (display->last_error) {
2036 		errno = display->last_error;
2037 		ret = -1;
2038 	} else {
2039 		/* We don't make EPIPE a fatal error here, so that we may try to
2040 		 * read events after the failed flush. When the compositor sends
2041 		 * an error it will close the socket, and if we make EPIPE fatal
2042 		 * here we don't get a chance to process the error. */
2043 		ret = wl_connection_flush(display->connection);
2044 		if (ret < 0 && errno != EAGAIN && errno != EPIPE)
2045 			display_fatal_error(display, errno);
2046 	}
2047 
2048 	pthread_mutex_unlock(&display->mutex);
2049 
2050 	return ret;
2051 }
2052 
2053 /** Set the user data associated with a proxy
2054  *
2055  * \param proxy The proxy object
2056  * \param user_data The data to be associated with proxy
2057  *
2058  * Set the user data associated with \c proxy. When events for this
2059  * proxy are received, \c user_data will be supplied to its listener.
2060  *
2061  * \memberof wl_proxy
2062  */
2063 WL_EXPORT void
wl_proxy_set_user_data(struct wl_proxy * proxy,void * user_data)2064 wl_proxy_set_user_data(struct wl_proxy *proxy, void *user_data)
2065 {
2066 	proxy->user_data = user_data;
2067 }
2068 
2069 /** Get the user data associated with a proxy
2070  *
2071  * \param proxy The proxy object
2072  * \return The user data associated with proxy
2073  *
2074  * \memberof wl_proxy
2075  */
2076 WL_EXPORT void *
wl_proxy_get_user_data(struct wl_proxy * proxy)2077 wl_proxy_get_user_data(struct wl_proxy *proxy)
2078 {
2079 	return proxy->user_data;
2080 }
2081 
2082 /** Get the protocol object version of a proxy object
2083  *
2084  * \param proxy The proxy object
2085  * \return The protocol object version of the proxy or 0
2086  *
2087  * Gets the protocol object version of a proxy object, or 0
2088  * if the proxy was created with unversioned API.
2089  *
2090  * A returned value of 0 means that no version information is
2091  * available, so the caller must make safe assumptions about
2092  * the object's real version.
2093  *
2094  * wl_display's version will always return 0.
2095  *
2096  * \memberof wl_proxy
2097  */
2098 WL_EXPORT uint32_t
wl_proxy_get_version(struct wl_proxy * proxy)2099 wl_proxy_get_version(struct wl_proxy *proxy)
2100 {
2101 	return proxy->version;
2102 }
2103 
2104 /** Get the id of a proxy object
2105  *
2106  * \param proxy The proxy object
2107  * \return The id the object associated with the proxy
2108  *
2109  * \memberof wl_proxy
2110  */
2111 WL_EXPORT uint32_t
wl_proxy_get_id(struct wl_proxy * proxy)2112 wl_proxy_get_id(struct wl_proxy *proxy)
2113 {
2114 	return proxy->object.id;
2115 }
2116 
2117 /** Set the tag of a proxy object
2118  *
2119  * A toolkit or application can set a unique tag on a proxy in order to
2120  * identify whether an object is managed by itself or some external part.
2121  *
2122  * To create a tag, the recommended way is to define a statically allocated
2123  * constant char array containing some descriptive string. The tag will be the
2124  * pointer to the non-const pointer to the beginning of the array.
2125  *
2126  * For example, to define and set a tag on a surface managed by a certain
2127  * subsystem:
2128  *
2129  * 	static const char *my_tag = "my tag";
2130  *
2131  * 	wl_proxy_set_tag((struct wl_proxy *) surface, &my_tag);
2132  *
2133  * Then, in a callback with wl_surface as an argument, in order to check
2134  * whether it's a surface managed by the same subsystem.
2135  *
2136  * 	const char * const *tag;
2137  *
2138  * 	tag = wl_proxy_get_tag((struct wl_proxy *) surface);
2139  * 	if (tag != &my_tag)
2140  *		return;
2141  *
2142  *	...
2143  *
2144  * For debugging purposes, a tag should be suitable to be included in a debug
2145  * log entry, e.g.
2146  *
2147  * 	const char * const *tag;
2148  *
2149  * 	tag = wl_proxy_get_tag((struct wl_proxy *) surface);
2150  * 	printf("Got a surface with the tag %p (%s)\n",
2151  * 	       tag, (tag && *tag) ? *tag : "");
2152  *
2153  * \param proxy The proxy object
2154  * \param tag The tag
2155  *
2156  * \memberof wl_proxy
2157  * \since 1.17.90
2158  */
2159 WL_EXPORT void
wl_proxy_set_tag(struct wl_proxy * proxy,const char * const * tag)2160 wl_proxy_set_tag(struct wl_proxy *proxy,
2161 		 const char * const *tag)
2162 {
2163 	proxy->tag = tag;
2164 }
2165 
2166 /** Get the tag of a proxy object
2167  *
2168  * See wl_proxy_set_tag for details.
2169  *
2170  * \param proxy The proxy object
2171  *
2172  * \memberof wl_proxy
2173  * \since 1.17.90
2174  */
2175 WL_EXPORT const char * const *
wl_proxy_get_tag(struct wl_proxy * proxy)2176 wl_proxy_get_tag(struct wl_proxy *proxy)
2177 {
2178 	return proxy->tag;
2179 }
2180 
2181 /** Get the interface name (class) of a proxy object
2182  *
2183  * \param proxy The proxy object
2184  * \return The interface name of the object associated with the proxy
2185  *
2186  * \memberof wl_proxy
2187  */
2188 WL_EXPORT const char *
wl_proxy_get_class(struct wl_proxy * proxy)2189 wl_proxy_get_class(struct wl_proxy *proxy)
2190 {
2191 	return proxy->object.interface->name;
2192 }
2193 
2194 /** Assign a proxy to an event queue
2195  *
2196  * \param proxy The proxy object
2197  * \param queue The event queue that will handle this proxy or NULL
2198  *
2199  * Assign proxy to event queue. Events coming from \c proxy will be
2200  * queued in \c queue from now. If queue is NULL, then the display's
2201  * default queue is set to the proxy.
2202  *
2203  * \note By default, the queue set in proxy is the one inherited from parent.
2204  *
2205  * \sa wl_display_dispatch_queue()
2206  *
2207  * \memberof wl_proxy
2208  */
2209 WL_EXPORT void
wl_proxy_set_queue(struct wl_proxy * proxy,struct wl_event_queue * queue)2210 wl_proxy_set_queue(struct wl_proxy *proxy, struct wl_event_queue *queue)
2211 {
2212 	if (queue)
2213 		proxy->queue = queue;
2214 	else
2215 		proxy->queue = &proxy->display->default_queue;
2216 }
2217 
2218 /** Create a proxy wrapper for making queue assignments thread-safe
2219  *
2220  * \param proxy The proxy object to be wrapped
2221  * \return A proxy wrapper for the given proxy or NULL on failure
2222  *
2223  * A proxy wrapper is type of 'struct wl_proxy' instance that can be used when
2224  * sending requests instead of using the original proxy. A proxy wrapper does
2225  * not have an implementation or dispatcher, and events received on the
2226  * object is still emitted on the original proxy. Trying to set an
2227  * implementation or dispatcher will have no effect but result in a warning
2228  * being logged.
2229  *
2230  * Setting the proxy queue of the proxy wrapper will make new objects created
2231  * using the proxy wrapper use the set proxy queue.
2232  * Even though there is no implementation nor dispatcher, the proxy queue can
2233  * be changed. This will affect the default queue of new objects created by
2234  * requests sent via the proxy wrapper.
2235  *
2236  * A proxy wrapper can only be destroyed using wl_proxy_wrapper_destroy().
2237  *
2238  * A proxy wrapper must be destroyed before the proxy it was created from.
2239  *
2240  * If a user reads and dispatches events on more than one thread, it is
2241  * necessary to use a proxy wrapper when sending requests on objects when the
2242  * intention is that a newly created proxy is to use a proxy queue different
2243  * from the proxy the request was sent on, as creating the new proxy and then
2244  * setting the queue is not thread safe.
2245  *
2246  * For example, a module that runs using its own proxy queue that needs to
2247  * do display roundtrip must wrap the wl_display proxy object before sending
2248  * the wl_display.sync request. For example:
2249  *
2250  * \code
2251  *
2252  *   struct wl_event_queue *queue = ...;
2253  *   struct wl_display *wrapped_display;
2254  *   struct wl_callback *callback;
2255  *
2256  *   wrapped_display = wl_proxy_create_wrapper(display);
2257  *   wl_proxy_set_queue((struct wl_proxy *) wrapped_display, queue);
2258  *   callback = wl_display_sync(wrapped_display);
2259  *   wl_proxy_wrapper_destroy(wrapped_display);
2260  *   wl_callback_add_listener(callback, ...);
2261  *
2262  * \endcode
2263  *
2264  * \memberof wl_proxy
2265  */
2266 WL_EXPORT void *
wl_proxy_create_wrapper(void * proxy)2267 wl_proxy_create_wrapper(void *proxy)
2268 {
2269 	struct wl_proxy *wrapped_proxy = proxy;
2270 	struct wl_proxy *wrapper;
2271 
2272 	wrapper = zalloc(sizeof *wrapper);
2273 	if (!wrapper)
2274 		return NULL;
2275 
2276 	pthread_mutex_lock(&wrapped_proxy->display->mutex);
2277 
2278 	wrapper->object.interface = wrapped_proxy->object.interface;
2279 	wrapper->object.id = wrapped_proxy->object.id;
2280 	wrapper->version = wrapped_proxy->version;
2281 	wrapper->display = wrapped_proxy->display;
2282 	wrapper->queue = wrapped_proxy->queue;
2283 	wrapper->flags = WL_PROXY_FLAG_WRAPPER;
2284 	wrapper->refcount = 1;
2285 
2286 	pthread_mutex_unlock(&wrapped_proxy->display->mutex);
2287 
2288 	return wrapper;
2289 }
2290 
2291 /** Destroy a proxy wrapper
2292  * \param proxy_wrapper The proxy wrapper to be destroyed
2293  *
2294  * \memberof wl_proxy
2295  */
2296 WL_EXPORT void
wl_proxy_wrapper_destroy(void * proxy_wrapper)2297 wl_proxy_wrapper_destroy(void *proxy_wrapper)
2298 {
2299 	struct wl_proxy *wrapper = proxy_wrapper;
2300 
2301 	if (!(wrapper->flags & WL_PROXY_FLAG_WRAPPER))
2302 		wl_abort("Tried to destroy non-wrapper proxy with "
2303 			 "wl_proxy_wrapper_destroy\n");
2304 
2305 	assert(wrapper->refcount == 1);
2306 
2307 	free(wrapper);
2308 }
2309 
2310 /** Safely converts an object into its corresponding proxy
2311  *
2312  * \param object The object to convert
2313  * \return A corresponding proxy, or NULL on failure
2314  *
2315  * Safely converts an object into its corresponding proxy.
2316  *
2317  * This is useful for implementing functions that are given a \c wl_argument
2318  * array, and that need to do further introspection on the ".o" field, as it
2319  * is otherwise an opaque type.
2320  *
2321  * \memberof wl_proxy
2322  */
2323 WL_EXPORT struct wl_proxy *
wl_proxy_from_object(struct wl_object * object)2324 wl_proxy_from_object(struct wl_object *object)
2325 {
2326 	struct wl_proxy *proxy;
2327 	if (object == NULL)
2328 		return NULL;
2329 	return wl_container_of(object, proxy, object);
2330 }
2331 
2332 WL_EXPORT void
wl_log_set_handler_client(wl_log_func_t handler)2333 wl_log_set_handler_client(wl_log_func_t handler)
2334 {
2335 	wl_log_handler = handler;
2336 }
2337 
2338 /** Adds a new protocol client logger.
2339  *
2340  * When a new protocol message arrives or is sent from the client
2341  * all the protocol logger functions will be called, carrying the
2342  * \a user_data pointer, the type of the message (request or
2343  * event) and the actual message.
2344  * The lifetime of the messages passed to the logger function ends
2345  * when they return so the messages cannot be stored and accessed
2346  * later.
2347  *
2348  * \a errno is set on error.
2349  *
2350  * \param display The display object
2351  * \param func The function to call to log a new protocol message
2352  * \param user_data The user data pointer to pass to \a func
2353  *
2354  * \return The protocol logger object on success, NULL on failure.
2355  *
2356  * \sa wl_protocol_logger_client_destroy
2357  *
2358  * \memberof wl_display
2359  */
2360 WL_EXPORT struct wl_protocol_logger_client *
wl_display_add_protocol_logger_client(struct wl_display * display,wl_protocol_logger_client_func_t func,void * user_data)2361 wl_display_add_protocol_logger_client(struct wl_display *display,
2362 				      wl_protocol_logger_client_func_t func,
2363 				      void *user_data)
2364 {
2365 	struct wl_protocol_logger_client *logger;
2366 
2367 	logger = malloc(sizeof *logger);
2368 	if (!logger)
2369 		return NULL;
2370 
2371 	logger->func = func;
2372 	logger->user_data = user_data;
2373 	wl_list_insert(&display->protocol_loggers, &logger->link);
2374 
2375 	return logger;
2376 }
2377 
2378 /** Destroys a protocol client logger.
2379  *
2380  * This function destroys a protocol client logger and removes it from the
2381  * display it was added to with \a wl_display_add_protocol_logger_client.
2382  * The \a logger object becomes invalid after calling this function.
2383  *
2384  * \sa wl_display_add_protocol_logger_client
2385  *
2386  * \memberof wl_protocol_logger_client
2387  */
2388 WL_EXPORT void
wl_protocol_logger_client_destroy(struct wl_protocol_logger_client * logger)2389 wl_protocol_logger_client_destroy(struct wl_protocol_logger_client *logger)
2390 {
2391 	wl_list_remove(&logger->link);
2392 	free(logger);
2393 }
2394