]> sigrok.org Git - libsigrok.git/blob - src/session.c
session: fix use after free of session->devs as reported by valgrind
[libsigrok.git] / src / session.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2015 Daniel Elstner <daniel.kitta@gmail.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <string.h>
27 #include <glib.h>
28 #include <libsigrok/libsigrok.h>
29 #include "libsigrok-internal.h"
30
31 /** @cond PRIVATE */
32 #define LOG_PREFIX "session"
33 /** @endcond */
34
35 /**
36  * @file
37  *
38  * Creating, using, or destroying libsigrok sessions.
39  */
40
41 /**
42  * @defgroup grp_session Session handling
43  *
44  * Creating, using, or destroying libsigrok sessions.
45  *
46  * @{
47  */
48
49 struct datafeed_callback {
50         sr_datafeed_callback cb;
51         void *cb_data;
52 };
53
54 /** Custom GLib event source for generic descriptor I/O.
55  * @see https://developer.gnome.org/glib/stable/glib-The-Main-Event-Loop.html
56  * @internal
57  */
58 struct fd_source {
59         GSource base;
60
61         int64_t timeout_us;
62         int64_t due_us;
63
64         /* Meta-data needed to keep track of installed sources */
65         struct sr_session *session;
66         void *key;
67
68         GPollFD pollfd;
69 };
70
71 /** FD event source prepare() method.
72  * This is called immediately before poll().
73  */
74 static gboolean fd_source_prepare(GSource *source, int *timeout)
75 {
76         int64_t now_us;
77         struct fd_source *fsource;
78         int remaining_ms;
79
80         fsource = (struct fd_source *)source;
81
82         if (fsource->timeout_us >= 0) {
83                 now_us = g_source_get_time(source);
84
85                 if (fsource->due_us == 0) {
86                         /* First-time initialization of the expiration time */
87                         fsource->due_us = now_us + fsource->timeout_us;
88                 }
89                 remaining_ms = (MAX(0, fsource->due_us - now_us) + 999) / 1000;
90         } else {
91                 remaining_ms = -1;
92         }
93         *timeout = remaining_ms;
94
95         return (remaining_ms == 0);
96 }
97
98 /** FD event source check() method.
99  * This is called after poll() returns to check whether an event fired.
100  */
101 static gboolean fd_source_check(GSource *source)
102 {
103         struct fd_source *fsource;
104         unsigned int revents;
105
106         fsource = (struct fd_source *)source;
107         revents = fsource->pollfd.revents;
108
109         return (revents != 0 || (fsource->timeout_us >= 0
110                         && fsource->due_us <= g_source_get_time(source)));
111 }
112
113 /** FD event source dispatch() method.
114  * This is called if either prepare() or check() returned TRUE.
115  */
116 static gboolean fd_source_dispatch(GSource *source,
117                 GSourceFunc callback, void *user_data)
118 {
119         struct fd_source *fsource;
120         unsigned int revents;
121         gboolean keep;
122
123         fsource = (struct fd_source *)source;
124         revents = fsource->pollfd.revents;
125
126         if (!callback) {
127                 sr_err("Callback not set, cannot dispatch event.");
128                 return G_SOURCE_REMOVE;
129         }
130         keep = (*(sr_receive_data_callback)callback)
131                         (fsource->pollfd.fd, revents, user_data);
132
133         if (fsource->timeout_us >= 0 && G_LIKELY(keep)
134                         && G_LIKELY(!g_source_is_destroyed(source)))
135                 fsource->due_us = g_source_get_time(source)
136                                 + fsource->timeout_us;
137         return keep;
138 }
139
140 /** FD event source finalize() method.
141  */
142 static void fd_source_finalize(GSource *source)
143 {
144         struct fd_source *fsource;
145
146         fsource = (struct fd_source *)source;
147
148         sr_dbg("%s: key %p", __func__, fsource->key);
149
150         sr_session_source_destroyed(fsource->session, fsource->key, source);
151 }
152
153 /** Create an event source for I/O on a file descriptor.
154  *
155  * In order to maintain API compatibility, this event source also doubles
156  * as a timer event source.
157  *
158  * @param session The session the event source belongs to.
159  * @param key The key used to identify this source.
160  * @param fd The file descriptor or HANDLE.
161  * @param timeout_ms The timeout interval in ms, or -1 to wait indefinitely.
162  * @return A new event source object, or NULL on failure.
163  */
164 static GSource *fd_source_new(struct sr_session *session, void *key,
165                 gintptr fd, int events, int timeout_ms)
166 {
167         static GSourceFuncs fd_source_funcs = {
168                 .prepare  = &fd_source_prepare,
169                 .check    = &fd_source_check,
170                 .dispatch = &fd_source_dispatch,
171                 .finalize = &fd_source_finalize
172         };
173         GSource *source;
174         struct fd_source *fsource;
175
176         source = g_source_new(&fd_source_funcs, sizeof(struct fd_source));
177         fsource = (struct fd_source *)source;
178
179         g_source_set_name(source, (fd < 0) ? "timer" : "fd");
180
181         if (timeout_ms >= 0) {
182                 fsource->timeout_us = 1000 * (int64_t)timeout_ms;
183                 fsource->due_us = 0;
184         } else {
185                 fsource->timeout_us = -1;
186                 fsource->due_us = INT64_MAX;
187         }
188         fsource->session = session;
189         fsource->key = key;
190
191         fsource->pollfd.fd = fd;
192         fsource->pollfd.events = events;
193         fsource->pollfd.revents = 0;
194
195         if (fd >= 0)
196                 g_source_add_poll(source, &fsource->pollfd);
197
198         return source;
199 }
200
201 /**
202  * Create a new session.
203  *
204  * @param ctx         The context in which to create the new session.
205  * @param new_session This will contain a pointer to the newly created
206  *                    session if the return value is SR_OK, otherwise the value
207  *                    is undefined and should not be used. Must not be NULL.
208  *
209  * @retval SR_OK Success.
210  * @retval SR_ERR_ARG Invalid argument.
211  *
212  * @since 0.4.0
213  */
214 SR_API int sr_session_new(struct sr_context *ctx,
215                 struct sr_session **new_session)
216 {
217         struct sr_session *session;
218
219         if (!new_session)
220                 return SR_ERR_ARG;
221
222         session = g_malloc0(sizeof(struct sr_session));
223
224         session->ctx = ctx;
225
226         g_mutex_init(&session->main_mutex);
227
228         /* To maintain API compatibility, we need a lookup table
229          * which maps poll_object IDs to GSource* pointers.
230          */
231         session->event_sources = g_hash_table_new(NULL, NULL);
232
233         *new_session = session;
234
235         return SR_OK;
236 }
237
238 /**
239  * Destroy a session.
240  * This frees up all memory used by the session.
241  *
242  * @param session The session to destroy. Must not be NULL.
243  *
244  * @retval SR_OK Success.
245  * @retval SR_ERR_ARG Invalid session passed.
246  *
247  * @since 0.4.0
248  */
249 SR_API int sr_session_destroy(struct sr_session *session)
250 {
251         if (!session) {
252                 sr_err("%s: session was NULL", __func__);
253                 return SR_ERR_ARG;
254         }
255
256         sr_session_dev_remove_all(session);
257         g_slist_free_full(session->owned_devs, (GDestroyNotify)sr_dev_inst_free);
258
259         g_hash_table_unref(session->event_sources);
260
261         g_mutex_clear(&session->main_mutex);
262
263         g_free(session);
264
265         return SR_OK;
266 }
267
268 /**
269  * Remove all the devices from a session.
270  *
271  * The session itself (i.e., the struct sr_session) is not free'd and still
272  * exists after this function returns.
273  *
274  * @param session The session to use. Must not be NULL.
275  *
276  * @retval SR_OK Success.
277  * @retval SR_ERR_BUG Invalid session passed.
278  *
279  * @since 0.4.0
280  */
281 SR_API int sr_session_dev_remove_all(struct sr_session *session)
282 {
283         struct sr_dev_inst *sdi;
284         GSList *l;
285
286         if (!session) {
287                 sr_err("%s: session was NULL", __func__);
288                 return SR_ERR_ARG;
289         }
290
291         for (l = session->devs; l; l = l->next) {
292                 sdi = (struct sr_dev_inst *) l->data;
293                 sdi->session = NULL;
294         }
295
296         g_slist_free(session->devs);
297         session->devs = NULL;
298
299         return SR_OK;
300 }
301
302 /**
303  * Add a device instance to a session.
304  *
305  * @param session The session to add to. Must not be NULL.
306  * @param sdi The device instance to add to a session. Must not
307  *            be NULL. Also, sdi->driver and sdi->driver->dev_open must
308  *            not be NULL.
309  *
310  * @retval SR_OK Success.
311  * @retval SR_ERR_ARG Invalid argument.
312  *
313  * @since 0.4.0
314  */
315 SR_API int sr_session_dev_add(struct sr_session *session,
316                 struct sr_dev_inst *sdi)
317 {
318         int ret;
319
320         if (!sdi) {
321                 sr_err("%s: sdi was NULL", __func__);
322                 return SR_ERR_ARG;
323         }
324
325         if (!session) {
326                 sr_err("%s: session was NULL", __func__);
327                 return SR_ERR_ARG;
328         }
329
330         /* If sdi->session is not NULL, the device is already in this or
331          * another session. */
332         if (sdi->session) {
333                 sr_err("%s: already assigned to session", __func__);
334                 return SR_ERR_ARG;
335         }
336
337         /* If sdi->driver is NULL, this is a virtual device. */
338         if (!sdi->driver) {
339                 /* Just add the device, don't run dev_open(). */
340                 session->devs = g_slist_append(session->devs, sdi);
341                 sdi->session = session;
342                 return SR_OK;
343         }
344
345         /* sdi->driver is non-NULL (i.e. we have a real device). */
346         if (!sdi->driver->dev_open) {
347                 sr_err("%s: sdi->driver->dev_open was NULL", __func__);
348                 return SR_ERR_BUG;
349         }
350
351         session->devs = g_slist_append(session->devs, sdi);
352         sdi->session = session;
353
354         /* TODO: This is invalid if the session runs in a different thread.
355          * The usage semantics and restrictions need to be documented.
356          */
357         if (session->running) {
358                 /* Adding a device to a running session. Commit settings
359                  * and start acquisition on that device now. */
360                 if ((ret = sr_config_commit(sdi)) != SR_OK) {
361                         sr_err("Failed to commit device settings before "
362                                "starting acquisition in running session (%s)",
363                                sr_strerror(ret));
364                         return ret;
365                 }
366                 if ((ret = sdi->driver->dev_acquisition_start(sdi,
367                                         sdi)) != SR_OK) {
368                         sr_err("Failed to start acquisition of device in "
369                                "running session (%s)", sr_strerror(ret));
370                         return ret;
371                 }
372         }
373
374         return SR_OK;
375 }
376
377 /**
378  * List all device instances attached to a session.
379  *
380  * @param session The session to use. Must not be NULL.
381  * @param devlist A pointer where the device instance list will be
382  *                stored on return. If no devices are in the session,
383  *                this will be NULL. Each element in the list points
384  *                to a struct sr_dev_inst *.
385  *                The list must be freed by the caller, but not the
386  *                elements pointed to.
387  *
388  * @retval SR_OK Success.
389  * @retval SR_ERR_ARG Invalid argument.
390  *
391  * @since 0.4.0
392  */
393 SR_API int sr_session_dev_list(struct sr_session *session, GSList **devlist)
394 {
395         if (!session)
396                 return SR_ERR_ARG;
397
398         if (!devlist)
399                 return SR_ERR_ARG;
400
401         *devlist = g_slist_copy(session->devs);
402
403         return SR_OK;
404 }
405
406 /**
407  * Remove a device instance from a session.
408  *
409  * @param session The session to remove from. Must not be NULL.
410  * @param sdi The device instance to remove from a session. Must not
411  *            be NULL. Also, sdi->driver and sdi->driver->dev_open must
412  *            not be NULL.
413  *
414  * @retval SR_OK Success.
415  * @retval SR_ERR_ARG Invalid argument.
416  *
417  * @since 0.4.0
418  */
419 SR_API int sr_session_dev_remove(struct sr_session *session,
420                 struct sr_dev_inst *sdi)
421 {
422         if (!sdi) {
423                 sr_err("%s: sdi was NULL", __func__);
424                 return SR_ERR_ARG;
425         }
426
427         if (!session) {
428                 sr_err("%s: session was NULL", __func__);
429                 return SR_ERR_ARG;
430         }
431
432         /* If sdi->session is not session, the device is not in this
433          * session. */
434         if (sdi->session != session) {
435                 sr_err("%s: not assigned to this session", __func__);
436                 return SR_ERR_ARG;
437         }
438
439         session->devs = g_slist_remove(session->devs, sdi);
440         sdi->session = NULL;
441
442         return SR_OK;
443 }
444
445 /**
446  * Remove all datafeed callbacks in a session.
447  *
448  * @param session The session to use. Must not be NULL.
449  *
450  * @retval SR_OK Success.
451  * @retval SR_ERR_ARG Invalid session passed.
452  *
453  * @since 0.4.0
454  */
455 SR_API int sr_session_datafeed_callback_remove_all(struct sr_session *session)
456 {
457         if (!session) {
458                 sr_err("%s: session was NULL", __func__);
459                 return SR_ERR_ARG;
460         }
461
462         g_slist_free_full(session->datafeed_callbacks, g_free);
463         session->datafeed_callbacks = NULL;
464
465         return SR_OK;
466 }
467
468 /**
469  * Add a datafeed callback to a session.
470  *
471  * @param session The session to use. Must not be NULL.
472  * @param cb Function to call when a chunk of data is received.
473  *           Must not be NULL.
474  * @param cb_data Opaque pointer passed in by the caller.
475  *
476  * @retval SR_OK Success.
477  * @retval SR_ERR_BUG No session exists.
478  *
479  * @since 0.3.0
480  */
481 SR_API int sr_session_datafeed_callback_add(struct sr_session *session,
482                 sr_datafeed_callback cb, void *cb_data)
483 {
484         struct datafeed_callback *cb_struct;
485
486         if (!session) {
487                 sr_err("%s: session was NULL", __func__);
488                 return SR_ERR_BUG;
489         }
490
491         if (!cb) {
492                 sr_err("%s: cb was NULL", __func__);
493                 return SR_ERR_ARG;
494         }
495
496         cb_struct = g_malloc0(sizeof(struct datafeed_callback));
497         cb_struct->cb = cb;
498         cb_struct->cb_data = cb_data;
499
500         session->datafeed_callbacks =
501             g_slist_append(session->datafeed_callbacks, cb_struct);
502
503         return SR_OK;
504 }
505
506 /**
507  * Get the trigger assigned to this session.
508  *
509  * @param session The session to use.
510  *
511  * @retval NULL Invalid (NULL) session was passed to the function.
512  * @retval other The trigger assigned to this session (can be NULL).
513  *
514  * @since 0.4.0
515  */
516 SR_API struct sr_trigger *sr_session_trigger_get(struct sr_session *session)
517 {
518         if (!session)
519                 return NULL;
520
521         return session->trigger;
522 }
523
524 /**
525  * Set the trigger of this session.
526  *
527  * @param session The session to use. Must not be NULL.
528  * @param trig The trigger to assign to this session. Can be NULL.
529  *
530  * @retval SR_OK Success.
531  * @retval SR_ERR_ARG Invalid argument.
532  *
533  * @since 0.4.0
534  */
535 SR_API int sr_session_trigger_set(struct sr_session *session, struct sr_trigger *trig)
536 {
537         if (!session)
538                 return SR_ERR_ARG;
539
540         session->trigger = trig;
541
542         return SR_OK;
543 }
544
545 static int verify_trigger(struct sr_trigger *trigger)
546 {
547         struct sr_trigger_stage *stage;
548         struct sr_trigger_match *match;
549         GSList *l, *m;
550
551         if (!trigger->stages) {
552                 sr_err("No trigger stages defined.");
553                 return SR_ERR;
554         }
555
556         sr_spew("Checking trigger:");
557         for (l = trigger->stages; l; l = l->next) {
558                 stage = l->data;
559                 if (!stage->matches) {
560                         sr_err("Stage %d has no matches defined.", stage->stage);
561                         return SR_ERR;
562                 }
563                 for (m = stage->matches; m; m = m->next) {
564                         match = m->data;
565                         if (!match->channel) {
566                                 sr_err("Stage %d match has no channel.", stage->stage);
567                                 return SR_ERR;
568                         }
569                         if (!match->match) {
570                                 sr_err("Stage %d match is not defined.", stage->stage);
571                                 return SR_ERR;
572                         }
573                         sr_spew("Stage %d match on channel %s, match %d", stage->stage,
574                                         match->channel->name, match->match);
575                 }
576         }
577
578         return SR_OK;
579 }
580
581 /** Set up the main context the session will be executing in.
582  *
583  * Must be called just before the session starts, by the thread which
584  * will execute the session main loop. Once acquired, the main context
585  * pointer is immutable for the duration of the session run.
586  */
587 static int set_main_context(struct sr_session *session)
588 {
589         GMainContext *main_context;
590
591         g_mutex_lock(&session->main_mutex);
592
593         /* May happen if sr_session_start() is called a second time
594          * while the session is still running.
595          */
596         if (session->main_context) {
597                 sr_err("Main context already set.");
598
599                 g_mutex_unlock(&session->main_mutex);
600                 return SR_ERR;
601         }
602         main_context = g_main_context_ref_thread_default();
603         /*
604          * Try to use an existing main context if possible, but only if we
605          * can make it owned by the current thread. Otherwise, create our
606          * own main context so that event source callbacks can execute in
607          * the session thread.
608          */
609         if (g_main_context_acquire(main_context)) {
610                 g_main_context_release(main_context);
611
612                 sr_dbg("Using thread-default main context.");
613         } else {
614                 g_main_context_unref(main_context);
615
616                 sr_dbg("Creating our own main context.");
617                 main_context = g_main_context_new();
618         }
619         session->main_context = main_context;
620
621         g_mutex_unlock(&session->main_mutex);
622
623         return SR_OK;
624 }
625
626 /** Unset the main context used for the current session run.
627  *
628  * Must be called right after stopping the session. Note that if the
629  * session is stopped asynchronously, the main loop may still be running
630  * after the main context has been unset. This is OK as long as no new
631  * event sources are created -- the main loop holds its own reference
632  * to the main context.
633  */
634 static int unset_main_context(struct sr_session *session)
635 {
636         int ret;
637
638         g_mutex_lock(&session->main_mutex);
639
640         if (session->main_context) {
641                 g_main_context_unref(session->main_context);
642                 session->main_context = NULL;
643                 ret = SR_OK;
644         } else {
645                 /* May happen if the set/unset calls are not matched.
646                  */
647                 sr_err("No main context to unset.");
648                 ret = SR_ERR;
649         }
650         g_mutex_unlock(&session->main_mutex);
651
652         return ret;
653 }
654
655 static unsigned int session_source_attach(struct sr_session *session,
656                 GSource *source)
657 {
658         unsigned int id = 0;
659
660         g_mutex_lock(&session->main_mutex);
661
662         if (session->main_context)
663                 id = g_source_attach(source, session->main_context);
664         else
665                 sr_err("Cannot add event source without main context.");
666
667         g_mutex_unlock(&session->main_mutex);
668
669         return id;
670 }
671
672 /* Idle handler; invoked when the number of registered event sources
673  * for a running session drops to zero.
674  */
675 static gboolean delayed_stop_check(void *data)
676 {
677         struct sr_session *session;
678
679         session = data;
680         session->stop_check_id = 0;
681
682         /* Session already ended? */
683         if (!session->running)
684                 return G_SOURCE_REMOVE;
685
686         /* New event sources may have been installed in the meantime. */
687         if (g_hash_table_size(session->event_sources) != 0)
688                 return G_SOURCE_REMOVE;
689
690         session->running = FALSE;
691         unset_main_context(session);
692
693         sr_info("Stopped.");
694
695         /* This indicates a bug in user code, since it is not valid to
696          * restart or destroy a session while it may still be running.
697          */
698         if (!session->main_loop && !session->stopped_callback) {
699                 sr_err("BUG: Session stop left unhandled.");
700                 return G_SOURCE_REMOVE;
701         }
702         if (session->main_loop)
703                 g_main_loop_quit(session->main_loop);
704
705         if (session->stopped_callback)
706                 (*session->stopped_callback)(session->stopped_cb_data);
707
708         return G_SOURCE_REMOVE;
709 }
710
711 static int stop_check_later(struct sr_session *session)
712 {
713         GSource *source;
714         unsigned int source_id;
715
716         if (session->stop_check_id != 0)
717                 return SR_OK; /* idle handler already installed */
718
719         source = g_idle_source_new();
720         g_source_set_callback(source, &delayed_stop_check, session, NULL);
721
722         source_id = session_source_attach(session, source);
723         session->stop_check_id = source_id;
724
725         g_source_unref(source);
726
727         return (source_id != 0) ? SR_OK : SR_ERR;
728 }
729
730 /**
731  * Start a session.
732  *
733  * When this function returns with a status code indicating success, the
734  * session is running. Use sr_session_stopped_callback_set() to receive
735  * notification upon completion, or call sr_session_run() to block until
736  * the session stops.
737  *
738  * Session events will be processed in the context of the current thread.
739  * If a thread-default GLib main context has been set, and is not owned by
740  * any other thread, it will be used. Otherwise, libsigrok will create its
741  * own main context for the current thread.
742  *
743  * @param session The session to use. Must not be NULL.
744  *
745  * @retval SR_OK Success.
746  * @retval SR_ERR_ARG Invalid session passed.
747  * @retval SR_ERR Other error.
748  *
749  * @since 0.4.0
750  */
751 SR_API int sr_session_start(struct sr_session *session)
752 {
753         struct sr_dev_inst *sdi;
754         struct sr_channel *ch;
755         GSList *l, *c, *lend;
756         int ret;
757
758         if (!session) {
759                 sr_err("%s: session was NULL", __func__);
760                 return SR_ERR_ARG;
761         }
762
763         if (!session->devs) {
764                 sr_err("%s: session->devs was NULL; a session "
765                        "cannot be started without devices.", __func__);
766                 return SR_ERR_ARG;
767         }
768
769         if (session->running) {
770                 sr_err("Cannot (re-)start session while it is still running.");
771                 return SR_ERR;
772         }
773
774         if (session->trigger) {
775                 ret = verify_trigger(session->trigger);
776                 if (ret != SR_OK)
777                         return ret;
778         }
779
780         /* Check enabled channels and commit settings of all devices. */
781         for (l = session->devs; l; l = l->next) {
782                 sdi = l->data;
783                 for (c = sdi->channels; c; c = c->next) {
784                         ch = c->data;
785                         if (ch->enabled)
786                                 break;
787                 }
788                 if (!c) {
789                         sr_err("%s device %s has no enabled channels.",
790                                 sdi->driver->name, sdi->connection_id);
791                         return SR_ERR;
792                 }
793
794                 ret = sr_config_commit(sdi);
795                 if (ret != SR_OK) {
796                         sr_err("Failed to commit %s device %s settings "
797                                 "before starting acquisition.",
798                                 sdi->driver->name, sdi->connection_id);
799                         return ret;
800                 }
801         }
802
803         ret = set_main_context(session);
804         if (ret != SR_OK)
805                 return ret;
806
807         sr_info("Starting.");
808
809         session->running = TRUE;
810
811         /* Have all devices start acquisition. */
812         for (l = session->devs; l; l = l->next) {
813                 sdi = l->data;
814                 ret = sdi->driver->dev_acquisition_start(sdi, sdi);
815                 if (ret != SR_OK) {
816                         sr_err("Could not start %s device %s acquisition.",
817                                 sdi->driver->name, sdi->connection_id);
818                         break;
819                 }
820         }
821
822         if (ret != SR_OK) {
823                 /* If there are multiple devices, some of them may already have
824                  * started successfully. Stop them now before returning. */
825                 lend = l->next;
826                 for (l = session->devs; l != lend; l = l->next) {
827                         sdi = l->data;
828                         if (sdi->driver->dev_acquisition_stop)
829                                 sdi->driver->dev_acquisition_stop(sdi, sdi);
830                 }
831                 /* TODO: Handle delayed stops. Need to iterate the event
832                  * sources... */
833                 session->running = FALSE;
834
835                 unset_main_context(session);
836                 return ret;
837         }
838
839         if (g_hash_table_size(session->event_sources) == 0)
840                 stop_check_later(session);
841
842         return SR_OK;
843 }
844
845 /**
846  * Block until the running session stops.
847  *
848  * This is a convenience function which creates a GLib main loop and runs
849  * it to process session events until the session stops.
850  *
851  * Instead of using this function, applications may run their own GLib main
852  * loop, and use sr_session_stopped_callback_set() to receive notification
853  * when the session finished running.
854  *
855  * @param session The session to use. Must not be NULL.
856  *
857  * @retval SR_OK Success.
858  * @retval SR_ERR_ARG Invalid session passed.
859  * @retval SR_ERR Other error.
860  *
861  * @since 0.4.0
862  */
863 SR_API int sr_session_run(struct sr_session *session)
864 {
865         if (!session) {
866                 sr_err("%s: session was NULL", __func__);
867                 return SR_ERR_ARG;
868         }
869         if (!session->running) {
870                 sr_err("No session running.");
871                 return SR_ERR;
872         }
873         if (session->main_loop) {
874                 sr_err("Main loop already created.");
875                 return SR_ERR;
876         }
877
878         g_mutex_lock(&session->main_mutex);
879
880         if (!session->main_context) {
881                 sr_err("Cannot run without main context.");
882                 g_mutex_unlock(&session->main_mutex);
883                 return SR_ERR;
884         }
885         session->main_loop = g_main_loop_new(session->main_context, FALSE);
886
887         g_mutex_unlock(&session->main_mutex);
888
889         g_main_loop_run(session->main_loop);
890
891         g_main_loop_unref(session->main_loop);
892         session->main_loop = NULL;
893
894         return SR_OK;
895 }
896
897 static gboolean session_stop_sync(void *user_data)
898 {
899         struct sr_session *session;
900         struct sr_dev_inst *sdi;
901         GSList *node;
902
903         session = user_data;
904
905         if (!session->running)
906                 return G_SOURCE_REMOVE;
907
908         sr_info("Stopping.");
909
910         for (node = session->devs; node; node = node->next) {
911                 sdi = node->data;
912                 if (sdi->driver && sdi->driver->dev_acquisition_stop)
913                         sdi->driver->dev_acquisition_stop(sdi, sdi);
914         }
915
916         return G_SOURCE_REMOVE;
917 }
918
919 /**
920  * Stop a session.
921  *
922  * This requests the drivers of each device participating in the session to
923  * abort the acquisition as soon as possible. Even after this function returns,
924  * event processing still continues until all devices have actually stopped.
925  *
926  * Use sr_session_stopped_callback_set() to receive notification when the event
927  * processing finished.
928  *
929  * This function is reentrant. That is, it may be called from a different
930  * thread than the one executing the session, as long as it can be ensured
931  * that the session object is valid.
932  *
933  * If the session is not running, sr_session_stop() silently does nothing.
934  *
935  * @param session The session to use. Must not be NULL.
936  *
937  * @retval SR_OK Success.
938  * @retval SR_ERR_ARG Invalid session passed.
939  *
940  * @since 0.4.0
941  */
942 SR_API int sr_session_stop(struct sr_session *session)
943 {
944         GMainContext *main_context;
945
946         if (!session) {
947                 sr_err("%s: session was NULL", __func__);
948                 return SR_ERR_ARG;
949         }
950
951         g_mutex_lock(&session->main_mutex);
952
953         main_context = (session->main_context)
954                 ? g_main_context_ref(session->main_context)
955                 : NULL;
956
957         g_mutex_unlock(&session->main_mutex);
958
959         if (!main_context) {
960                 sr_dbg("No main context set; already stopped?");
961                 /* Not an error; as it would be racy. */
962                 return SR_OK;
963         }
964         g_main_context_invoke(main_context, &session_stop_sync, session);
965         g_main_context_unref(main_context);
966
967         return SR_OK;
968 }
969
970 /**
971  * Return whether the session is currently running.
972  *
973  * Note that this function should be called from the same thread
974  * the session was started in.
975  *
976  * @param session The session to use. Must not be NULL.
977  *
978  * @retval TRUE Session is running.
979  * @retval FALSE Session is not running.
980  * @retval SR_ERR_ARG Invalid session passed.
981  *
982  * @since 0.4.0
983  */
984 SR_API int sr_session_is_running(struct sr_session *session)
985 {
986         if (!session) {
987                 sr_err("%s: session was NULL", __func__);
988                 return SR_ERR_ARG;
989         }
990         return session->running;
991 }
992
993 /**
994  * Set the callback to be invoked after a session stopped running.
995  *
996  * Install a callback to receive notification when a session run stopped.
997  * This can be used to integrate session execution with an existing main
998  * loop, without having to block in sr_session_run().
999  *
1000  * Note that the callback will be invoked in the context of the thread
1001  * that calls sr_session_start().
1002  *
1003  * @param session The session to use. Must not be NULL.
1004  * @param cb The callback to invoke on session stop. May be NULL to unset.
1005  * @param cb_data User data pointer to be passed to the callback.
1006  *
1007  * @retval SR_OK Success.
1008  * @retval SR_ERR_ARG Invalid session passed.
1009  *
1010  * @since 0.4.0
1011  */
1012 SR_API int sr_session_stopped_callback_set(struct sr_session *session,
1013                 sr_session_stopped_callback cb, void *cb_data)
1014 {
1015         if (!session) {
1016                 sr_err("%s: session was NULL", __func__);
1017                 return SR_ERR_ARG;
1018         }
1019         session->stopped_callback = cb;
1020         session->stopped_cb_data = cb_data;
1021
1022         return SR_OK;
1023 }
1024
1025 /**
1026  * Debug helper.
1027  *
1028  * @param packet The packet to show debugging information for.
1029  */
1030 static void datafeed_dump(const struct sr_datafeed_packet *packet)
1031 {
1032         const struct sr_datafeed_logic *logic;
1033         const struct sr_datafeed_analog_old *analog_old;
1034         const struct sr_datafeed_analog *analog;
1035
1036         /* Please use the same order as in libsigrok.h. */
1037         switch (packet->type) {
1038         case SR_DF_HEADER:
1039                 sr_dbg("bus: Received SR_DF_HEADER packet.");
1040                 break;
1041         case SR_DF_END:
1042                 sr_dbg("bus: Received SR_DF_END packet.");
1043                 break;
1044         case SR_DF_META:
1045                 sr_dbg("bus: Received SR_DF_META packet.");
1046                 break;
1047         case SR_DF_TRIGGER:
1048                 sr_dbg("bus: Received SR_DF_TRIGGER packet.");
1049                 break;
1050         case SR_DF_LOGIC:
1051                 logic = packet->payload;
1052                 sr_dbg("bus: Received SR_DF_LOGIC packet (%" PRIu64 " bytes, "
1053                        "unitsize = %d).", logic->length, logic->unitsize);
1054                 break;
1055         case SR_DF_ANALOG_OLD:
1056                 analog_old = packet->payload;
1057                 sr_dbg("bus: Received SR_DF_ANALOG_OLD packet (%d samples).",
1058                        analog_old->num_samples);
1059                 break;
1060         case SR_DF_FRAME_BEGIN:
1061                 sr_dbg("bus: Received SR_DF_FRAME_BEGIN packet.");
1062                 break;
1063         case SR_DF_FRAME_END:
1064                 sr_dbg("bus: Received SR_DF_FRAME_END packet.");
1065                 break;
1066         case SR_DF_ANALOG:
1067                 analog = packet->payload;
1068                 sr_dbg("bus: Received SR_DF_ANALOG packet (%d samples).",
1069                        analog->num_samples);
1070                 break;
1071         default:
1072                 sr_dbg("bus: Received unknown packet type: %d.", packet->type);
1073                 break;
1074         }
1075 }
1076
1077 /**
1078  * Send a packet to whatever is listening on the datafeed bus.
1079  *
1080  * Hardware drivers use this to send a data packet to the frontend.
1081  *
1082  * @param sdi TODO.
1083  * @param packet The datafeed packet to send to the session bus.
1084  *
1085  * @retval SR_OK Success.
1086  * @retval SR_ERR_ARG Invalid argument.
1087  *
1088  * @private
1089  */
1090 SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi,
1091                 const struct sr_datafeed_packet *packet)
1092 {
1093         GSList *l;
1094         struct datafeed_callback *cb_struct;
1095         struct sr_datafeed_packet *packet_in, *packet_out;
1096         struct sr_transform *t;
1097         int ret;
1098
1099         if (!sdi) {
1100                 sr_err("%s: sdi was NULL", __func__);
1101                 return SR_ERR_ARG;
1102         }
1103
1104         if (!packet) {
1105                 sr_err("%s: packet was NULL", __func__);
1106                 return SR_ERR_ARG;
1107         }
1108
1109         if (!sdi->session) {
1110                 sr_err("%s: session was NULL", __func__);
1111                 return SR_ERR_BUG;
1112         }
1113
1114         if (packet->type == SR_DF_ANALOG_OLD) {
1115                 /* Convert to SR_DF_ANALOG. */
1116                 const struct sr_datafeed_analog_old *analog_old = packet->payload;
1117                 struct sr_analog_encoding encoding;
1118                 struct sr_analog_meaning meaning;
1119                 struct sr_analog_spec spec;
1120                 struct sr_datafeed_analog analog;
1121                 struct sr_datafeed_packet new_packet;
1122                 new_packet.type = SR_DF_ANALOG;
1123                 new_packet.payload = &analog;
1124                 analog.data = analog_old->data;
1125                 analog.num_samples = analog_old->num_samples;
1126                 analog.encoding = &encoding;
1127                 analog.meaning = &meaning;
1128                 analog.spec = &spec;
1129                 encoding.unitsize = sizeof(float);
1130                 encoding.is_signed = TRUE;
1131                 encoding.is_float = TRUE;
1132 #ifdef WORDS_BIGENDIAN
1133                 encoding.is_bigendian = TRUE;
1134 #else
1135                 encoding.is_bigendian = FALSE;
1136 #endif
1137                 encoding.digits = 0;
1138                 encoding.is_digits_decimal = FALSE;
1139                 encoding.scale.p = 1;
1140                 encoding.scale.q = 1;
1141                 encoding.offset.p = 0;
1142                 encoding.offset.q = 1;
1143                 meaning.mq = analog_old->mq;
1144                 meaning.unit = analog_old->unit;
1145                 meaning.mqflags = analog_old->mqflags;
1146                 meaning.channels = analog_old->channels;
1147                 spec.spec_digits = 0;
1148                 return sr_session_send(sdi, &new_packet);
1149         }
1150
1151         /*
1152          * Pass the packet to the first transform module. If that returns
1153          * another packet (instead of NULL), pass that packet to the next
1154          * transform module in the list, and so on.
1155          */
1156         packet_in = (struct sr_datafeed_packet *)packet;
1157         for (l = sdi->session->transforms; l; l = l->next) {
1158                 t = l->data;
1159                 sr_spew("Running transform module '%s'.", t->module->id);
1160                 ret = t->module->receive(t, packet_in, &packet_out);
1161                 if (ret < 0) {
1162                         sr_err("Error while running transform module: %d.", ret);
1163                         return SR_ERR;
1164                 }
1165                 if (!packet_out) {
1166                         /*
1167                          * If any of the transforms don't return an output
1168                          * packet, abort.
1169                          */
1170                         sr_spew("Transform module didn't return a packet, aborting.");
1171                         return SR_OK;
1172                 } else {
1173                         /*
1174                          * Use this transform module's output packet as input
1175                          * for the next transform module.
1176                          */
1177                         packet_in = packet_out;
1178                 }
1179         }
1180         packet = packet_in;
1181
1182         /*
1183          * If the last transform did output a packet, pass it to all datafeed
1184          * callbacks.
1185          */
1186         for (l = sdi->session->datafeed_callbacks; l; l = l->next) {
1187                 if (sr_log_loglevel_get() >= SR_LOG_DBG)
1188                         datafeed_dump(packet);
1189                 cb_struct = l->data;
1190                 cb_struct->cb(sdi, packet, cb_struct->cb_data);
1191         }
1192
1193         return SR_OK;
1194 }
1195
1196 /**
1197  * Add an event source for a file descriptor.
1198  *
1199  * @param session The session to use. Must not be NULL.
1200  * @param key The key which identifies the event source.
1201  * @param source An event source object. Must not be NULL.
1202  *
1203  * @retval SR_OK Success.
1204  * @retval SR_ERR_ARG Invalid argument.
1205  * @retval SR_ERR_BUG Event source with @a key already installed.
1206  * @retval SR_ERR Other error.
1207  *
1208  * @private
1209  */
1210 SR_PRIV int sr_session_source_add_internal(struct sr_session *session,
1211                 void *key, GSource *source)
1212 {
1213         /*
1214          * This must not ever happen, since the source has already been
1215          * created and its finalize() method will remove the key for the
1216          * already installed source. (Well it would, if we did not have
1217          * another sanity check there.)
1218          */
1219         if (g_hash_table_contains(session->event_sources, key)) {
1220                 sr_err("Event source with key %p already exists.", key);
1221                 return SR_ERR_BUG;
1222         }
1223         g_hash_table_insert(session->event_sources, key, source);
1224
1225         if (session_source_attach(session, source) == 0)
1226                 return SR_ERR;
1227
1228         return SR_OK;
1229 }
1230
1231 SR_PRIV int sr_session_fd_source_add(struct sr_session *session,
1232                 void *key, gintptr fd, int events, int timeout,
1233                 sr_receive_data_callback cb, void *cb_data)
1234 {
1235         GSource *source;
1236         int ret;
1237
1238         source = fd_source_new(session, key, fd, events, timeout);
1239         if (!source)
1240                 return SR_ERR;
1241
1242         g_source_set_callback(source, (GSourceFunc)cb, cb_data, NULL);
1243
1244         ret = sr_session_source_add_internal(session, key, source);
1245         g_source_unref(source);
1246
1247         return ret;
1248 }
1249
1250 /**
1251  * Add an event source for a file descriptor.
1252  *
1253  * @param session The session to use. Must not be NULL.
1254  * @param fd The file descriptor, or a negative value to create a timer source.
1255  * @param events Events to check for.
1256  * @param timeout Max time in ms to wait before the callback is called,
1257  *                or -1 to wait indefinitely.
1258  * @param cb Callback function to add. Must not be NULL.
1259  * @param cb_data Data for the callback function. Can be NULL.
1260  *
1261  * @retval SR_OK Success.
1262  * @retval SR_ERR_ARG Invalid argument.
1263  *
1264  * @since 0.3.0
1265  * @private
1266  */
1267 SR_PRIV int sr_session_source_add(struct sr_session *session, int fd,
1268                 int events, int timeout, sr_receive_data_callback cb, void *cb_data)
1269 {
1270         if (fd < 0 && timeout < 0) {
1271                 sr_err("Cannot create timer source without timeout.");
1272                 return SR_ERR_ARG;
1273         }
1274         return sr_session_fd_source_add(session, GINT_TO_POINTER(fd),
1275                         fd, events, timeout, cb, cb_data);
1276 }
1277
1278 /**
1279  * Add an event source for a GPollFD.
1280  *
1281  * @param session The session to use. Must not be NULL.
1282  * @param pollfd The GPollFD. Must not be NULL.
1283  * @param timeout Max time in ms to wait before the callback is called,
1284  *                or -1 to wait indefinitely.
1285  * @param cb Callback function to add. Must not be NULL.
1286  * @param cb_data Data for the callback function. Can be NULL.
1287  *
1288  * @retval SR_OK Success.
1289  * @retval SR_ERR_ARG Invalid argument.
1290  *
1291  * @since 0.3.0
1292  * @private
1293  */
1294 SR_PRIV int sr_session_source_add_pollfd(struct sr_session *session,
1295                 GPollFD *pollfd, int timeout, sr_receive_data_callback cb,
1296                 void *cb_data)
1297 {
1298         if (!pollfd) {
1299                 sr_err("%s: pollfd was NULL", __func__);
1300                 return SR_ERR_ARG;
1301         }
1302         return sr_session_fd_source_add(session, pollfd, pollfd->fd,
1303                         pollfd->events, timeout, cb, cb_data);
1304 }
1305
1306 /**
1307  * Add an event source for a GIOChannel.
1308  *
1309  * @param session The session to use. Must not be NULL.
1310  * @param channel The GIOChannel.
1311  * @param events Events to poll on.
1312  * @param timeout Max time in ms to wait before the callback is called,
1313  *                or -1 to wait indefinitely.
1314  * @param cb Callback function to add. Must not be NULL.
1315  * @param cb_data Data for the callback function. Can be NULL.
1316  *
1317  * @retval SR_OK Success.
1318  * @retval SR_ERR_ARG Invalid argument.
1319  *
1320  * @since 0.3.0
1321  * @private
1322  */
1323 SR_PRIV int sr_session_source_add_channel(struct sr_session *session,
1324                 GIOChannel *channel, int events, int timeout,
1325                 sr_receive_data_callback cb, void *cb_data)
1326 {
1327         GPollFD pollfd;
1328
1329         if (!channel) {
1330                 sr_err("%s: channel was NULL", __func__);
1331                 return SR_ERR_ARG;
1332         }
1333         /* We should be using g_io_create_watch(), but can't without
1334          * changing the driver API, as the callback signature is different.
1335          */
1336 #ifdef G_OS_WIN32
1337         g_io_channel_win32_make_pollfd(channel, events, &pollfd);
1338 #else
1339         pollfd.fd = g_io_channel_unix_get_fd(channel);
1340         pollfd.events = events;
1341 #endif
1342         return sr_session_fd_source_add(session, channel, pollfd.fd,
1343                         pollfd.events, timeout, cb, cb_data);
1344 }
1345
1346 /**
1347  * Remove the source identified by the specified poll object.
1348  *
1349  * @param session The session to use. Must not be NULL.
1350  * @param key The key by which the source is identified.
1351  *
1352  * @retval SR_OK Success
1353  * @retval SR_ERR_BUG No event source for poll_object found.
1354  *
1355  * @private
1356  */
1357 SR_PRIV int sr_session_source_remove_internal(struct sr_session *session,
1358                 void *key)
1359 {
1360         GSource *source;
1361
1362         source = g_hash_table_lookup(session->event_sources, key);
1363         /*
1364          * Trying to remove an already removed event source is problematic
1365          * since the poll_object handle may have been reused in the meantime.
1366          */
1367         if (!source) {
1368                 sr_warn("Cannot remove non-existing event source %p.", key);
1369                 return SR_ERR_BUG;
1370         }
1371         g_source_destroy(source);
1372
1373         return SR_OK;
1374 }
1375
1376 /**
1377  * Remove the source belonging to the specified file descriptor.
1378  *
1379  * @param session The session to use. Must not be NULL.
1380  * @param fd The file descriptor for which the source should be removed.
1381  *
1382  * @retval SR_OK Success
1383  * @retval SR_ERR_ARG Invalid argument
1384  * @retval SR_ERR_BUG Internal error.
1385  *
1386  * @since 0.3.0
1387  * @private
1388  */
1389 SR_PRIV int sr_session_source_remove(struct sr_session *session, int fd)
1390 {
1391         return sr_session_source_remove_internal(session, GINT_TO_POINTER(fd));
1392 }
1393
1394 /**
1395  * Remove the source belonging to the specified poll descriptor.
1396  *
1397  * @param session The session to use. Must not be NULL.
1398  * @param pollfd The poll descriptor for which the source should be removed.
1399  *               Must not be NULL.
1400  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
1401  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
1402  *         internal errors.
1403  *
1404  * @since 0.2.0
1405  * @private
1406  */
1407 SR_PRIV int sr_session_source_remove_pollfd(struct sr_session *session,
1408                 GPollFD *pollfd)
1409 {
1410         if (!pollfd) {
1411                 sr_err("%s: pollfd was NULL", __func__);
1412                 return SR_ERR_ARG;
1413         }
1414         return sr_session_source_remove_internal(session, pollfd);
1415 }
1416
1417 /**
1418  * Remove the source belonging to the specified channel.
1419  *
1420  * @param session The session to use. Must not be NULL.
1421  * @param channel The channel for which the source should be removed.
1422  *                Must not be NULL.
1423  * @retval SR_OK Success.
1424  * @retval SR_ERR_ARG Invalid argument.
1425  * @return SR_ERR_BUG Internal error.
1426  *
1427  * @since 0.2.0
1428  * @private
1429  */
1430 SR_PRIV int sr_session_source_remove_channel(struct sr_session *session,
1431                 GIOChannel *channel)
1432 {
1433         if (!channel) {
1434                 sr_err("%s: channel was NULL", __func__);
1435                 return SR_ERR_ARG;
1436         }
1437         return sr_session_source_remove_internal(session, channel);
1438 }
1439
1440 /** Unregister an event source that has been destroyed.
1441  *
1442  * This is intended to be called from a source's finalize() method.
1443  *
1444  * @param session The session to use. Must not be NULL.
1445  * @param key The key used to identify @a source.
1446  * @param source The source object that was destroyed.
1447  *
1448  * @retval SR_OK Success.
1449  * @retval SR_ERR_BUG Event source for @a key does not match @a source.
1450  * @retval SR_ERR Other error.
1451  *
1452  * @private
1453  */
1454 SR_PRIV int sr_session_source_destroyed(struct sr_session *session,
1455                 void *key, GSource *source)
1456 {
1457         GSource *registered_source;
1458
1459         registered_source = g_hash_table_lookup(session->event_sources, key);
1460         /*
1461          * Trying to remove an already removed event source is problematic
1462          * since the poll_object handle may have been reused in the meantime.
1463          */
1464         if (!registered_source) {
1465                 sr_err("No event source for key %p found.", key);
1466                 return SR_ERR_BUG;
1467         }
1468         if (registered_source != source) {
1469                 sr_err("Event source for key %p does not match"
1470                         " destroyed source.", key);
1471                 return SR_ERR_BUG;
1472         }
1473         g_hash_table_remove(session->event_sources, key);
1474
1475         if (g_hash_table_size(session->event_sources) > 0)
1476                 return SR_OK;
1477
1478         /* If no event sources are left, consider the acquisition finished.
1479          * This is pretty crude, as it requires all event sources to be
1480          * registered via the libsigrok API.
1481          */
1482         return stop_check_later(session);
1483 }
1484
1485 static void copy_src(struct sr_config *src, struct sr_datafeed_meta *meta_copy)
1486 {
1487         g_variant_ref(src->data);
1488         meta_copy->config = g_slist_append(meta_copy->config,
1489                                            g_memdup(src, sizeof(struct sr_config)));
1490 }
1491
1492 SR_PRIV int sr_packet_copy(const struct sr_datafeed_packet *packet,
1493                 struct sr_datafeed_packet **copy)
1494 {
1495         const struct sr_datafeed_meta *meta;
1496         struct sr_datafeed_meta *meta_copy;
1497         const struct sr_datafeed_logic *logic;
1498         struct sr_datafeed_logic *logic_copy;
1499         const struct sr_datafeed_analog_old *analog_old;
1500         struct sr_datafeed_analog_old *analog_old_copy;
1501         const struct sr_datafeed_analog *analog;
1502         struct sr_datafeed_analog *analog_copy;
1503         uint8_t *payload;
1504
1505         *copy = g_malloc0(sizeof(struct sr_datafeed_packet));
1506         (*copy)->type = packet->type;
1507
1508         switch (packet->type) {
1509         case SR_DF_TRIGGER:
1510         case SR_DF_END:
1511                 /* No payload. */
1512                 break;
1513         case SR_DF_HEADER:
1514                 payload = g_malloc(sizeof(struct sr_datafeed_header));
1515                 memcpy(payload, packet->payload, sizeof(struct sr_datafeed_header));
1516                 (*copy)->payload = payload;
1517                 break;
1518         case SR_DF_META:
1519                 meta = packet->payload;
1520                 meta_copy = g_malloc0(sizeof(struct sr_datafeed_meta));
1521                 g_slist_foreach(meta->config, (GFunc)copy_src, meta_copy->config);
1522                 (*copy)->payload = meta_copy;
1523                 break;
1524         case SR_DF_LOGIC:
1525                 logic = packet->payload;
1526                 logic_copy = g_malloc(sizeof(logic));
1527                 logic_copy->length = logic->length;
1528                 logic_copy->unitsize = logic->unitsize;
1529                 memcpy(logic_copy->data, logic->data, logic->length * logic->unitsize);
1530                 (*copy)->payload = logic_copy;
1531                 break;
1532         case SR_DF_ANALOG_OLD:
1533                 analog_old = packet->payload;
1534                 analog_old_copy = g_malloc(sizeof(analog_old));
1535                 analog_old_copy->channels = g_slist_copy(analog_old->channels);
1536                 analog_old_copy->num_samples = analog_old->num_samples;
1537                 analog_old_copy->mq = analog_old->mq;
1538                 analog_old_copy->unit = analog_old->unit;
1539                 analog_old_copy->mqflags = analog_old->mqflags;
1540                 analog_old_copy->data = g_malloc(analog_old->num_samples * sizeof(float));
1541                 memcpy(analog_old_copy->data, analog_old->data,
1542                                 analog_old->num_samples * sizeof(float));
1543                 (*copy)->payload = analog_old_copy;
1544                 break;
1545         case SR_DF_ANALOG:
1546                 analog = packet->payload;
1547                 analog_copy = g_malloc(sizeof(analog));
1548                 analog_copy->data = g_malloc(
1549                                 analog->encoding->unitsize * analog->num_samples);
1550                 memcpy(analog_copy->data, analog->data,
1551                                 analog->encoding->unitsize * analog->num_samples);
1552                 analog_copy->num_samples = analog->num_samples;
1553                 analog_copy->encoding = g_memdup(analog->encoding,
1554                                 sizeof(struct sr_analog_encoding));
1555                 analog_copy->meaning = g_memdup(analog->meaning,
1556                                 sizeof(struct sr_analog_meaning));
1557                 analog_copy->meaning->channels = g_slist_copy(
1558                                 analog->meaning->channels);
1559                 analog_copy->spec = g_memdup(analog->spec,
1560                                 sizeof(struct sr_analog_spec));
1561                 (*copy)->payload = analog_copy;
1562                 break;
1563         default:
1564                 sr_err("Unknown packet type %d", packet->type);
1565                 return SR_ERR;
1566         }
1567
1568         return SR_OK;
1569 }
1570
1571 void sr_packet_free(struct sr_datafeed_packet *packet)
1572 {
1573         const struct sr_datafeed_meta *meta;
1574         const struct sr_datafeed_logic *logic;
1575         const struct sr_datafeed_analog_old *analog_old;
1576         const struct sr_datafeed_analog *analog;
1577         struct sr_config *src;
1578         GSList *l;
1579
1580         switch (packet->type) {
1581         case SR_DF_TRIGGER:
1582         case SR_DF_END:
1583                 /* No payload. */
1584                 break;
1585         case SR_DF_HEADER:
1586                 /* Payload is a simple struct. */
1587                 g_free((void *)packet->payload);
1588                 break;
1589         case SR_DF_META:
1590                 meta = packet->payload;
1591                 for (l = meta->config; l; l = l->next) {
1592                         src = l->data;
1593                         g_variant_unref(src->data);
1594                         g_free(src);
1595                 }
1596                 g_slist_free(meta->config);
1597                 g_free((void *)packet->payload);
1598                 break;
1599         case SR_DF_LOGIC:
1600                 logic = packet->payload;
1601                 g_free(logic->data);
1602                 g_free((void *)packet->payload);
1603                 break;
1604         case SR_DF_ANALOG_OLD:
1605                 analog_old = packet->payload;
1606                 g_slist_free(analog_old->channels);
1607                 g_free(analog_old->data);
1608                 g_free((void *)packet->payload);
1609                 break;
1610         case SR_DF_ANALOG:
1611                 analog = packet->payload;
1612                 g_free(analog->data);
1613                 g_free(analog->encoding);
1614                 g_slist_free(analog->meaning->channels);
1615                 g_free(analog->meaning);
1616                 g_free(analog->spec);
1617                 g_free((void *)packet->payload);
1618                 break;
1619         default:
1620                 sr_err("Unknown packet type %d", packet->type);
1621         }
1622         g_free(packet);
1623
1624 }
1625
1626 /** @} */