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