777c482dac62da3d1ec7fa0d7f1e959bacd017e4
[platform/upstream/wayland.git] / src / wayland-client.c
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 "../config.h"
30
31 #include <stdlib.h>
32 #include <stdint.h>
33 #include <stddef.h>
34 #include <stdio.h>
35 #include <stdbool.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <sys/socket.h>
40 #include <sys/un.h>
41 #include <ctype.h>
42 #include <assert.h>
43 #include <fcntl.h>
44 #include <poll.h>
45 #include <pthread.h>
46 #include <sys/time.h>
47 #include <limits.h>
48
49 #include "wayland-util.h"
50 #include "wayland-os.h"
51 #include "wayland-client.h"
52 #include "wayland-private.h"
53
54 //#define WL_DEBUG_QUEUE
55
56 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
57 #define WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT 10
58 // END
59
60 /** \cond */
61
62 enum wl_proxy_flag {
63         WL_PROXY_FLAG_ID_DELETED = (1 << 0),
64         WL_PROXY_FLAG_DESTROYED = (1 << 1),
65         WL_PROXY_FLAG_WRAPPER = (1 << 2),
66         WL_PROXY_FLAG_ID_OVERRIDEN = (1 << 31)
67 };
68
69 struct wl_zombie {
70         int event_count;
71         int *fd_count;
72 };
73
74 struct wl_proxy {
75         struct wl_object object;
76         struct wl_display *display;
77         struct wl_event_queue *queue;
78         uint32_t flags;
79         int refcount;
80         void *user_data;
81         wl_dispatcher_func_t dispatcher;
82         uint32_t version;
83         const char * const *tag;
84         struct wl_list queue_link; /**< in struct wl_event_queue::proxy_list */
85 };
86
87 struct wl_event_queue {
88         struct wl_list event_list;
89         struct wl_list proxy_list; /**< struct wl_proxy::queue_link */
90         struct wl_display *display;
91 };
92
93 struct wl_display {
94         struct wl_proxy proxy;
95         struct wl_connection *connection;
96
97         /* errno of the last wl_display error */
98         int last_error;
99
100         /* When display gets an error event from some object, it stores
101          * information about it here, so that client can get this
102          * information afterwards */
103         struct {
104                 /* Code of the error. It can be compared to
105                  * the interface's errors enumeration. */
106                 uint32_t code;
107                 /* interface (protocol) in which the error occurred */
108                 const struct wl_interface *interface;
109                 /* id of the proxy that caused the error. There's no warranty
110                  * that the proxy is still valid. It's up to client how it will
111                  * use it */
112                 uint32_t id;
113                 char message[512];
114         } protocol_error;
115         int fd;
116         struct wl_map objects;
117         struct wl_event_queue display_queue;
118         struct wl_event_queue default_queue;
119         pthread_mutex_t mutex;
120
121         int reader_count;
122         uint32_t read_serial;
123         pthread_cond_t reader_cond;
124 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
125         uint32_t force_sync_count;
126 // END
127         /* last errno value */
128         int prev_errno;
129         char *name;
130 };
131
132 /** \endcond */
133
134 /**
135  * This helper function wakes up all threads that are
136  * waiting for display->reader_cond (i. e. when reading is done,
137  * canceled, or an error occurred)
138  *
139  * NOTE: must be called with display->mutex locked
140  */
141 static void
142 display_wakeup_threads(struct wl_display *display)
143 {
144         /* Thread can get sleeping only in read_events(). If we're
145          * waking it up, it means that the read completed or was
146          * canceled, so we must increase the read_serial.
147          * This prevents from indefinite sleeping in read_events().
148          */
149         ++display->read_serial;
150
151         pthread_cond_broadcast(&display->reader_cond);
152 }
153
154 /**
155  * This function is called for local errors (no memory, server hung up)
156  *
157  * \param display
158  * \param error    error value (EINVAL, EFAULT, ...)
159  *
160  * \note this function is called with display mutex locked
161  */
162 static void
163 display_fatal_error(struct wl_display *display, int error)
164 {
165         if (display->last_error)
166                 return;
167
168         if (!error)
169                 error = EFAULT;
170
171         wl_log("[WL_LAST_ERROR_SET][FUNC:%s][LINE:%d] display:%p last_error (%d -> %d)\n", __FUNCTION__, __LINE__, display, display->last_error, error);
172         display->last_error = error;
173
174         wl_log("got fatal error: %d (display %p, last_error=%d)\n", error, display, display->last_error);
175
176         display_wakeup_threads(display);
177 }
178
179 static void
180 display_print_protocol_error_information(struct wl_display *display, int error)
181 {
182         if (error == EINVAL || error == ENOMEM || error == EFAULT || error == EPROTO)
183                 wl_log("error(%d) %s, display:%p, last_error:%d", error, display->protocol_error.message,
184                                 display, display->last_error);
185 }
186
187 /**
188  * This function is called for error events
189  * and indicates that in some object an error occurred.
190  * The difference between this function and display_fatal_error()
191  * is that this one handles errors that will come by wire,
192  * whereas display_fatal_error() is called for local errors.
193  *
194  * \param display
195  * \param code    error code
196  * \param id      id of the object that generated the error
197  * \param intf    protocol interface
198  */
199 static void
200 display_protocol_error(struct wl_display *display, uint32_t code,
201                        uint32_t id, const struct wl_interface *intf)
202 {
203         int err;
204
205         if (display->last_error)
206                 return;
207
208         /* set correct errno */
209         if (intf && wl_interface_equal(intf, &wl_display_interface)) {
210                 switch (code) {
211                 case WL_DISPLAY_ERROR_INVALID_OBJECT:
212                 case WL_DISPLAY_ERROR_INVALID_METHOD:
213                         err = EINVAL;
214                         break;
215                 case WL_DISPLAY_ERROR_NO_MEMORY:
216                         err = ENOMEM;
217                         break;
218                 case WL_DISPLAY_ERROR_IMPLEMENTATION:
219                         err = EPROTO;
220                         break;
221                 default:
222                         err = EFAULT;
223                 }
224         } else {
225                 err = EPROTO;
226         }
227
228         pthread_mutex_lock(&display->mutex);
229
230         wl_log("[WL_LAST_ERROR_SET][FUNC:%s][LINE:%d] display:%p last_error (%d -> %d)\n", __FUNCTION__, __LINE__, display, display->last_error, err);
231         display->last_error = err;
232
233         display->protocol_error.code = code;
234         display->protocol_error.id = id;
235         display->protocol_error.interface = intf;
236
237         wl_log("[WL_PROTOCOL_ERROR] display:%p last_error:%d, errno:%d\n", display, display->last_error, errno);
238         wl_log("... protocol_error.code : %d\n", display->protocol_error.code);
239         wl_log("... protocol_error.id : %d\n", display->protocol_error.id);
240         wl_log("... protocol_error.interface->name : %s\n", intf ? intf->name : NULL);
241         wl_log("... protocol_error.interface->version : %d\n", intf ? intf->version : -1);
242         wl_log("... protocol_error.message : %s\n", display->protocol_error.message);
243
244         /*
245          * here it is not necessary to wake up threads like in
246          * display_fatal_error, because this function is called from
247          * an event handler and that means that read_events() is done
248          * and woke up all threads. Since wl_display_prepare_read()
249          * fails when there are events in the queue, no threads
250          * can sleep in read_events() during dispatching
251          * (and therefore during calling this function), so this is safe.
252          */
253
254         pthread_mutex_unlock(&display->mutex);
255 }
256
257 static void
258 wl_event_queue_init(struct wl_event_queue *queue, struct wl_display *display)
259 {
260         wl_list_init(&queue->event_list);
261         wl_list_init(&queue->proxy_list);
262         queue->display = display;
263 }
264
265 static void
266 wl_proxy_unref(struct wl_proxy *proxy)
267 {
268         assert(proxy->refcount > 0);
269         if (--proxy->refcount > 0)
270                 return;
271
272         /* If we get here, the client must have explicitly requested
273          * deletion. */
274         assert(proxy->flags & WL_PROXY_FLAG_DESTROYED);
275         free(proxy);
276 }
277
278 static void
279 validate_closure_objects(struct wl_closure *closure)
280 {
281         const char *signature;
282         struct argument_details arg;
283         int i, count;
284         struct wl_proxy *proxy;
285
286         signature = closure->message->signature;
287         count = arg_count_for_signature(signature);
288         for (i = 0; i < count; i++) {
289                 signature = get_next_argument(signature, &arg);
290                 switch (arg.type) {
291                 case 'n':
292                 case 'o':
293                         proxy = (struct wl_proxy *) closure->args[i].o;
294                         if (proxy && proxy->flags & WL_PROXY_FLAG_DESTROYED)
295                                 closure->args[i].o = NULL;
296                         break;
297                 default:
298                         break;
299                 }
300         }
301 }
302
303 /* Destroys a closure which was demarshaled for dispatch; unrefs all the
304  * proxies in its arguments, as well as its own proxy, and destroys the
305  * closure itself. */
306 static void
307 destroy_queued_closure(struct wl_closure *closure)
308 {
309         const char *signature;
310         struct argument_details arg;
311         struct wl_proxy *proxy;
312         int i, count;
313
314         signature = closure->message->signature;
315         count = arg_count_for_signature(signature);
316         for (i = 0; i < count; i++) {
317                 signature = get_next_argument(signature, &arg);
318                 switch (arg.type) {
319                 case 'n':
320                 case 'o':
321                         proxy = (struct wl_proxy *) closure->args[i].o;
322                         if (proxy)
323                                 wl_proxy_unref(proxy);
324                         break;
325                 default:
326                         break;
327                 }
328         }
329
330         wl_proxy_unref(closure->proxy);
331         wl_closure_destroy(closure);
332 }
333
334 static void
335 wl_event_queue_release(struct wl_event_queue *queue)
336 {
337         struct wl_closure *closure;
338
339         if (!wl_list_empty(&queue->proxy_list)) {
340                 struct wl_proxy *proxy, *tmp;
341
342                 if (queue != &queue->display->default_queue) {
343                         wl_log("warning: queue %p destroyed while proxies "
344                                "still attached:\n", queue);
345                 }
346
347                 wl_list_for_each_safe(proxy, tmp, &queue->proxy_list,
348                                       queue_link) {
349                         if (queue != &queue->display->default_queue) {
350                                 wl_log("  %s@%u still attached\n",
351                                        proxy->object.interface->name,
352                                        proxy->object.id);
353                         }
354                         proxy->queue = NULL;
355                         wl_list_remove(&proxy->queue_link);
356                         wl_list_init(&proxy->queue_link);
357                 }
358         }
359
360         while (!wl_list_empty(&queue->event_list)) {
361                 closure = wl_container_of(queue->event_list.next,
362                                           closure, link);
363                 wl_list_remove(&closure->link);
364                 destroy_queued_closure(closure);
365         }
366 }
367
368 /** Destroy an event queue
369  *
370  * \param queue The event queue to be destroyed
371  *
372  * Destroy the given event queue. Any pending event on that queue is
373  * discarded.
374  *
375  * The \ref wl_display object used to create the queue should not be
376  * destroyed until all event queues created with it are destroyed with
377  * this function.
378  *
379  * \memberof wl_event_queue
380  */
381 WL_EXPORT void
382 wl_event_queue_destroy(struct wl_event_queue *queue)
383 {
384         struct wl_display *display = queue->display;
385
386         pthread_mutex_lock(&display->mutex);
387         wl_event_queue_release(queue);
388         wl_log("display(%p) queue(%p) destroyed", display, queue);
389         free(queue);
390         pthread_mutex_unlock(&display->mutex);
391 }
392
393 /** Create a new event queue for this display
394  *
395  * \param display The display context object
396  * \return A new event queue associated with this display or NULL on
397  * failure.
398  *
399  * \memberof wl_display
400  */
401 WL_EXPORT struct wl_event_queue *
402 wl_display_create_queue(struct wl_display *display)
403 {
404         struct wl_event_queue *queue;
405
406         queue = zalloc(sizeof *queue);
407         if (queue == NULL)
408                 return NULL;
409
410         wl_log("display(%p) queue(%p) created", display, queue);
411
412         pthread_mutex_lock(&display->mutex);
413         wl_event_queue_init(queue, display);
414         pthread_mutex_unlock(&display->mutex);
415
416         return queue;
417 }
418
419 static int
420 message_count_fds(const char *signature)
421 {
422         unsigned int count, i, fds = 0;
423         struct argument_details arg;
424
425         count = arg_count_for_signature(signature);
426         for (i = 0; i < count; i++) {
427                 signature = get_next_argument(signature, &arg);
428                 if (arg.type == 'h')
429                         fds++;
430         }
431
432         return fds;
433 }
434
435 static struct wl_zombie *
436 prepare_zombie(struct wl_proxy *proxy)
437 {
438         const struct wl_interface *interface = proxy->object.interface;
439         const struct wl_message *message;
440         int i, count;
441         struct wl_zombie *zombie = NULL;
442
443         /* If we hit an event with an FD, ensure we have a zombie object and
444          * fill the fd_count slot for that event with the number of FDs for
445          * that event. Interfaces with no events containing FDs will not have
446          * zombie objects created. */
447         for (i = 0; i < interface->event_count; i++) {
448                 message = &interface->events[i];
449                 count = message_count_fds(message->signature);
450
451                 if (!count)
452                         continue;
453
454                 if (!zombie) {
455                         zombie = zalloc(sizeof(*zombie) +
456                                         (interface->event_count * sizeof(int)));
457                         if (!zombie)
458                                 return NULL;
459
460                         zombie->event_count = interface->event_count;
461                         zombie->fd_count = (int *) &zombie[1];
462                 }
463
464                 zombie->fd_count[i] = count;
465         }
466
467         return zombie;
468 }
469
470 static enum wl_iterator_result
471 free_zombies(void *element, void *data, uint32_t flags)
472 {
473         if (flags & WL_MAP_ENTRY_ZOMBIE)
474                 free(element);
475
476         return WL_ITERATOR_CONTINUE;
477 }
478
479 static struct wl_proxy *
480 proxy_create(struct wl_proxy *factory, const struct wl_interface *interface,
481              uint32_t version)
482 {
483         struct wl_proxy *proxy;
484         struct wl_display *display = factory->display;
485
486         proxy = zalloc(sizeof *proxy);
487         if (proxy == NULL)
488                 return NULL;
489
490         proxy->object.interface = interface;
491         proxy->display = display;
492         proxy->queue = factory->queue;
493         proxy->refcount = 1;
494         proxy->version = version;
495
496         proxy->object.id = wl_map_insert_new(&display->objects, 0, proxy);
497         if (proxy->object.id == 0) {
498                 free(proxy);
499                 return NULL;
500         }
501
502         wl_list_insert(&proxy->queue->proxy_list, &proxy->queue_link);
503
504         return proxy;
505 }
506
507 /** Create a proxy object with a given interface
508  *
509  * \param factory Factory proxy object
510  * \param interface Interface the proxy object should use
511  * \return A newly allocated proxy object or NULL on failure
512  *
513  * This function creates a new proxy object with the supplied interface. The
514  * proxy object will have an id assigned from the client id space. The id
515  * should be created on the compositor side by sending an appropriate request
516  * with \ref wl_proxy_marshal().
517  *
518  * The proxy will inherit the display and event queue of the factory object.
519  *
520  * \note This should not normally be used by non-generated code.
521  *
522  * \sa wl_display, wl_event_queue, wl_proxy_marshal()
523  *
524  * \memberof wl_proxy
525  */
526 WL_EXPORT struct wl_proxy *
527 wl_proxy_create(struct wl_proxy *factory, const struct wl_interface *interface)
528 {
529         struct wl_display *display = factory->display;
530         struct wl_proxy *proxy;
531
532         pthread_mutex_lock(&display->mutex);
533         proxy = proxy_create(factory, interface, factory->version);
534         pthread_mutex_unlock(&display->mutex);
535
536         return proxy;
537 }
538
539 /* The caller should hold the display lock */
540 static struct wl_proxy *
541 wl_proxy_create_for_id(struct wl_proxy *factory,
542                        uint32_t id, const struct wl_interface *interface)
543 {
544         struct wl_proxy *proxy;
545         struct wl_display *display = factory->display;
546
547         proxy = zalloc(sizeof *proxy);
548         if (proxy == NULL)
549                 return NULL;
550
551         proxy->object.interface = interface;
552         proxy->object.id = id;
553         proxy->display = display;
554         proxy->queue = factory->queue;
555         proxy->refcount = 1;
556         proxy->version = factory->version;
557
558         if (wl_map_insert_at(&display->objects, 0, id, proxy) == -1) {
559                 free(proxy);
560                 return NULL;
561         }
562
563         wl_list_insert(&proxy->queue->proxy_list, &proxy->queue_link);
564
565         return proxy;
566 }
567
568 static void
569 proxy_destroy(struct wl_proxy *proxy)
570 {
571         if (proxy->flags & WL_PROXY_FLAG_ID_DELETED) {
572                 wl_map_remove(&proxy->display->objects, proxy->object.id);
573         } else if (proxy->object.id < WL_SERVER_ID_START) {
574                 struct wl_zombie *zombie = prepare_zombie(proxy);
575
576                 /* The map now contains the zombie entry, until the delete_id
577                  * event arrives. */
578                 wl_map_insert_at(&proxy->display->objects,
579                                  WL_MAP_ENTRY_ZOMBIE,
580                                  proxy->object.id,
581                                  zombie);
582         } else {
583                 /* Clear the given proxy information from the map
584                  * only if it is not overriden. */
585                 if (!(proxy->flags & WL_PROXY_FLAG_ID_OVERRIDEN))
586                         wl_map_insert_at(&proxy->display->objects, 0,
587                                          proxy->object.id, NULL);
588         }
589
590         proxy->flags |= WL_PROXY_FLAG_DESTROYED;
591
592         proxy->queue = NULL;
593         wl_list_remove(&proxy->queue_link);
594         wl_list_init(&proxy->queue_link);
595
596         wl_proxy_unref(proxy);
597 }
598
599 static void
600 wl_proxy_destroy_caller_locks(struct wl_proxy *proxy)
601 {
602         if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
603                 wl_abort("Tried to destroy wrapper with wl_proxy_destroy()\n");
604
605         proxy_destroy(proxy);
606 }
607
608 /** Destroy a proxy object
609  *
610  * \param proxy The proxy to be destroyed
611  *
612  * \c proxy must not be a proxy wrapper.
613  *
614  * \note This function will abort in response to egregious
615  * errors, and will do so with the display lock held. This means
616  * SIGABRT handlers must not perform any actions that would
617  * attempt to take that lock, or a deadlock would occur.
618  *
619  * \memberof wl_proxy
620  */
621 WL_EXPORT void
622 wl_proxy_destroy(struct wl_proxy *proxy)
623 {
624         struct wl_display *display = proxy->display;
625
626         pthread_mutex_lock(&display->mutex);
627
628         wl_proxy_destroy_caller_locks(proxy);
629
630         pthread_mutex_unlock(&display->mutex);
631 }
632
633 /** Set a proxy's listener
634  *
635  * \param proxy The proxy object
636  * \param implementation The listener to be added to proxy
637  * \param data User data to be associated with the proxy
638  * \return 0 on success or -1 on failure
639  *
640  * Set proxy's listener to \c implementation and its user data to
641  * \c data. If a listener has already been set, this function
642  * fails and nothing is changed.
643  *
644  * \c implementation is a vector of function pointers. For an opcode
645  * \c n, \c implementation[n] should point to the handler of \c n for
646  * the given object.
647  *
648  * \c proxy must not be a proxy wrapper.
649  *
650  * \memberof wl_proxy
651  */
652 WL_EXPORT int
653 wl_proxy_add_listener(struct wl_proxy *proxy,
654                       void (**implementation)(void), void *data)
655 {
656         struct wl_display *display = proxy->display;
657
658         if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
659                 wl_abort("Proxy %p is a wrapper\n", proxy);
660
661         pthread_mutex_lock(&display->mutex);
662         if (proxy->object.implementation || proxy->dispatcher) {
663                 wl_log("proxy %s@%u already has listener\n",
664                        proxy->object.interface->name, proxy->object.id);
665                 pthread_mutex_unlock(&display->mutex);
666                 return -1;
667         }
668
669         proxy->object.implementation = implementation;
670         proxy->user_data = data;
671
672         pthread_mutex_unlock(&display->mutex);
673
674         return 0;
675 }
676
677 /** Get a proxy's listener
678  *
679  * \param proxy The proxy object
680  * \return The address of the proxy's listener or NULL if no listener is set
681  *
682  * Gets the address to the proxy's listener; which is the listener set with
683  * \ref wl_proxy_add_listener.
684  *
685  * This function is useful in clients with multiple listeners on the same
686  * interface to allow the identification of which code to execute.
687  *
688  * \memberof wl_proxy
689  */
690 WL_EXPORT const void *
691 wl_proxy_get_listener(struct wl_proxy *proxy)
692 {
693         struct wl_display *display = proxy->display;
694         const void *listener;
695
696         pthread_mutex_lock(&display->mutex);
697         listener = proxy->object.implementation;
698         pthread_mutex_unlock(&display->mutex);
699
700         return listener;
701 }
702
703 /** Set a proxy's listener (with dispatcher)
704  *
705  * \param proxy The proxy object
706  * \param dispatcher The dispatcher to be used for this proxy
707  * \param implementation The dispatcher-specific listener implementation
708  * \param data User data to be associated with the proxy
709  * \return 0 on success or -1 on failure
710  *
711  * Set proxy's listener to use \c dispatcher_func as its dispatcher and \c
712  * dispatcher_data as its dispatcher-specific implementation and its user data
713  * to \c data. If a listener has already been set, this function
714  * fails and nothing is changed.
715  *
716  * The exact details of dispatcher_data depend on the dispatcher used.  This
717  * function is intended to be used by language bindings, not user code.
718  *
719  * \c proxy must not be a proxy wrapper.
720  *
721  * \memberof wl_proxy
722  */
723 WL_EXPORT int
724 wl_proxy_add_dispatcher(struct wl_proxy *proxy,
725                         wl_dispatcher_func_t dispatcher,
726                         const void *implementation, void *data)
727 {
728         struct wl_display *display = proxy->display;
729
730         if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
731                 wl_abort("Proxy %p is a wrapper\n", proxy);
732
733         pthread_mutex_lock(&display->mutex);
734
735         if (proxy->object.implementation || proxy->dispatcher) {
736                 wl_log("proxy %s@%u already has listener\n",
737                        proxy->object.interface->name, proxy->object.id);
738                 pthread_mutex_unlock(&display->mutex);
739                 return -1;
740         }
741
742         proxy->object.implementation = implementation;
743         proxy->dispatcher = dispatcher;
744         proxy->user_data = data;
745
746         pthread_mutex_unlock(&display->mutex);
747
748         return 0;
749 }
750
751 static struct wl_proxy *
752 create_outgoing_proxy(struct wl_proxy *proxy, const struct wl_message *message,
753                       union wl_argument *args,
754                       const struct wl_interface *interface, uint32_t version)
755 {
756         int i, count;
757         const char *signature;
758         struct argument_details arg;
759         struct wl_proxy *new_proxy = NULL;
760
761         signature = message->signature;
762         count = arg_count_for_signature(signature);
763         for (i = 0; i < count; i++) {
764                 signature = get_next_argument(signature, &arg);
765
766                 switch (arg.type) {
767                 case 'n':
768                         new_proxy = proxy_create(proxy, interface, version);
769                         if (new_proxy == NULL)
770                                 return NULL;
771
772                         args[i].o = &new_proxy->object;
773                         break;
774                 }
775         }
776
777         return new_proxy;
778 }
779
780 /** Prepare a request to be sent to the compositor
781  *
782  * \param proxy The proxy object
783  * \param opcode Opcode of the request to be sent
784  * \param args Extra arguments for the given request
785  * \param interface The interface to use for the new proxy
786  *
787  * This function translates a request given an opcode, an interface and a
788  * wl_argument array to the wire format and writes it to the connection
789  * buffer.
790  *
791  * For new-id arguments, this function will allocate a new wl_proxy
792  * and send the ID to the server.  The new wl_proxy will be returned
793  * on success or NULL on error with errno set accordingly.  The newly
794  * created proxy will inherit their version from their parent.
795  *
796  * \note This is intended to be used by language bindings and not in
797  * non-generated code.
798  *
799  * \sa wl_proxy_marshal()
800  *
801  * \memberof wl_proxy
802  */
803 WL_EXPORT struct wl_proxy *
804 wl_proxy_marshal_array_constructor(struct wl_proxy *proxy,
805                                    uint32_t opcode, union wl_argument *args,
806                                    const struct wl_interface *interface)
807 {
808         return wl_proxy_marshal_array_constructor_versioned(proxy, opcode,
809                                                             args, interface,
810                                                             proxy->version);
811 }
812
813 // TIZEN_ONLY(20190716) : leave log about pending requests from clients if sendmsg() fails due to EAGAIN error
814 /** Print the client_entries of the wl_map
815  * \param map  Pointer to wl_map.
816  */
817 static void
818 print_map_client_enteries(struct wl_map *map)
819 {
820         struct wl_proxy *proxy = NULL;
821         char data[4096] = {'\0'};
822         char *str_ptr = data;
823         int length = sizeof(data), id = 0, count = 0;
824         int *len = &length;
825
826         count = wl_map_client_entries_count(map);
827         if(count <= 0)
828                 return;
829
830         WL_SNPRINTF(str_ptr, len, "Map Client Entries:\n"
831                                 " [Interface Name, ID]\n");
832         for (id = 0; id < count; id++) {
833                 proxy = wl_map_lookup(map, id);
834                 if (proxy && !wl_object_is_zombie(map, id)) {
835                         WL_SNPRINTF(str_ptr, len, "[%-15s, %-3d]\n",
836                                 proxy->object.interface->name, id);
837
838                         /* If the current data to be printed exceeds
839                          * 4096 bytes, print it and start to fill
840                          * from the beginning
841                          */
842                         if(length <= 0) {
843 #ifdef HAVE_DLOG
844                                 wl_dlog("%s", data);
845 #else
846                                 fprintf(stderr, "[%s][%d][Pid: %d] %s",
847                                         __FILE__, __LINE__, (int)getpid(), data);
848 #endif
849                                 length = sizeof(data);
850                                 memset(data, '\0', length);
851                                 str_ptr = data;
852                                 id--;
853                         }
854                 }
855         }
856 #ifdef HAVE_DLOG
857         wl_dlog("\n%s", data);
858 #else
859         fprintf(stderr, "[%s][%d][Pid: %d] \n%s",
860                 __FILE__, __LINE__, (int)getpid(), data);
861 #endif
862 }
863 // TIZEN_ONLY : END
864
865 /** Prepare a request to be sent to the compositor
866  *
867  * \param proxy The proxy object
868  * \param opcode Opcode of the request to be sent
869  * \param args Extra arguments for the given request
870  * \param interface The interface to use for the new proxy
871  * \param version The protocol object version for the new proxy
872  *
873  * Translates the request given by opcode and the extra arguments into the
874  * wire format and write it to the connection buffer.  This version takes an
875  * array of the union type wl_argument.
876  *
877  * For new-id arguments, this function will allocate a new wl_proxy
878  * and send the ID to the server.  The new wl_proxy will be returned
879  * on success or NULL on error with errno set accordingly.  The newly
880  * created proxy will have the version specified.
881  *
882  * \note This is intended to be used by language bindings and not in
883  * non-generated code.
884  *
885  * \sa wl_proxy_marshal()
886  *
887  * \memberof wl_proxy
888  */
889 WL_EXPORT struct wl_proxy *
890 wl_proxy_marshal_array_constructor_versioned(struct wl_proxy *proxy,
891                                              uint32_t opcode,
892                                              union wl_argument *args,
893                                              const struct wl_interface *interface,
894                                              uint32_t version)
895 {
896         return wl_proxy_marshal_array_flags(proxy, opcode, interface, version, 0, args);
897 }
898
899 /** Prepare a request to be sent to the compositor
900  *
901  * \param proxy The proxy object
902  * \param opcode Opcode of the request to be sent
903  * \param interface The interface to use for the new proxy
904  * \param version The protocol object version of the new proxy
905  * \param flags Flags that modify marshalling behaviour
906  * \param ... Extra arguments for the given request
907  * \return A new wl_proxy for the new_id argument or NULL on error
908  *
909  * Translates the request given by opcode and the extra arguments into the
910  * wire format and write it to the connection buffer.
911  *
912  * For new-id arguments, this function will allocate a new wl_proxy
913  * and send the ID to the server.  The new wl_proxy will be returned
914  * on success or NULL on error with errno set accordingly.  The newly
915  * created proxy will have the version specified.
916  *
917  * The flag WL_MARSHAL_FLAG_DESTROY may be passed to ensure the proxy
918  * is destroyed atomically with the marshalling in order to prevent
919  * races that can occur if the display lock is dropped between the
920  * marshal and destroy operations.
921  *
922  * \note This should not normally be used by non-generated code.
923  *
924  * \memberof wl_proxy
925  */
926 WL_EXPORT struct wl_proxy *
927 wl_proxy_marshal_flags(struct wl_proxy *proxy, uint32_t opcode,
928                        const struct wl_interface *interface, uint32_t version,
929                        uint32_t flags, ...)
930 {
931         union wl_argument args[WL_CLOSURE_MAX_ARGS];
932         va_list ap;
933
934         va_start(ap, flags);
935         wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
936                                  args, WL_CLOSURE_MAX_ARGS, ap);
937         va_end(ap);
938
939         return wl_proxy_marshal_array_flags(proxy, opcode, interface, version, flags, args);
940 }
941
942 /** Prepare a request to be sent to the compositor
943  *
944  * \param proxy The proxy object
945  * \param opcode Opcode of the request to be sent
946  * \param interface The interface to use for the new proxy
947  * \param version The protocol object version for the new proxy
948  * \param flags Flags that modify marshalling behaviour
949  * \param args Extra arguments for the given request
950  *
951  * Translates the request given by opcode and the extra arguments into the
952  * wire format and write it to the connection buffer.  This version takes an
953  * array of the union type wl_argument.
954  *
955  * For new-id arguments, this function will allocate a new wl_proxy
956  * and send the ID to the server.  The new wl_proxy will be returned
957  * on success or NULL on error with errno set accordingly.  The newly
958  * created proxy will have the version specified.
959  *
960  * The flag WL_MARSHAL_FLAG_DESTROY may be passed to ensure the proxy
961  * is destroyed atomically with the marshalling in order to prevent
962  * races that can occur if the display lock is dropped between the
963  * marshal and destroy operations.
964  *
965  * \note This is intended to be used by language bindings and not in
966  * non-generated code.
967  *
968  * \sa wl_proxy_marshal_flags()
969  *
970  * \memberof wl_proxy
971  */
972 WL_EXPORT struct wl_proxy *
973 wl_proxy_marshal_array_flags(struct wl_proxy *proxy, uint32_t opcode,
974                              const struct wl_interface *interface, uint32_t version,
975                              uint32_t flags, union wl_argument *args)
976 {
977         struct wl_closure *closure;
978         struct wl_proxy *new_proxy = NULL;
979         const struct wl_message *message;
980         struct wl_display *disp = proxy->display;
981
982         pthread_mutex_lock(&disp->mutex);
983
984         message = &proxy->object.interface->methods[opcode];
985         if (interface) {
986                 new_proxy = create_outgoing_proxy(proxy, message,
987                                                   args, interface,
988                                                   version);
989                 if (new_proxy == NULL)
990                         goto err_unlock;
991         }
992
993         if (proxy->display->last_error) {
994                 goto err_unlock;
995         }
996
997         closure = wl_closure_marshal(&proxy->object, opcode, args, message);
998         if (closure == NULL) {
999                 // TIZEN_ONLY(20210310) : wayland-client : do not abort when there is an EBADF error on marshalling request
1000                 if (errno == EBADF) {
1001                         wl_log("fail wl_closure_marshal with EBADF");
1002                         if (new_proxy) {
1003                                 new_proxy->flags |= WL_PROXY_FLAG_ID_DELETED;
1004                                 proxy_destroy(new_proxy);
1005                                 new_proxy = NULL;
1006                         }
1007                         goto err_unlock;
1008                 }
1009                 // TIZEN_ONLY : END
1010
1011                 // TIZEN_ONLY(20200306) : wayland-client : do abort when there is an error on marshalling request
1012                 wl_abort("Error marshalling request: %m\n");
1013                 // TIZEN_ONLY : END
1014                 //wl_log("Error marshalling request: %m\n");
1015                 //display_fatal_error(proxy->display, errno);
1016                 //goto err_unlock;
1017         }
1018
1019         if (debug_client)
1020                 wl_closure_print(closure, &proxy->object, true, false, NULL);
1021
1022         if (wl_closure_send(closure, proxy->display->connection)) {
1023                 // TIZEN_ONLY(20170328) : leave log about pending requests from clients if sendmsg() fails due to EAGAIN error
1024                 if (errno == EAGAIN) {
1025                         wl_closure_print(closure, &proxy->object, true, false, NULL);
1026                         wl_print_connection_data(proxy->display->connection, OUT);
1027                         print_map_client_enteries(&(proxy->display->objects));
1028                 }
1029                 // TIZEN_ONLY : END
1030                 wl_abort("Error sending request: %m\n");
1031                 //wl_log("Error sending request: %m\n");
1032                 //display_fatal_error(proxy->display, errno);
1033         }
1034
1035         wl_closure_destroy(closure);
1036
1037  err_unlock:
1038         if (flags & WL_MARSHAL_FLAG_DESTROY)
1039                 wl_proxy_destroy_caller_locks(proxy);
1040
1041         pthread_mutex_unlock(&disp->mutex);
1042
1043         return new_proxy;
1044 }
1045
1046
1047 /** Prepare a request to be sent to the compositor
1048  *
1049  * \param proxy The proxy object
1050  * \param opcode Opcode of the request to be sent
1051  * \param ... Extra arguments for the given request
1052  *
1053  * This function is similar to wl_proxy_marshal_constructor(), except
1054  * it doesn't create proxies for new-id arguments.
1055  *
1056  * \note This should not normally be used by non-generated code.
1057  *
1058  * \sa wl_proxy_create()
1059  *
1060  * \memberof wl_proxy
1061  */
1062 WL_EXPORT void
1063 wl_proxy_marshal(struct wl_proxy *proxy, uint32_t opcode, ...)
1064 {
1065         union wl_argument args[WL_CLOSURE_MAX_ARGS];
1066         va_list ap;
1067
1068         va_start(ap, opcode);
1069         wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
1070                                  args, WL_CLOSURE_MAX_ARGS, ap);
1071         va_end(ap);
1072
1073         wl_proxy_marshal_array_constructor(proxy, opcode, args, NULL);
1074 }
1075
1076 /** Prepare a request to be sent to the compositor
1077  *
1078  * \param proxy The proxy object
1079  * \param opcode Opcode of the request to be sent
1080  * \param interface The interface to use for the new proxy
1081  * \param ... Extra arguments for the given request
1082  * \return A new wl_proxy for the new_id argument or NULL on error
1083  *
1084  * This function translates a request given an opcode, an interface and extra
1085  * arguments to the wire format and writes it to the connection buffer. The
1086  * types of the extra arguments must correspond to the argument types of the
1087  * method associated with the opcode in the interface.
1088  *
1089  * For new-id arguments, this function will allocate a new wl_proxy
1090  * and send the ID to the server.  The new wl_proxy will be returned
1091  * on success or NULL on error with errno set accordingly.  The newly
1092  * created proxy will inherit their version from their parent.
1093  *
1094  * \note This should not normally be used by non-generated code.
1095  *
1096  * \memberof wl_proxy
1097  */
1098 WL_EXPORT struct wl_proxy *
1099 wl_proxy_marshal_constructor(struct wl_proxy *proxy, uint32_t opcode,
1100                              const struct wl_interface *interface, ...)
1101 {
1102         union wl_argument args[WL_CLOSURE_MAX_ARGS];
1103         va_list ap;
1104
1105         va_start(ap, interface);
1106         wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
1107                                  args, WL_CLOSURE_MAX_ARGS, ap);
1108         va_end(ap);
1109
1110         return wl_proxy_marshal_array_constructor(proxy, opcode,
1111                                                   args, interface);
1112 }
1113
1114
1115 /** Prepare a request to be sent to the compositor
1116  *
1117  * \param proxy The proxy object
1118  * \param opcode Opcode of the request to be sent
1119  * \param interface The interface to use for the new proxy
1120  * \param version The protocol object version of the new proxy
1121  * \param ... Extra arguments for the given request
1122  * \return A new wl_proxy for the new_id argument or NULL on error
1123  *
1124  * Translates the request given by opcode and the extra arguments into the
1125  * wire format and write it to the connection buffer.
1126  *
1127  * For new-id arguments, this function will allocate a new wl_proxy
1128  * and send the ID to the server.  The new wl_proxy will be returned
1129  * on success or NULL on error with errno set accordingly.  The newly
1130  * created proxy will have the version specified.
1131  *
1132  * \note This should not normally be used by non-generated code.
1133  *
1134  * \memberof wl_proxy
1135  */
1136 WL_EXPORT struct wl_proxy *
1137 wl_proxy_marshal_constructor_versioned(struct wl_proxy *proxy, uint32_t opcode,
1138                                        const struct wl_interface *interface,
1139                                        uint32_t version, ...)
1140 {
1141         union wl_argument args[WL_CLOSURE_MAX_ARGS];
1142         va_list ap;
1143
1144         va_start(ap, version);
1145         wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
1146                                  args, WL_CLOSURE_MAX_ARGS, ap);
1147         va_end(ap);
1148
1149         return wl_proxy_marshal_array_constructor_versioned(proxy, opcode,
1150                                                             args, interface,
1151                                                             version);
1152 }
1153
1154 /** Prepare a request to be sent to the compositor
1155  *
1156  * \param proxy The proxy object
1157  * \param opcode Opcode of the request to be sent
1158  * \param args Extra arguments for the given request
1159  *
1160  * This function is similar to wl_proxy_marshal_array_constructor(), except
1161  * it doesn't create proxies for new-id arguments.
1162  *
1163  * \note This is intended to be used by language bindings and not in
1164  * non-generated code.
1165  *
1166  * \sa wl_proxy_marshal()
1167  *
1168  * \memberof wl_proxy
1169  */
1170 WL_EXPORT void
1171 wl_proxy_marshal_array(struct wl_proxy *proxy, uint32_t opcode,
1172                        union wl_argument *args)
1173 {
1174         wl_proxy_marshal_array_constructor(proxy, opcode, args, NULL);
1175 }
1176
1177 static void
1178 display_handle_error(void *data,
1179                      struct wl_display *display, void *object,
1180                      uint32_t code, const char *message)
1181 {
1182         struct wl_proxy *proxy = object;
1183         uint32_t object_id;
1184         const struct wl_interface *interface;
1185
1186         if (proxy) {
1187                 wl_log("%s@%u: error %d: %s\n",
1188                        proxy->object.interface->name,
1189                        proxy->object.id,
1190                        code, message);
1191
1192                 object_id = proxy->object.id;
1193                 interface = proxy->object.interface;
1194
1195                 pthread_mutex_lock(&display->mutex);
1196                 if (!display->last_error)
1197                         snprintf(display->protocol_error.message, 512, "%s@%u: error %d: %s\n",
1198                                  proxy->object.interface->name, proxy->object.id, code, message);
1199                 pthread_mutex_unlock(&display->mutex);
1200
1201         } else {
1202                 wl_log("[destroyed object]: error %d: %s\n",
1203                        code, message);
1204
1205                 object_id = 0;
1206                 interface = NULL;
1207
1208                 pthread_mutex_lock(&display->mutex);
1209                 if (!display->last_error)
1210                         snprintf(display->protocol_error.message, 512,
1211                                  "[destroyed object]: error %d: %s\n", code, message);
1212                 pthread_mutex_unlock(&display->mutex);
1213         }
1214
1215         display_protocol_error(display, code, object_id, interface);
1216 }
1217
1218 static void
1219 display_handle_delete_id(void *data, struct wl_display *display, uint32_t id)
1220 {
1221         struct wl_proxy *proxy;
1222
1223         pthread_mutex_lock(&display->mutex);
1224
1225         proxy = wl_map_lookup(&display->objects, id);
1226
1227         if (wl_object_is_zombie(&display->objects, id)) {
1228                 /* For zombie objects, the 'proxy' is actually the zombie
1229                  * event-information structure, which we can free. */
1230                 free(proxy);
1231                 wl_map_remove(&display->objects, id);
1232         } else if (proxy) {
1233                 proxy->flags |= WL_PROXY_FLAG_ID_DELETED;
1234         } else {
1235                 wl_log("error: received delete_id for unknown id (%u)\n", id);
1236         }
1237
1238         pthread_mutex_unlock(&display->mutex);
1239 }
1240
1241 static const struct wl_display_listener display_listener = {
1242         display_handle_error,
1243         display_handle_delete_id
1244 };
1245
1246 static int
1247 connect_to_socket(const char *name)
1248 {
1249         struct sockaddr_un addr;
1250         socklen_t size;
1251         const char *runtime_dir;
1252         int name_size, fd;
1253         bool path_is_absolute;
1254
1255         if (name == NULL)
1256                 name = getenv("WAYLAND_DISPLAY");
1257         if (name == NULL)
1258                 name = "wayland-0";
1259
1260         path_is_absolute = name[0] == '/';
1261
1262         runtime_dir = getenv("XDG_RUNTIME_DIR");
1263         if (((!runtime_dir || runtime_dir[0] != '/') && !path_is_absolute)) {
1264                 wl_log("error: XDG_RUNTIME_DIR is invalid or not set in the environment.\n");
1265                 /* to prevent programs reporting
1266                  * "failed to create display: Success" */
1267                 errno = ENOENT;
1268                 return -1;
1269         }
1270
1271         fd = wl_os_socket_cloexec(PF_LOCAL, SOCK_STREAM, 0);
1272         if (fd < 0)
1273                 return -1;
1274
1275         memset(&addr, 0, sizeof addr);
1276         addr.sun_family = AF_LOCAL;
1277         if (!path_is_absolute) {
1278                 name_size =
1279                         snprintf(addr.sun_path, sizeof addr.sun_path,
1280                                  "%s/%s", runtime_dir, name) + 1;
1281         } else {
1282                 /* absolute path */
1283                 name_size =
1284                         snprintf(addr.sun_path, sizeof addr.sun_path,
1285                                  "%s", name) + 1;
1286         }
1287
1288         assert(name_size > 0);
1289         if (name_size > (int)sizeof addr.sun_path) {
1290                 if (!path_is_absolute) {
1291                         wl_log("error: socket path \"%s/%s\" plus null terminator"
1292                                " exceeds %i bytes\n", runtime_dir, name, (int) sizeof(addr.sun_path));
1293                 } else {
1294                         wl_log("error: socket path \"%s\" plus null terminator"
1295                                " exceeds %i bytes\n", name, (int) sizeof(addr.sun_path));
1296                 }
1297                 close(fd);
1298                 /* to prevent programs reporting
1299                  * "failed to add socket: Success" */
1300                 errno = ENAMETOOLONG;
1301                 return -1;
1302         };
1303
1304         size = offsetof (struct sockaddr_un, sun_path) + name_size;
1305
1306         if (connect(fd, (struct sockaddr *) &addr, size) < 0) {
1307                 // TIZEN_ONLY(20170410): Debug logs to identify the failure cause of wl_display_connect()
1308                 wl_log("connect() failed: fd(%d) errno(%d, %m) socket path(%s)\n", fd, errno, addr.sun_path);
1309                 // END
1310                 close(fd);
1311                 return -1;
1312         }
1313
1314         return fd;
1315 }
1316
1317 /** Connect to Wayland display on an already open fd
1318  *
1319  * \param fd The fd to use for the connection
1320  * \return A \ref wl_display object or \c NULL on failure
1321  *
1322  * The wl_display takes ownership of the fd and will close it when the
1323  * display is destroyed.  The fd will also be closed in case of
1324  * failure.
1325  *
1326  * \memberof wl_display
1327  */
1328 WL_EXPORT struct wl_display *
1329 wl_display_connect_to_fd(int fd)
1330 {
1331         struct wl_display *display;
1332         const char *debug;
1333
1334         debug = getenv("WAYLAND_DLOG");
1335         if (debug && (strstr(debug, "client") || strstr(debug, "1")))
1336                 debug_dlog = 1;
1337
1338         debug = getenv("WAYLAND_DEBUG");
1339         if (debug && (strstr(debug, "client") || strstr(debug, "1")))
1340                 debug_client = 1;
1341
1342         display = zalloc(sizeof *display);
1343         if (display == NULL) {
1344                 // TIZEN_ONLY(20170410): Debbug logs to identify the failure cause of wl_display_connect()
1345                 wl_log("no memory\n");
1346                 errno = ENOMEM;
1347                 // END
1348                 close(fd);
1349                 return NULL;
1350         }
1351
1352         display->fd = fd;
1353         display->prev_errno = 0;
1354         display->last_error = 0;
1355         display->name = NULL;
1356         wl_map_init(&display->objects, WL_MAP_CLIENT_SIDE);
1357         wl_event_queue_init(&display->default_queue, display);
1358         wl_event_queue_init(&display->display_queue, display);
1359         pthread_mutex_init(&display->mutex, NULL);
1360         pthread_cond_init(&display->reader_cond, NULL);
1361         display->reader_count = 0;
1362 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
1363         display->force_sync_count = 0;
1364 // END
1365
1366         if (wl_map_insert_at(&display->objects, 0, 0, NULL) == -1)
1367                 goto err_connection;
1368
1369         display->proxy.object.id =
1370                 wl_map_insert_new(&display->objects, 0, display);
1371
1372         if (display->proxy.object.id == 0)
1373                 goto err_connection;
1374
1375         display->proxy.object.interface = &wl_display_interface;
1376         display->proxy.display = display;
1377         display->proxy.object.implementation = (void(**)(void)) &display_listener;
1378         display->proxy.user_data = display;
1379         display->proxy.queue = &display->default_queue;
1380         display->proxy.flags = 0;
1381         display->proxy.refcount = 1;
1382
1383         display->protocol_error.message[0] = '\0';
1384
1385         /* We set this version to 0 for backwards compatibility.
1386          *
1387          * If a client is using old versions of protocol headers,
1388          * it will use unversioned API to create proxies.  Those
1389          * proxies will inherit this 0.
1390          *
1391          * A client could be passing these proxies into library
1392          * code newer than the headers that checks proxy
1393          * versions.  When the proxy version is reported as 0
1394          * the library will know that it can't reliably determine
1395          * the proxy version, and should do whatever fallback is
1396          * required.
1397          *
1398          * This trick forces wl_display to always report 0, but
1399          * since it's a special object that we can't bind
1400          * specific versions of anyway, this should be fine.
1401          */
1402         display->proxy.version = 0;
1403
1404         display->connection = wl_connection_create(display->fd);
1405         if (display->connection == NULL)
1406                 goto err_connection;
1407
1408 #ifdef WL_DEBUG_QUEUE
1409         if (debug_client)
1410                 wl_dlog("display(%p) default_queue(%p) display_queue(%p) fd(%d)",
1411                         display, &display->default_queue, &display->display_queue, display->fd);
1412 #endif
1413
1414         wl_log("display(%p) connected.", display);
1415
1416         return display;
1417
1418  err_connection:
1419         // TIZEN_ONLY(20170410): Debug logs to identify the failure cause of wl_display_connect()
1420         wl_log("%s() failed. display(%p), fd(%d), errno(%d, %m)\n", __func__, display, fd, errno);
1421         // END
1422         pthread_mutex_destroy(&display->mutex);
1423         pthread_cond_destroy(&display->reader_cond);
1424         wl_map_release(&display->objects);
1425         close(display->fd);
1426         free(display);
1427
1428         return NULL;
1429 }
1430
1431 /** Connect to a Wayland display
1432  *
1433  * \param name Name of the Wayland display to connect to
1434  * \return A \ref wl_display object or \c NULL on failure
1435  *
1436  * Connect to the Wayland display named \c name. If \c name is \c NULL,
1437  * its value will be replaced with the WAYLAND_DISPLAY environment
1438  * variable if it is set, otherwise display "wayland-0" will be used.
1439  *
1440  * If WAYLAND_SOCKET is set, it's interpreted as a file descriptor number
1441  * referring to an already opened socket. In this case, the socket is used
1442  * as-is and \c name is ignored.
1443  *
1444  * If \c name is a relative path, then the socket is opened relative to
1445  * the XDG_RUNTIME_DIR directory.
1446  *
1447  * If \c name is an absolute path, then that path is used as-is for
1448  * the location of the socket at which the Wayland server is listening;
1449  * no qualification inside XDG_RUNTIME_DIR is attempted.
1450  *
1451  * If \c name is \c NULL and the WAYLAND_DISPLAY environment variable
1452  * is set to an absolute pathname, then that pathname is used as-is
1453  * for the socket in the same manner as if \c name held an absolute
1454  * path. Support for absolute paths in \c name and WAYLAND_DISPLAY
1455  * is present since Wayland version 1.15.
1456  *
1457  * \memberof wl_display
1458  */
1459 WL_EXPORT struct wl_display *
1460 wl_display_connect(const char *name)
1461 {
1462         char *connection, *end;
1463         int flags, fd;
1464
1465         connection = getenv("WAYLAND_SOCKET");
1466         if (connection) {
1467                 int prev_errno = errno;
1468                 errno = 0;
1469                 fd = strtol(connection, &end, 10);
1470                 if (errno != 0 || connection == end || *end != '\0')
1471                 {
1472                         wl_log("error: fd(%d), errno(%d, %m)\n", fd, errno);
1473                         return NULL;
1474                 }
1475                 errno = prev_errno;
1476
1477                 if (fd < 0 || fd > INT_MAX - 1)
1478                         return NULL;
1479
1480                 flags = fcntl(fd, F_GETFD);
1481                 if (flags == -1 && errno == EBADF)
1482                         return NULL;
1483                 else if (flags != -1)
1484                         fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
1485                 unsetenv("WAYLAND_SOCKET");
1486         } else {
1487                 fd = connect_to_socket(name);
1488                 if (fd < 0)
1489                         return NULL;
1490         }
1491
1492         return wl_display_connect_to_fd(fd);
1493 }
1494
1495 /** Close a connection to a Wayland display
1496  *
1497  * \param display The display context object
1498  *
1499  * Close the connection to \c display and free all resources associated
1500  * with it.
1501  *
1502  * \memberof wl_display
1503  */
1504 WL_EXPORT void
1505 wl_display_disconnect(struct wl_display *display)
1506 {
1507         wl_connection_destroy(display->connection);
1508         wl_map_for_each(&display->objects, free_zombies, NULL);
1509         wl_map_release(&display->objects);
1510         wl_event_queue_release(&display->default_queue);
1511         wl_event_queue_release(&display->display_queue);
1512         pthread_mutex_destroy(&display->mutex);
1513         pthread_cond_destroy(&display->reader_cond);
1514         close(display->fd);
1515
1516         wl_log("display(%p) disconnected", display);
1517
1518         if (display->name)
1519                 free(display->name);
1520         free(display);
1521 }
1522
1523 /** Get a display context's file descriptor
1524  *
1525  * \param display The display context object
1526  * \return Display object file descriptor
1527  *
1528  * Return the file descriptor associated with a display so it can be
1529  * integrated into the client's main loop.
1530  *
1531  * \memberof wl_display
1532  */
1533 WL_EXPORT int
1534 wl_display_get_fd(struct wl_display *display)
1535 {
1536         return display->fd;
1537 }
1538
1539 static void
1540 sync_callback(void *data, struct wl_callback *callback, uint32_t serial)
1541 {
1542         int *done = data;
1543
1544         *done = 1;
1545         wl_callback_destroy(callback);
1546 }
1547
1548 static const struct wl_callback_listener sync_listener = {
1549         sync_callback
1550 };
1551
1552 static int display_dispatch_queue_ensure_flush(struct wl_display *display,
1553         struct wl_event_queue *queue);
1554
1555 /** Block until all pending request are processed by the server
1556  *
1557  * \param display The display context object
1558  * \param queue The queue on which to run the roundtrip
1559  * \return The number of dispatched events on success or -1 on failure
1560  *
1561  * This function blocks until the server has processed all currently issued
1562  * requests by sending a request to the display server and waiting for a
1563  * reply before returning.
1564  *
1565  * This function uses wl_display_dispatch_queue() internally. It is not allowed
1566  * to call this function while the thread is being prepared for reading events,
1567  * and doing so will cause a dead lock.
1568  *
1569  * \note This function may dispatch other events being received on the given
1570  * queue.
1571  *
1572  * \sa wl_display_roundtrip()
1573  * \memberof wl_display
1574  */
1575 WL_EXPORT int
1576 wl_display_roundtrip_queue(struct wl_display *display, struct wl_event_queue *queue)
1577 {
1578         struct wl_display *display_wrapper;
1579         struct wl_callback *callback;
1580         int done, ret = 0;
1581
1582         done = 0;
1583
1584         display_wrapper = wl_proxy_create_wrapper(display);
1585         if (!display_wrapper)
1586                 return -1;
1587
1588         wl_proxy_set_queue((struct wl_proxy *) display_wrapper, queue);
1589         callback = wl_display_sync(display_wrapper);
1590         wl_proxy_wrapper_destroy(display_wrapper);
1591
1592         if (callback == NULL)
1593                 return -1;
1594
1595         wl_callback_add_listener(callback, &sync_listener, &done);
1596         while (!done && ret >= 0)
1597                 ret = display_dispatch_queue_ensure_flush(display, queue);
1598
1599         if (ret == -1 && !done)
1600                 wl_callback_destroy(callback);
1601
1602         return ret;
1603 }
1604
1605 /** Block until all pending request are processed by the server
1606  *
1607  * \param display The display context object
1608  * \return The number of dispatched events on success or -1 on failure
1609  *
1610  * This function blocks until the server has processed all currently issued
1611  * requests by sending a request to the display server and waiting for a reply
1612  * before returning.
1613  *
1614  * This function uses wl_display_dispatch_queue() internally. It is not allowed
1615  * to call this function while the thread is being prepared for reading events,
1616  * and doing so will cause a dead lock.
1617  *
1618  * \note This function may dispatch other events being received on the default
1619  * queue.
1620  *
1621  * \memberof wl_display
1622  */
1623 WL_EXPORT int
1624 wl_display_roundtrip(struct wl_display *display)
1625 {
1626         return wl_display_roundtrip_queue(display, &display->default_queue);
1627 }
1628
1629 static int
1630 create_proxies(struct wl_proxy *sender, struct wl_closure *closure)
1631 {
1632         struct wl_proxy *proxy;
1633         const char *signature;
1634         struct argument_details arg;
1635         uint32_t id;
1636         int i;
1637         int count;
1638
1639         signature = closure->message->signature;
1640         count = arg_count_for_signature(signature);
1641         for (i = 0; i < count; i++) {
1642                 signature = get_next_argument(signature, &arg);
1643                 switch (arg.type) {
1644                 case 'n':
1645                         id = closure->args[i].n;
1646                         if (id == 0) {
1647                                 closure->args[i].o = NULL;
1648                                 break;
1649                         }
1650                         proxy = wl_proxy_create_for_id(sender, id,
1651                                                        closure->message->types[i]);
1652                         if (proxy == NULL)
1653                                 return -1;
1654                         closure->args[i].o = (struct wl_object *)proxy;
1655                         break;
1656                 default:
1657                         break;
1658                 }
1659         }
1660
1661         return 0;
1662 }
1663
1664 static void
1665 increase_closure_args_refcount(struct wl_closure *closure)
1666 {
1667         const char *signature;
1668         struct argument_details arg;
1669         int i, count;
1670         struct wl_proxy *proxy;
1671
1672         signature = closure->message->signature;
1673         count = arg_count_for_signature(signature);
1674         for (i = 0; i < count; i++) {
1675                 signature = get_next_argument(signature, &arg);
1676                 switch (arg.type) {
1677                 case 'n':
1678                 case 'o':
1679                         proxy = (struct wl_proxy *) closure->args[i].o;
1680                         if (proxy)
1681                                 proxy->refcount++;
1682                         break;
1683                 default:
1684                         break;
1685                 }
1686         }
1687
1688         closure->proxy->refcount++;
1689 }
1690
1691 int
1692 wl_display_override_object_id(void *object, const uint32_t id, int side)
1693 {
1694         struct wl_proxy *proxy = (struct wl_proxy *)object;
1695         struct wl_proxy *overriden_proxy;
1696
1697         /* Check if the given object is the pointer of wl_proxy object */
1698         if (!proxy || (sizeof(*proxy) != sizeof(struct wl_proxy))) {
1699                 wl_log("errno:%d\n", errno);
1700                 wl_abort("invalid object data to override (id:%u, errno:%d)\n", id, errno = EINVAL);
1701                 return 0;
1702         }
1703         else if (id < WL_SERVER_ID_START || side != WL_MAP_CLIENT_SIDE) {
1704                 wl_log("errno:%d\n", errno);
1705                 wl_abort("invalid object id to override (id:%u, side:%d, errno:%d)\n", id, side, errno = EINVAL);
1706                 return 0;
1707         }
1708
1709         overriden_proxy = wl_map_lookup(&proxy->display->objects, id);
1710         if (!overriden_proxy) {
1711                 if (errno || proxy->display->last_error)
1712                         wl_log("display:%p, errno:%d, last_error:%d\n", proxy->display, errno, proxy->display->last_error);
1713                 wl_abort("no proxy found with the given object id(%u), errno(%d)\n", id, errno = EINVAL);
1714                 return 0;
1715         }
1716         else if (overriden_proxy != proxy) {
1717                 if (errno || proxy->display->last_error)
1718                         wl_log("display:%p, errno:%d, last_error:%d\n", proxy->display, errno, proxy->display->last_error);
1719                 wl_abort("invalid proxy objects(%p, %p) found (id:%u), errno(%d)\n", overriden_proxy, proxy, id, errno = EINVAL);
1720                 return 0;
1721         }
1722
1723         /* Set overriden flag for the overriden proxy not to set data as NULL later. */
1724         overriden_proxy->flags |= WL_PROXY_FLAG_ID_OVERRIDEN;
1725         overriden_proxy->object.id = 0;
1726
1727         wl_log("proxy(%p) with id(%u) has been overriden\n", overriden_proxy, id);
1728         return 1;
1729 }
1730
1731 static int
1732 queue_event(struct wl_display *display, int len)
1733 {
1734         uint32_t p[2], id;
1735         int opcode, size;
1736         struct wl_proxy *proxy;
1737         struct wl_closure *closure;
1738         const struct wl_message *message;
1739         struct wl_event_queue *queue;
1740         struct timespec tp;
1741         unsigned int time;
1742         int num_zombie_fds;
1743
1744         wl_connection_copy(display->connection, p, sizeof p);
1745         id = p[0];
1746         opcode = p[1] & 0xffff;
1747         size = p[1] >> 16;
1748         if (len < size)
1749                 return 0;
1750
1751         /* If our proxy is gone or a zombie, just eat the event (and any FDs,
1752          * if applicable). */
1753         proxy = wl_map_lookup(&display->objects, id);
1754         if (!proxy || wl_object_is_zombie(&display->objects, id)) {
1755                 struct wl_zombie *zombie = wl_map_lookup(&display->objects, id);
1756                 num_zombie_fds = (zombie && opcode < zombie->event_count) ?
1757                         zombie->fd_count[opcode] : 0;
1758
1759                 if (debug_client) {
1760                         clock_gettime(CLOCK_REALTIME, &tp);
1761                         time = (tp.tv_sec * 1000000L) + (tp.tv_nsec / 1000);
1762
1763                         fprintf(stderr, "[%7u.%03u] discarded [%s]@%d.[event %d]"
1764                                 "(%d fd, %d byte)\n",
1765                                 time / 1000, time % 1000,
1766                                 zombie ? "zombie" : "unknown",
1767                                 id, opcode,
1768                                 num_zombie_fds, size);
1769                 }
1770                 if (num_zombie_fds > 0)
1771                         wl_connection_close_fds_in(display->connection,
1772                                                    num_zombie_fds);
1773
1774                 wl_connection_consume(display->connection, size);
1775                 return size;
1776         }
1777
1778         if (opcode >= proxy->object.interface->event_count) {
1779                 wl_log("interface '%s' has no event %u\n",
1780                        proxy->object.interface->name, opcode);
1781                 return -1;
1782         }
1783
1784         message = &proxy->object.interface->events[opcode];
1785         closure = wl_connection_demarshal(display->connection, size,
1786                                           &display->objects, message);
1787         if (!closure) {
1788                 wl_log("wl_connection_demarshal failed\n");
1789                 return -1;
1790         }
1791
1792         if (create_proxies(proxy, closure) < 0) {
1793                 wl_log("create_proxies failed\n");
1794                 wl_closure_destroy(closure);
1795                 return -1;
1796         }
1797
1798         if (wl_closure_lookup_objects(closure, &display->objects) != 0) {
1799                 wl_log("wl_closure_lookup_objects failed\n");
1800                 wl_closure_destroy(closure);
1801                 return -1;
1802         }
1803
1804         closure->proxy = proxy;
1805         increase_closure_args_refcount(closure);
1806
1807         if (proxy == &display->proxy)
1808                 queue = &display->display_queue;
1809         else
1810                 queue = proxy->queue;
1811
1812 #ifdef WL_DEBUG_QUEUE
1813         if (debug_client) {
1814                 wl_dlog("display_q(%p) default_q(%p) queue(%p) add event", &display->display_queue, &display->default_queue, queue);
1815                 wl_closure_print(closure, &proxy->object, false);
1816         }
1817 #endif
1818         if (!queue)
1819                 wl_abort("Tried to add event to destroyed queue\n");
1820
1821         wl_list_insert(queue->event_list.prev, &closure->link);
1822
1823         return size;
1824 }
1825
1826 static uint32_t
1827 id_from_object(union wl_argument *arg)
1828 {
1829         struct wl_proxy *proxy;
1830
1831         if (arg->o) {
1832                 proxy = (struct wl_proxy *)arg->o;
1833                 return proxy->object.id;
1834         }
1835
1836         return 0;
1837 }
1838
1839 static void
1840 dispatch_event(struct wl_display *display, struct wl_event_queue *queue)
1841 {
1842         struct wl_closure *closure;
1843         struct wl_proxy *proxy;
1844         int opcode;
1845         bool proxy_destroyed;
1846
1847         closure = wl_container_of(queue->event_list.next, closure, link);
1848         wl_list_remove(&closure->link);
1849         opcode = closure->opcode;
1850
1851         /* Verify that the receiving object is still valid by checking if has
1852          * been destroyed by the application. */
1853         validate_closure_objects(closure);
1854         proxy = closure->proxy;
1855         proxy_destroyed = !!(proxy->flags & WL_PROXY_FLAG_DESTROYED);
1856         if (proxy_destroyed) {
1857                 if (debug_client)
1858                         wl_closure_print(closure, &proxy->object, false, true, id_from_object);
1859                 destroy_queued_closure(closure);
1860                 return;
1861         }
1862
1863         pthread_mutex_unlock(&display->mutex);
1864
1865         if (proxy->dispatcher) {
1866                 if (debug_client)
1867                         wl_closure_print(closure, &proxy->object, false, false, id_from_object);
1868
1869                 wl_closure_dispatch(closure, proxy->dispatcher,
1870                                     &proxy->object, opcode);
1871         } else if (proxy->object.implementation) {
1872                 if (debug_client)
1873                         wl_closure_print(closure, &proxy->object, false, false, id_from_object);
1874
1875                 wl_closure_invoke(closure, WL_CLOSURE_INVOKE_CLIENT,
1876                                   &proxy->object, opcode, proxy->user_data);
1877         }
1878
1879         pthread_mutex_lock(&display->mutex);
1880
1881         destroy_queued_closure(closure);
1882 }
1883
1884 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
1885 static void
1886 force_sync_callback(void *data, struct wl_callback *callback, uint32_t serial)
1887 {
1888         wl_callback_destroy(callback);
1889         wl_log("[force_sync_callback] serial=%d\n", serial);
1890 }
1891
1892 static const struct wl_callback_listener force_sync_listener = {
1893         force_sync_callback
1894 };
1895
1896 static int
1897 force_display_sync(struct wl_display *display)
1898 {
1899         struct wl_callback *callback;
1900         int ret = 0;
1901
1902         pthread_mutex_unlock(&display->mutex);
1903
1904         callback = wl_display_sync(display);
1905
1906         if (!callback)
1907         {
1908                 wl_log("[force_display_sync] failed to get a callback (display:%p)!\n", display);
1909                 return -2;
1910         }
1911
1912         wl_callback_add_listener(callback, &force_sync_listener, NULL);
1913
1914         pthread_mutex_lock(&display->mutex);
1915
1916         if (display->last_error)
1917                 wl_log("[force_display_sync] display:%p, last_error:%d, errno:%d\n", display, display->last_error, errno);
1918
1919         /* We don't make EPIPE a fatal error here, so that we may try to
1920          * read events after the failed flush. When the compositor sends
1921          * an error it will close the socket, and if we make EPIPE fatal
1922          * here we don't get a chance to process the error. */
1923         ret = wl_connection_flush(display->connection);
1924         if (ret < 0 && errno != EAGAIN && errno != EPIPE)
1925                 display_fatal_error(display, errno);
1926
1927         if (ret < 0)
1928                 wl_log("[force_display_sync] error on flushing display (display:%p, ret:%d, errno:%d)\n", display, ret, errno);
1929
1930         return ret;
1931 }
1932 // END
1933
1934 static int
1935 read_events(struct wl_display *display)
1936 {
1937         int total, rem, size;
1938         uint32_t serial;
1939
1940 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
1941         struct timeval now;
1942         struct timespec ts;
1943         int ret = 0, res = 0;
1944 // END
1945
1946         display->reader_count--;
1947         if (display->reader_count == 0) {
1948                 total = wl_connection_read(display->connection);
1949                 if (total < 0 && errno != EAGAIN && errno != EPIPE)
1950                         wl_log("read failed: total(%d) errno(%d), display(%p)", total, errno, display);
1951                 if (total == -1) {
1952                         if (errno == EAGAIN) {
1953                                 /* we must wake up threads whenever
1954                                  * the reader_count dropped to 0 */
1955                                 display_wakeup_threads(display);
1956
1957                                 return 0;
1958                         }
1959
1960                         wl_log("errno(%d)\n", errno);
1961                         display_fatal_error(display, errno);
1962                         return -1;
1963                 } else if (total == 0) {
1964                         /* The compositor has closed the socket. This
1965                          * should be considered an error so we'll fake
1966                          * an errno */
1967                         errno = EPIPE;
1968                         display_fatal_error(display, errno);
1969                         wl_log("pipe error\n");
1970                         return -1;
1971                 }
1972
1973                 for (rem = total; rem >= 8; rem -= size) {
1974                         size = queue_event(display, rem);
1975                         if (size == -1) {
1976                                 wl_log("queue_event failed\n");
1977                                 display_fatal_error(display, errno);
1978                                 return -1;
1979                         } else if (size == 0) {
1980                                 break;
1981                         }
1982                 }
1983
1984                 display_wakeup_threads(display);
1985         } else {
1986                 serial = display->read_serial;
1987                 while (display->read_serial == serial)
1988 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
1989                 {
1990                         gettimeofday(&now, NULL);
1991
1992                         ts.tv_nsec = now.tv_usec * 1000;
1993                         ts.tv_sec = now.tv_sec + WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT;// 10 seconds
1994
1995                         ret = pthread_cond_timedwait(&display->reader_cond,
1996                                           &display->mutex, &ts);
1997
1998                         if (ETIMEDOUT == ret)
1999                         {
2000                                 wl_log("=== Timeout on pthread_cond_timedwait. Start leaving data (timeout=%d)!===\n", WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT);
2001                                 wl_log("[read events] display->read_serial : %d, serial : %d\n", display->read_serial, serial);
2002                                 wl_log("=== Timeout on pthread_cond_timedwait. End of data leaving !===\n");
2003
2004                                 wl_log("=== FORCE_DISPLAY_SYNC BEGIN ===\n");
2005
2006                                 res = force_display_sync(display);
2007                                 display->force_sync_count++;
2008
2009                                 wl_log("=== FORCE_DISPLAY_SYNC DONE (res=%d, force_sync_count=%d) ===\n", res, display->force_sync_count);
2010
2011                                 /* return if there is any error on doing display sync and leave display protocol error if exits */
2012                                 if (res < 0)
2013                                 {
2014                                         wl_log("=== FORCE_DISPLAY_SYNC ERROR (res=%d) ===\n", res);
2015
2016                                         if (display->last_error)
2017                                         {
2018                                                 wl_log("[read_events] display:%p, last_error:%d\n", display, display->last_error);
2019                                                 display_print_protocol_error_information(display, display->last_error);
2020
2021                                                 wl_log("[WL_ERRNO_SET][FUNC:%s][LINE:%d] errno (%d -> %d), display:%p\n", __FUNCTION__, __LINE__, errno, display->last_error, display);
2022                                                 errno = display->last_error;
2023                                         }
2024
2025                                         return -1;
2026                                 }
2027                         }
2028                         else if (ret)
2029                         {
2030                                 wl_log("=== Error waiting pthread_cond_timedwait : continue, errno(%d) ===\n", ret);
2031                         }
2032                 }
2033 // END
2034
2035                 if (display->last_error) {
2036                         errno = display->last_error;
2037                         return -1;
2038                 }
2039         }
2040
2041         return 0;
2042 }
2043
2044 static void
2045 cancel_read(struct wl_display *display)
2046 {
2047         display->reader_count--;
2048         if (display->reader_count == 0)
2049                 display_wakeup_threads(display);
2050 }
2051
2052 /** Read events from display file descriptor
2053  *
2054  * \param display The display context object
2055  * \return 0 on success or -1 on error.  In case of error errno will
2056  * be set accordingly
2057  *
2058  * Calling this function will result in data available on the display file
2059  * descriptor being read and read events will be queued on their corresponding
2060  * event queues.
2061  *
2062  * Before calling this function, depending on what thread it is to be called
2063  * from, wl_display_prepare_read_queue() or wl_display_prepare_read() needs to
2064  * be called. See wl_display_prepare_read_queue() for more details.
2065  *
2066  * When being called at a point where other threads have been prepared to read
2067  * (using wl_display_prepare_read_queue() or wl_display_prepare_read()) this
2068  * function will sleep until all other prepared threads have either been
2069  * cancelled (using wl_display_cancel_read()) or them self entered this
2070  * function. The last thread that calls this function will then read and queue
2071  * events on their corresponding event queues, and finally wake up all other
2072  * wl_display_read_events() calls causing them to return.
2073  *
2074  * If a thread cancels a read preparation when all other threads that have
2075  * prepared to read has either called wl_display_cancel_read() or
2076  * wl_display_read_events(), all reader threads will return without having read
2077  * any data.
2078  *
2079  * To dispatch events that may have been queued, call
2080  * wl_display_dispatch_pending() or wl_display_dispatch_queue_pending().
2081  *
2082  * \sa wl_display_prepare_read(), wl_display_cancel_read(),
2083  * wl_display_dispatch_pending(), wl_display_dispatch()
2084  *
2085  * \memberof wl_display
2086  */
2087 WL_EXPORT int
2088 wl_display_read_events(struct wl_display *display)
2089 {
2090         int ret;
2091
2092         pthread_mutex_lock(&display->mutex);
2093
2094         if (display->last_error) {
2095                 cancel_read(display);
2096                 pthread_mutex_unlock(&display->mutex);
2097
2098                 errno = display->last_error;
2099                 return -1;
2100         }
2101
2102         ret = read_events(display);
2103
2104         pthread_mutex_unlock(&display->mutex);
2105
2106         return ret;
2107 }
2108
2109 static int
2110 dispatch_queue(struct wl_display *display, struct wl_event_queue *queue)
2111 {
2112         int count;
2113
2114         if (display->last_error)
2115                 goto err;
2116
2117         count = 0;
2118         while (!wl_list_empty(&display->display_queue.event_list)) {
2119                 dispatch_event(display, &display->display_queue);
2120                 if (display->last_error)
2121                         goto err;
2122                 count++;
2123         }
2124
2125         while (!wl_list_empty(&queue->event_list)) {
2126                 dispatch_event(display, queue);
2127                 if (display->last_error)
2128                         goto err;
2129                 count++;
2130         }
2131
2132         return count;
2133
2134 err:
2135         errno = display->last_error;
2136
2137         return -1;
2138 }
2139
2140 /** Prepare to read events from the display's file descriptor to a queue
2141  *
2142  * \param display The display context object
2143  * \param queue The event queue to use
2144  * \return 0 on success or -1 if event queue was not empty
2145  *
2146  * This function (or wl_display_prepare_read()) must be called before reading
2147  * from the file descriptor using wl_display_read_events(). Calling
2148  * wl_display_prepare_read_queue() announces the calling thread's intention to
2149  * read and ensures that until the thread is ready to read and calls
2150  * wl_display_read_events(), no other thread will read from the file descriptor.
2151  * This only succeeds if the event queue is empty, and if not -1 is returned and
2152  * errno set to EAGAIN.
2153  *
2154  * If a thread successfully calls wl_display_prepare_read_queue(), it must
2155  * either call wl_display_read_events() when it's ready or cancel the read
2156  * intention by calling wl_display_cancel_read().
2157  *
2158  * Use this function before polling on the display fd or integrate the fd into a
2159  * toolkit event loop in a race-free way. A correct usage would be (with most
2160  * error checking left out):
2161  *
2162  * \code
2163  * while (wl_display_prepare_read_queue(display, queue) != 0)
2164  *         wl_display_dispatch_queue_pending(display, queue);
2165  * wl_display_flush(display);
2166  *
2167  * ret = poll(fds, nfds, -1);
2168  * if (has_error(ret))
2169  *         wl_display_cancel_read(display);
2170  * else
2171  *         wl_display_read_events(display);
2172  *
2173  * wl_display_dispatch_queue_pending(display, queue);
2174  * \endcode
2175  *
2176  * Here we call wl_display_prepare_read_queue(), which ensures that between
2177  * returning from that call and eventually calling wl_display_read_events(), no
2178  * other thread will read from the fd and queue events in our queue. If the call
2179  * to wl_display_prepare_read_queue() fails, we dispatch the pending events and
2180  * try again until we're successful.
2181  *
2182  * The wl_display_prepare_read_queue() function doesn't acquire exclusive access
2183  * to the display's fd. It only registers that the thread calling this function
2184  * has intention to read from fd. When all registered readers call
2185  * wl_display_read_events(), only one (at random) eventually reads and queues
2186  * the events and the others are sleeping meanwhile. This way we avoid races and
2187  * still can read from more threads.
2188  *
2189  * \sa wl_display_cancel_read(), wl_display_read_events(),
2190  * wl_display_prepare_read()
2191  *
2192  * \memberof wl_display
2193  */
2194 WL_EXPORT int
2195 wl_display_prepare_read_queue(struct wl_display *display,
2196                               struct wl_event_queue *queue)
2197 {
2198         int ret;
2199
2200         pthread_mutex_lock(&display->mutex);
2201
2202         if (!wl_list_empty(&queue->event_list)) {
2203                 errno = EAGAIN;
2204                 ret = -1;
2205         } else {
2206                 display->reader_count++;
2207                 ret = 0;
2208         }
2209
2210         pthread_mutex_unlock(&display->mutex);
2211
2212         return ret;
2213 }
2214
2215 /** Prepare to read events from the display's file descriptor
2216  *
2217  * \param display The display context object
2218  * \return 0 on success or -1 if event queue was not empty
2219  *
2220  * This function does the same thing as wl_display_prepare_read_queue()
2221  * with the default queue passed as the queue.
2222  *
2223  * \sa wl_display_prepare_read_queue
2224  * \memberof wl_display
2225  */
2226 WL_EXPORT int
2227 wl_display_prepare_read(struct wl_display *display)
2228 {
2229         return wl_display_prepare_read_queue(display, &display->default_queue);
2230 }
2231
2232 /** Cancel read intention on display's fd
2233  *
2234  * \param display The display context object
2235  *
2236  * After a thread successfully called wl_display_prepare_read() it must
2237  * either call wl_display_read_events() or wl_display_cancel_read().
2238  * If the threads do not follow this rule it will lead to deadlock.
2239  *
2240  * \sa wl_display_prepare_read(), wl_display_read_events()
2241  *
2242  * \memberof wl_display
2243  */
2244 WL_EXPORT void
2245 wl_display_cancel_read(struct wl_display *display)
2246 {
2247         pthread_mutex_lock(&display->mutex);
2248
2249         cancel_read(display);
2250
2251         pthread_mutex_unlock(&display->mutex);
2252 }
2253
2254 static int
2255 wl_display_poll(struct wl_display *display, short int events)
2256 {
2257         int ret;
2258         struct pollfd pfd[1];
2259
2260         pfd[0].fd = display->fd;
2261         pfd[0].events = events;
2262         do {
2263                 ret = poll(pfd, 1, -1);
2264         } while (ret == -1 && errno == EINTR);
2265
2266         return ret;
2267 }
2268
2269 /** Dispatch events in an event queue
2270  *
2271  * \param display The display context object
2272  * \param queue The event queue to dispatch
2273  * \return The number of dispatched events on success or -1 on failure
2274  *
2275  * Dispatch events on the given event queue.
2276  *
2277  * If the given event queue is empty, this function blocks until there are
2278  * events to be read from the display fd. Events are read and queued on
2279  * the appropriate event queues. Finally, events on given event queue are
2280  * dispatched. On failure -1 is returned and errno set appropriately.
2281  *
2282  * In a multi threaded environment, do not manually wait using poll() (or
2283  * equivalent) before calling this function, as doing so might cause a dead
2284  * lock. If external reliance on poll() (or equivalent) is required, see
2285  * wl_display_prepare_read_queue() of how to do so.
2286  *
2287  * This function is thread safe as long as it dispatches the right queue on the
2288  * right thread. It is also compatible with the multi thread event reading
2289  * preparation API (see wl_display_prepare_read_queue()), and uses the
2290  * equivalent functionality internally. It is not allowed to call this function
2291  * while the thread is being prepared for reading events, and doing so will
2292  * cause a dead lock.
2293  *
2294  * It can be used as a helper function to ease the procedure of reading and
2295  * dispatching events.
2296  *
2297  * \note Since Wayland 1.5 the display has an extra queue
2298  * for its own events (i. e. delete_id). This queue is dispatched always,
2299  * no matter what queue we passed as an argument to this function.
2300  * That means that this function can return non-0 value even when it
2301  * haven't dispatched any event for the given queue.
2302  *
2303  * \sa wl_display_dispatch(), wl_display_dispatch_pending(),
2304  * wl_display_dispatch_queue_pending(), wl_display_prepare_read_queue()
2305  *
2306  * \memberof wl_display
2307  */
2308 WL_EXPORT int
2309 wl_display_dispatch_queue(struct wl_display *display,
2310                           struct wl_event_queue *queue)
2311 {
2312         int ret;
2313
2314         if (wl_display_prepare_read_queue(display, queue) == -1)
2315                 return wl_display_dispatch_queue_pending(display, queue);
2316
2317         while (true) {
2318                 ret = wl_display_flush(display);
2319
2320                 if (ret != -1 || errno != EAGAIN)
2321                         break;
2322
2323                 if (wl_display_poll(display, POLLOUT) == -1) {
2324                         wl_display_cancel_read(display);
2325                         wl_log("wl_display_poll failed (display:%p)\n", display);
2326                         return -1;
2327                 }
2328         }
2329
2330         /* Don't stop if flushing hits an EPIPE; continue so we can read any
2331          * protocol error that may have triggered it. */
2332         if (ret < 0 && errno != EPIPE) {
2333                 display_print_protocol_error_information(display, errno);
2334                 wl_display_cancel_read(display);
2335                 return -1;
2336         }
2337
2338         if (wl_display_poll(display, POLLIN) == -1) {
2339                 wl_log("wl_display_poll failed (display:%p)\n", display);
2340                 wl_display_cancel_read(display);
2341                 return -1;
2342         }
2343
2344         if (wl_display_read_events(display) == -1) {
2345                 wl_log("wl_display_read_events failed (display:%p)\n", display);
2346                 return -1;
2347         }
2348
2349         ret = wl_display_dispatch_queue_pending(display, queue);
2350
2351         if (ret < 0)
2352                 wl_log("wl_display_dispatch_queue_pending failed (display:%p)\n", display);
2353
2354         return ret;
2355 }
2356
2357 /** Dispatch pending events in an event queue
2358  *
2359  * \param display The display context object
2360  * \param queue The event queue to dispatch
2361  * \return The number of dispatched events on success or -1 on failure
2362  *
2363  * Dispatch all incoming events for objects assigned to the given
2364  * event queue. On failure -1 is returned and errno set appropriately.
2365  * If there are no events queued, this function returns immediately.
2366  *
2367  * \memberof wl_display
2368  * \since 1.0.2
2369  */
2370 WL_EXPORT int
2371 wl_display_dispatch_queue_pending(struct wl_display *display,
2372                                   struct wl_event_queue *queue)
2373 {
2374         int ret;
2375
2376         pthread_mutex_lock(&display->mutex);
2377
2378         ret = dispatch_queue(display, queue);
2379
2380         pthread_mutex_unlock(&display->mutex);
2381
2382         return ret;
2383 }
2384
2385 /** Process incoming events
2386  *
2387  * \param display The display context object
2388  * \return The number of dispatched events on success or -1 on failure
2389  *
2390  * Dispatch events on the default event queue.
2391  *
2392  * If the default event queue is empty, this function blocks until there are
2393  * events to be read from the display fd. Events are read and queued on
2394  * the appropriate event queues. Finally, events on the default event queue
2395  * are dispatched. On failure -1 is returned and errno set appropriately.
2396  *
2397  * In a multi threaded environment, do not manually wait using poll() (or
2398  * equivalent) before calling this function, as doing so might cause a dead
2399  * lock. If external reliance on poll() (or equivalent) is required, see
2400  * wl_display_prepare_read_queue() of how to do so.
2401  *
2402  * This function is thread safe as long as it dispatches the right queue on the
2403  * right thread. It is also compatible with the multi thread event reading
2404  * preparation API (see wl_display_prepare_read_queue()), and uses the
2405  * equivalent functionality internally. It is not allowed to call this function
2406  * while the thread is being prepared for reading events, and doing so will
2407  * cause a dead lock.
2408  *
2409  * \note It is not possible to check if there are events on the queue
2410  * or not. For dispatching default queue events without blocking, see \ref
2411  * wl_display_dispatch_pending().
2412  *
2413  * \sa wl_display_dispatch_pending(), wl_display_dispatch_queue(),
2414  * wl_display_read_events()
2415  *
2416  * \memberof wl_display
2417  */
2418 WL_EXPORT int
2419 wl_display_dispatch(struct wl_display *display)
2420 {
2421         return wl_display_dispatch_queue(display, &display->default_queue);
2422 }
2423
2424 /** Dispatch default queue events without reading from the display fd
2425  *
2426  * \param display The display context object
2427  * \return The number of dispatched events or -1 on failure
2428  *
2429  * This function dispatches events on the main event queue. It does not
2430  * attempt to read the display fd and simply returns zero if the main
2431  * queue is empty, i.e., it doesn't block.
2432  *
2433  * \sa wl_display_dispatch(), wl_display_dispatch_queue(),
2434  * wl_display_flush()
2435  *
2436  * \memberof wl_display
2437  */
2438 WL_EXPORT int
2439 wl_display_dispatch_pending(struct wl_display *display)
2440 {
2441         return wl_display_dispatch_queue_pending(display,
2442                                                  &display->default_queue);
2443 }
2444
2445 /** Retrieve the last error that occurred on a display
2446  *
2447  * \param display The display context object
2448  * \return The last error that occurred on \c display or 0 if no error occurred
2449  *
2450  * Return the last error that occurred on the display. This may be an error sent
2451  * by the server or caused by the local client.
2452  *
2453  * \note Errors are \b fatal. If this function returns non-zero the display
2454  * can no longer be used.
2455  *
2456  * \memberof wl_display
2457  */
2458 WL_EXPORT int
2459 wl_display_get_error(struct wl_display *display)
2460 {
2461         int ret;
2462
2463         pthread_mutex_lock(&display->mutex);
2464
2465         ret = display->last_error;
2466
2467         pthread_mutex_unlock(&display->mutex);
2468
2469         return ret;
2470 }
2471
2472 /** Retrieves the information about a protocol error:
2473  *
2474  * \param display    The Wayland display
2475  * \param interface  if not NULL, stores the interface where the error occurred,
2476  *                   or NULL, if unknown.
2477  * \param id         if not NULL, stores the object id that generated
2478  *                   the error, or 0, if the object id is unknown. There's no
2479  *                   guarantee the object is still valid; the client must know
2480  *                   if it deleted the object.
2481  * \return           The error code as defined in the interface specification.
2482  *
2483  * \code
2484  * int err = wl_display_get_error(display);
2485  *
2486  * if (err == EPROTO) {
2487  *        code = wl_display_get_protocol_error(display, &interface, &id);
2488  *        handle_error(code, interface, id);
2489  * }
2490  *
2491  * ...
2492  * \endcode
2493  * \memberof wl_display
2494  */
2495 WL_EXPORT uint32_t
2496 wl_display_get_protocol_error(struct wl_display *display,
2497                               const struct wl_interface **interface,
2498                               uint32_t *id)
2499 {
2500         uint32_t ret;
2501
2502         pthread_mutex_lock(&display->mutex);
2503
2504         ret = display->protocol_error.code;
2505
2506         if (interface)
2507                 *interface = display->protocol_error.interface;
2508         if (id)
2509                 *id = display->protocol_error.id;
2510
2511         pthread_mutex_unlock(&display->mutex);
2512
2513         return ret;
2514 }
2515
2516
2517 /** Send all buffered requests on the display to the server
2518  *
2519  * \param display The display context object
2520  * \return The number of bytes sent on success or -1 on failure
2521  *
2522  * Send all buffered data on the client side to the server. Clients should
2523  * always call this function before blocking on input from the display fd.
2524  * On success, the number of bytes sent to the server is returned. On
2525  * failure, this function returns -1 and errno is set appropriately.
2526  *
2527  * wl_display_flush() never blocks.  It will write as much data as
2528  * possible, but if all data could not be written, errno will be set
2529  * to EAGAIN and -1 returned.  In that case, use poll on the display
2530  * file descriptor to wait for it to become writable again.
2531  *
2532  * \memberof wl_display
2533  */
2534 WL_EXPORT int
2535 wl_display_flush(struct wl_display *display)
2536 {
2537         int ret;
2538
2539         pthread_mutex_lock(&display->mutex);
2540
2541         if (display->last_error) {
2542                 errno = display->last_error;
2543                 ret = -1;
2544         } else {
2545                 /* We don't make EPIPE a fatal error here, so that we may try to
2546                  * read events after the failed flush. When the compositor sends
2547                  * an error it will close the socket, and if we make EPIPE fatal
2548                  * here we don't get a chance to process the error. */
2549                 ret = wl_connection_flush(display->connection);
2550                 if (ret < 0 && errno != EAGAIN && errno != EPIPE)
2551                         display_fatal_error(display, errno);
2552         }
2553
2554         pthread_mutex_unlock(&display->mutex);
2555
2556         return ret;
2557 }
2558
2559 /** Set the user data associated with a proxy
2560  *
2561  * \param proxy The proxy object
2562  * \param user_data The data to be associated with proxy
2563  *
2564  * Set the user data associated with \c proxy. When events for this
2565  * proxy are received, \c user_data will be supplied to its listener.
2566  *
2567  * \memberof wl_proxy
2568  */
2569 WL_EXPORT void
2570 wl_proxy_set_user_data(struct wl_proxy *proxy, void *user_data)
2571 {
2572         struct wl_display *display = proxy->display;
2573
2574         pthread_mutex_lock(&display->mutex);
2575         proxy->user_data = user_data;
2576         pthread_mutex_unlock(&display->mutex);
2577 }
2578
2579 /** Get the user data associated with a proxy
2580  *
2581  * \param proxy The proxy object
2582  * \return The user data associated with proxy
2583  *
2584  * \memberof wl_proxy
2585  */
2586 WL_EXPORT void *
2587 wl_proxy_get_user_data(struct wl_proxy *proxy)
2588 {
2589         struct wl_display *display = proxy->display;
2590         void *user_data;
2591
2592         pthread_mutex_lock(&display->mutex);
2593         user_data = proxy->user_data;
2594         pthread_mutex_unlock(&display->mutex);
2595
2596         return user_data;
2597 }
2598
2599 /** Get the protocol object version of a proxy object
2600  *
2601  * \param proxy The proxy object
2602  * \return The protocol object version of the proxy or 0
2603  *
2604  * Gets the protocol object version of a proxy object, or 0
2605  * if the proxy was created with unversioned API.
2606  *
2607  * A returned value of 0 means that no version information is
2608  * available, so the caller must make safe assumptions about
2609  * the object's real version.
2610  *
2611  * wl_display's version will always return 0.
2612  *
2613  * \memberof wl_proxy
2614  */
2615 WL_EXPORT uint32_t
2616 wl_proxy_get_version(struct wl_proxy *proxy)
2617 {
2618         struct wl_display *display = proxy->display;
2619         uint32_t version;
2620
2621         pthread_mutex_lock(&display->mutex);
2622         version = proxy->version;
2623         pthread_mutex_unlock(&display->mutex);
2624
2625         return version;
2626 }
2627
2628 /** Get the id of a proxy object
2629  *
2630  * \param proxy The proxy object
2631  * \return The id the object associated with the proxy
2632  *
2633  * \memberof wl_proxy
2634  */
2635 WL_EXPORT uint32_t
2636 wl_proxy_get_id(struct wl_proxy *proxy)
2637 {
2638         struct wl_display *display = proxy->display;
2639         uint32_t id;
2640
2641         pthread_mutex_lock(&display->mutex);
2642         id = proxy->object.id;
2643         pthread_mutex_unlock(&display->mutex);
2644
2645         return id;
2646 }
2647
2648 /** Set the tag of a proxy object
2649  *
2650  * A toolkit or application can set a unique tag on a proxy in order to
2651  * identify whether an object is managed by itself or some external part.
2652  *
2653  * To create a tag, the recommended way is to define a statically allocated
2654  * constant char array containing some descriptive string. The tag will be the
2655  * pointer to the non-const pointer to the beginning of the array.
2656  *
2657  * For example, to define and set a tag on a surface managed by a certain
2658  * subsystem:
2659  *
2660  *      static const char *my_tag = "my tag";
2661  *
2662  *      wl_proxy_set_tag((struct wl_proxy *) surface, &my_tag);
2663  *
2664  * Then, in a callback with wl_surface as an argument, in order to check
2665  * whether it's a surface managed by the same subsystem.
2666  *
2667  *      const char * const *tag;
2668  *
2669  *      tag = wl_proxy_get_tag((struct wl_proxy *) surface);
2670  *      if (tag != &my_tag)
2671  *              return;
2672  *
2673  *      ...
2674  *
2675  * For debugging purposes, a tag should be suitable to be included in a debug
2676  * log entry, e.g.
2677  *
2678  *      const char * const *tag;
2679  *
2680  *      tag = wl_proxy_get_tag((struct wl_proxy *) surface);
2681  *      printf("Got a surface with the tag %p (%s)\n",
2682  *             tag, (tag && *tag) ? *tag : "");
2683  *
2684  * \param proxy The proxy object
2685  * \param tag The tag
2686  *
2687  * \memberof wl_proxy
2688  * \since 1.17.90
2689  */
2690 WL_EXPORT void
2691 wl_proxy_set_tag(struct wl_proxy *proxy,
2692                  const char * const *tag)
2693 {
2694         proxy->tag = tag;
2695 }
2696
2697 /** Get the tag of a proxy object
2698  *
2699  * See wl_proxy_set_tag for details.
2700  *
2701  * \param proxy The proxy object
2702  *
2703  * \memberof wl_proxy
2704  * \since 1.17.90
2705  */
2706 WL_EXPORT const char * const *
2707 wl_proxy_get_tag(struct wl_proxy *proxy)
2708 {
2709         return proxy->tag;
2710 }
2711
2712 /** Get the interface name (class) of a proxy object
2713  *
2714  * \param proxy The proxy object
2715  * \return The interface name of the object associated with the proxy
2716  *
2717  * \memberof wl_proxy
2718  */
2719 WL_EXPORT const char *
2720 wl_proxy_get_class(struct wl_proxy *proxy)
2721 {
2722         struct wl_display *display = proxy->display;
2723         const char *name;
2724
2725         pthread_mutex_lock(&display->mutex);
2726         name = proxy->object.interface->name;
2727         pthread_mutex_unlock(&display->mutex);
2728
2729         return name;
2730 }
2731
2732 /** Assign a proxy to an event queue
2733  *
2734  * \param proxy The proxy object
2735  * \param queue The event queue that will handle this proxy or NULL
2736  *
2737  * Assign proxy to event queue. Events coming from \c proxy will be
2738  * queued in \c queue from now. If queue is NULL, then the display's
2739  * default queue is set to the proxy.
2740  *
2741  * In order to guarantee proper handing of all events which were queued
2742  * before the queue change takes effect, it is required to dispatch the
2743  * proxy's old event queue after setting a new event queue.
2744  *
2745  * This is particularly important for multi-threaded setups, where it is
2746  * possible for events to be queued to the proxy's old queue from a
2747  * different thread during the invocation of this function.
2748  *
2749  * To ensure that all events for a newly created proxy are dispatched
2750  * on a particular queue, it is necessary to use a proxy wrapper if
2751  * events are read and dispatched on more than one thread. See
2752  * wl_proxy_create_wrapper() for more details.
2753  *
2754  * \note By default, the queue set in proxy is the one inherited from parent.
2755  *
2756  * \sa wl_display_dispatch_queue()
2757  *
2758  * \memberof wl_proxy
2759  */
2760 WL_EXPORT void
2761 wl_proxy_set_queue(struct wl_proxy *proxy, struct wl_event_queue *queue)
2762 {
2763         struct wl_display *display = proxy->display;
2764
2765         pthread_mutex_lock(&display->mutex);
2766         
2767         wl_list_remove(&proxy->queue_link);
2768
2769         if (queue) {
2770                 assert(proxy->display == queue->display);
2771                 proxy->queue = queue;
2772         } else {
2773                 proxy->queue = &proxy->display->default_queue;
2774         }
2775
2776         wl_list_insert(&proxy->queue->proxy_list, &proxy->queue_link);
2777
2778         pthread_mutex_unlock(&display->mutex);
2779 }
2780
2781 /** Create a proxy wrapper for making queue assignments thread-safe
2782  *
2783  * \param proxy The proxy object to be wrapped
2784  * \return A proxy wrapper for the given proxy or NULL on failure
2785  *
2786  * A proxy wrapper is type of 'struct wl_proxy' instance that can be used when
2787  * sending requests instead of using the original proxy. A proxy wrapper does
2788  * not have an implementation or dispatcher, and events received on the
2789  * object is still emitted on the original proxy. Trying to set an
2790  * implementation or dispatcher will have no effect but result in a warning
2791  * being logged.
2792  *
2793  * Setting the proxy queue of the proxy wrapper will make new objects created
2794  * using the proxy wrapper use the set proxy queue.
2795  * Even though there is no implementation nor dispatcher, the proxy queue can
2796  * be changed. This will affect the default queue of new objects created by
2797  * requests sent via the proxy wrapper.
2798  *
2799  * A proxy wrapper can only be destroyed using wl_proxy_wrapper_destroy().
2800  *
2801  * A proxy wrapper must be destroyed before the proxy it was created from.
2802  *
2803  * If a user reads and dispatches events on more than one thread, it is
2804  * necessary to use a proxy wrapper when sending requests on objects when the
2805  * intention is that a newly created proxy is to use a proxy queue different
2806  * from the proxy the request was sent on, as creating the new proxy and then
2807  * setting the queue is not thread safe.
2808  *
2809  * For example, a module that runs using its own proxy queue that needs to
2810  * do display roundtrip must wrap the wl_display proxy object before sending
2811  * the wl_display.sync request. For example:
2812  *
2813  * \code
2814  *
2815  *   struct wl_event_queue *queue = ...;
2816  *   struct wl_display *wrapped_display;
2817  *   struct wl_callback *callback;
2818  *
2819  *   wrapped_display = wl_proxy_create_wrapper(display);
2820  *   wl_proxy_set_queue((struct wl_proxy *) wrapped_display, queue);
2821  *   callback = wl_display_sync(wrapped_display);
2822  *   wl_proxy_wrapper_destroy(wrapped_display);
2823  *   wl_callback_add_listener(callback, ...);
2824  *
2825  * \endcode
2826  *
2827  * \memberof wl_proxy
2828  */
2829 WL_EXPORT void *
2830 wl_proxy_create_wrapper(void *proxy)
2831 {
2832         struct wl_proxy *wrapped_proxy = proxy;
2833         struct wl_proxy *wrapper;
2834
2835         wrapper = zalloc(sizeof *wrapper);
2836         if (!wrapper)
2837                 return NULL;
2838
2839         pthread_mutex_lock(&wrapped_proxy->display->mutex);
2840
2841         wrapper->object.interface = wrapped_proxy->object.interface;
2842         wrapper->object.id = wrapped_proxy->object.id;
2843         wrapper->version = wrapped_proxy->version;
2844         wrapper->display = wrapped_proxy->display;
2845         wrapper->queue = wrapped_proxy->queue;
2846         wrapper->flags = WL_PROXY_FLAG_WRAPPER;
2847         wrapper->refcount = 1;
2848
2849         wl_list_insert(&wrapper->queue->proxy_list, &wrapper->queue_link);
2850
2851         pthread_mutex_unlock(&wrapped_proxy->display->mutex);
2852
2853         return wrapper;
2854 }
2855
2856 /** Destroy a proxy wrapper
2857  * \param proxy_wrapper The proxy wrapper to be destroyed
2858  *
2859  * \memberof wl_proxy
2860  */
2861 WL_EXPORT void
2862 wl_proxy_wrapper_destroy(void *proxy_wrapper)
2863 {
2864         struct wl_proxy *wrapper = proxy_wrapper;
2865         struct wl_display *display = wrapper->display;
2866
2867         if (!(wrapper->flags & WL_PROXY_FLAG_WRAPPER))
2868                 wl_abort("Tried to destroy non-wrapper proxy with "
2869                          "wl_proxy_wrapper_destroy\n");
2870
2871         assert(wrapper->refcount == 1);
2872
2873         pthread_mutex_lock(&display->mutex);
2874
2875         wrapper->flags |= WL_PROXY_FLAG_DESTROYED;
2876
2877         wl_list_remove(&wrapper->queue_link);
2878
2879         pthread_mutex_unlock(&display->mutex);
2880
2881         free(wrapper);
2882 }
2883
2884 WL_EXPORT void
2885 wl_log_set_handler_client(wl_log_func_t handler)
2886 {
2887         wl_log_handler = handler;
2888 }
2889
2890 //TIZEN_ONLY(20200516) : add APIs for setting/getting name of a display
2891 void
2892 wl_display_set_name(struct wl_display *display, char *name)
2893 {
2894         if (!display || !name)
2895                 return;
2896
2897         if (display->name)
2898                 free(display->name);
2899
2900         display->name = strdup(name);
2901 }
2902
2903 char *
2904 wl_display_get_name(struct wl_display *display)
2905 {
2906         if (!display)
2907                 return NULL;
2908
2909         return display->name;
2910 }
2911 // END
2912
2913 // TIZEN_ONLY(20230405) : Do not poll when flushing display fails if it's for roundtrip
2914 static int
2915 display_dispatch_queue_ensure_flush(struct wl_display *display,
2916                           struct wl_event_queue *queue)
2917 {
2918         int ret;
2919
2920         if (wl_display_prepare_read_queue(display, queue) == -1)
2921                 return wl_display_dispatch_queue_pending(display, queue);
2922
2923         while (true) {
2924                 ret = wl_display_flush(display);
2925
2926                 if (ret != -1 || errno != EAGAIN)
2927                         break;
2928
2929                 if (wl_display_poll(display, POLLOUT) == -1) {
2930                         wl_display_cancel_read(display);
2931                         wl_log("wl_display_poll failed (display:%p)\n", display);
2932                         return -1;
2933                 }
2934         }
2935
2936         if (ret < 0) {
2937                 wl_log("Error flushing display(%p) errno(%d, %m)", display, errno);
2938                 wl_display_cancel_read(display);
2939                 return -1;
2940         }
2941
2942         if (wl_display_poll(display, POLLIN) == -1) {
2943                 wl_log("wl_display_poll failed (display:%p)\n", display);
2944                 wl_display_cancel_read(display);
2945                 return -1;
2946         }
2947
2948         if (wl_display_read_events(display) == -1) {
2949                 wl_log("wl_display_read_events failed (display:%p)\n", display);
2950                 return -1;
2951         }
2952
2953         ret = wl_display_dispatch_queue_pending(display, queue);
2954
2955         if (ret < 0)
2956                 wl_log("wl_display_dispatch_queue_pending failed (display:%p)\n", display);
2957
2958         return ret;
2959 }
2960 // END