libsigrokdecode  0.5.2
sigrok protocol decoding library
srd.c
Go to the documentation of this file.
1 /*
2  * This file is part of the libsigrokdecode project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2013 Bert Vermeulen <bert@biot.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 "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include "libsigrokdecode.h"
24 #include <glib.h>
25 
26 /** @cond PRIVATE */
27 
28 /* Python module search paths */
29 SRD_PRIV GSList *searchpaths = NULL;
30 
31 /* session.c */
32 extern SRD_PRIV GSList *sessions;
33 extern SRD_PRIV int max_session_id;
34 
35 /** @endcond */
36 
37 /**
38  * @mainpage libsigrokdecode API
39  *
40  * @section sec_intro Introduction
41  *
42  * The <a href="http://sigrok.org">sigrok</a> project aims at creating a
43  * portable, cross-platform, Free/Libre/Open-Source signal analysis software
44  * suite that supports various device types (such as logic analyzers,
45  * oscilloscopes, multimeters, and more).
46  *
47  * <a href="http://sigrok.org/wiki/Libsigrokdecode">libsigrokdecode</a> is a
48  * shared library written in C which provides the basic API for (streaming)
49  * protocol decoding functionality.
50  *
51  * The <a href="http://sigrok.org/wiki/Protocol_decoders">protocol decoders</a>
52  * are written in Python (>= 3.0).
53  *
54  * @section sec_api API reference
55  *
56  * See the "Modules" page for an introduction to various libsigrokdecode
57  * related topics and the detailed API documentation of the respective
58  * functions.
59  *
60  * You can also browse the API documentation by file, or review all
61  * data structures.
62  *
63  * @section sec_mailinglists Mailing lists
64  *
65  * There is one mailing list for sigrok/libsigrokdecode: <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-devel">sigrok-devel</a>.
66  *
67  * @section sec_irc IRC
68  *
69  * You can find the sigrok developers in the
70  * <a href="irc://chat.freenode.net/sigrok">\#sigrok</a>
71  * IRC channel on Freenode.
72  *
73  * @section sec_website Website
74  *
75  * <a href="http://sigrok.org/wiki/Libsigrokdecode">sigrok.org/wiki/Libsigrokdecode</a>
76  */
77 
78 /**
79  * @file
80  *
81  * Initializing and shutting down libsigrokdecode.
82  */
83 
84 /**
85  * @defgroup grp_init Initialization
86  *
87  * Initializing and shutting down libsigrokdecode.
88  *
89  * Before using any of the libsigrokdecode functionality, srd_init() must
90  * be called to initialize the library.
91  *
92  * When libsigrokdecode functionality is no longer needed, srd_exit() should
93  * be called.
94  *
95  * @{
96  */
97 
98 static int searchpath_add_xdg_dir(const char *datadir)
99 {
100  char *decdir;
101  int ret;
102 
103  decdir = g_build_filename(datadir, PACKAGE_TARNAME, "decoders", NULL);
104 
105  if (g_file_test(decdir, G_FILE_TEST_IS_DIR))
106  ret = srd_decoder_searchpath_add(decdir);
107  else
108  ret = SRD_OK; /* Just ignore non-existing directory. */
109 
110  g_free(decdir);
111 
112  return ret;
113 }
114 
115 static void print_versions(void)
116 {
117  GString *s;
118  GSList *l, *l_orig, *m;
119  char *str;
120  const char *lib, *version;
121 
122  srd_dbg("libsigrokdecode %s/%s (rt: %s/%s).",
125 
126  s = g_string_sized_new(200);
127  g_string_append(s, "Libs: ");
128  l_orig = srd_buildinfo_libs_get();
129  for (l = l_orig; l; l = l->next) {
130  m = l->data;
131  lib = m->data;
132  version = m->next->data;
133  g_string_append_printf(s, "%s %s, ", lib, version);
134  g_slist_free_full(m, g_free);
135  }
136  g_slist_free(l_orig);
137  s->str[s->len - 2] = '.';
138  s->str[s->len - 1] = '\0';
139  srd_dbg("%s", s->str);
140  g_string_free(s, TRUE);
141 
142  str = srd_buildinfo_host_get();
143  srd_dbg("Host: %s.", str);
144  g_free(str);
145 }
146 
147 static int print_searchpaths(void)
148 {
149  PyObject *py_paths, *py_path, *py_bytes;
150  PyGILState_STATE gstate;
151  GString *s;
152  GSList *l;
153  int i;
154 
155  s = g_string_sized_new(500);
156  g_string_append(s, "Protocol decoder search paths:\n");
157  for (l = searchpaths; l; l = l->next)
158  g_string_append_printf(s, " - %s\n", (const char *)l->data);
159  s->str[s->len - 1] = '\0';
160  srd_dbg("%s", s->str);
161  g_string_free(s, TRUE);
162 
163  gstate = PyGILState_Ensure();
164 
165  py_paths = PySys_GetObject("path");
166  if (!py_paths)
167  goto err;
168 
169  s = g_string_sized_new(500);
170  g_string_append(s, "Python system search paths:\n");
171  for (i = 0; i < PyList_Size(py_paths); i++) {
172  py_path = PyList_GetItem(py_paths, i);
173  py_bytes = PyUnicode_AsUTF8String(py_path);
174  g_string_append_printf(s, " - %s\n", PyBytes_AsString(py_bytes));
175  }
176  s->str[s->len - 1] = '\0';
177  srd_dbg("%s", s->str);
178  g_string_free(s, TRUE);
179 
180  PyGILState_Release(gstate);
181 
182  return SRD_OK;
183 
184 err:
185  srd_err("Unable to query Python system search paths.");
186  PyGILState_Release(gstate);
187 
188  return SRD_ERR_PYTHON;
189 }
190 
191 /**
192  * Initialize libsigrokdecode.
193  *
194  * This initializes the Python interpreter, and creates and initializes
195  * a "sigrokdecode" Python module.
196  *
197  * Then, it searches for sigrok protocol decoders in the "decoders"
198  * subdirectory of the the libsigrokdecode installation directory.
199  * All decoders that are found are loaded into memory and added to an
200  * internal list of decoders, which can be queried via srd_decoder_list().
201  *
202  * The caller is responsible for calling the clean-up function srd_exit(),
203  * which will properly shut down libsigrokdecode and free its allocated memory.
204  *
205  * Multiple calls to srd_init(), without calling srd_exit() in between,
206  * are not allowed.
207  *
208  * @param path Path to an extra directory containing protocol decoders
209  * which will be added to the Python sys.path. May be NULL.
210  *
211  * @return SRD_OK upon success, a (negative) error code otherwise.
212  * Upon Python errors, SRD_ERR_PYTHON is returned. If the decoders
213  * directory cannot be accessed, SRD_ERR_DECODERS_DIR is returned.
214  * If not enough memory could be allocated, SRD_ERR_MALLOC is returned.
215  *
216  * @since 0.1.0
217  */
218 SRD_API int srd_init(const char *path)
219 {
220  const char *const *sys_datadirs;
221  const char *env_path;
222  size_t i;
223  int ret;
224 
225  if (max_session_id != -1) {
226  srd_err("libsigrokdecode is already initialized.");
227  return SRD_ERR;
228  }
229 
230  print_versions();
231 
232  srd_dbg("Initializing libsigrokdecode.");
233 
234  /* Add our own module to the list of built-in modules. */
235  PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
236 
237  /* Initialize the Python interpreter. */
238  Py_InitializeEx(0);
239 
240  /* Locations relative to the XDG system data directories. */
241  sys_datadirs = g_get_system_data_dirs();
242  for (i = g_strv_length((char **)sys_datadirs); i > 0; i--) {
243  ret = searchpath_add_xdg_dir(sys_datadirs[i - 1]);
244  if (ret != SRD_OK) {
245  Py_Finalize();
246  return ret;
247  }
248  }
249 #ifdef DECODERS_DIR
250  /* Hardcoded decoders install location, if defined. */
251  if ((ret = srd_decoder_searchpath_add(DECODERS_DIR)) != SRD_OK) {
252  Py_Finalize();
253  return ret;
254  }
255 #endif
256  /* Location relative to the XDG user data directory. */
257  ret = searchpath_add_xdg_dir(g_get_user_data_dir());
258  if (ret != SRD_OK) {
259  Py_Finalize();
260  return ret;
261  }
262 
263  /* Path specified by the user. */
264  if (path) {
265  if ((ret = srd_decoder_searchpath_add(path)) != SRD_OK) {
266  Py_Finalize();
267  return ret;
268  }
269  }
270 
271  /* Environment variable overrides everything, for debugging. */
272  if ((env_path = g_getenv("SIGROKDECODE_DIR"))) {
273  if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) {
274  Py_Finalize();
275  return ret;
276  }
277  }
278 
279  /* Initialize the Python GIL (this also happens to acquire it). */
280  PyEval_InitThreads();
281 
282  /* Release the GIL (ignore return value, we don't need it here). */
283  (void)PyEval_SaveThread();
284 
285  max_session_id = 0;
286 
287  print_searchpaths();
288 
289  return SRD_OK;
290 }
291 
292 /**
293  * Shutdown libsigrokdecode.
294  *
295  * This frees all the memory allocated for protocol decoders and shuts down
296  * the Python interpreter.
297  *
298  * This function should only be called if there was a (successful!) invocation
299  * of srd_init() before. Calling this function multiple times in a row, without
300  * any successful srd_init() calls in between, is not allowed.
301  *
302  * @return SRD_OK upon success, a (negative) error code otherwise.
303  *
304  * @since 0.1.0
305  */
306 SRD_API int srd_exit(void)
307 {
308  srd_dbg("Exiting libsigrokdecode.");
309 
310  for (GSList *l = sessions; l; l = l->next)
311  srd_session_destroy(l->data);
312 
314  g_slist_free_full(searchpaths, g_free);
315  searchpaths = NULL;
316 
317  /*
318  * Acquire the GIL, otherwise Py_Finalize() might have issues.
319  * Ignore the return value, we don't need it here.
320  */
321  if (Py_IsInitialized())
322  (void)PyGILState_Ensure();
323 
324  /* Py_Finalize() returns void, any finalization errors are ignored. */
325  Py_Finalize();
326 
327  /* Note: No need to release the GIL since Python is shut down now. */
328 
329  max_session_id = -1;
330 
331  return SRD_OK;
332 }
333 
334 /**
335  * Add an additional search directory for the protocol decoders.
336  *
337  * The specified directory is prepended (not appended!) to Python's sys.path,
338  * in order to search for sigrok protocol decoders in the specified
339  * directories first, and in the generic Python module directories (and in
340  * the current working directory) last. This avoids conflicts if there are
341  * Python modules which have the same name as a sigrok protocol decoder in
342  * sys.path or in the current working directory.
343  *
344  * @param path Path to the directory containing protocol decoders which shall
345  * be added to the Python sys.path, or NULL.
346  *
347  * @return SRD_OK upon success, a (negative) error code otherwise.
348  *
349  * @private
350  *
351  * @since 0.1.0
352  */
353 SRD_PRIV int srd_decoder_searchpath_add(const char *path)
354 {
355  PyObject *py_cur_path, *py_item;
356  PyGILState_STATE gstate;
357 
358  srd_dbg("Adding '%s' to module path.", path);
359 
360  gstate = PyGILState_Ensure();
361 
362  py_cur_path = PySys_GetObject("path");
363  if (!py_cur_path)
364  goto err;
365 
366  py_item = PyUnicode_FromString(path);
367  if (!py_item) {
368  srd_exception_catch("Failed to create Unicode object");
369  goto err;
370  }
371  if (PyList_Insert(py_cur_path, 0, py_item) < 0) {
372  srd_exception_catch("Failed to insert path element");
373  Py_DECREF(py_item);
374  goto err;
375  }
376  Py_DECREF(py_item);
377 
378  PyGILState_Release(gstate);
379 
380  searchpaths = g_slist_prepend(searchpaths, g_strdup(path));
381 
382  return SRD_OK;
383 
384 err:
385  PyGILState_Release(gstate);
386 
387  return SRD_ERR_PYTHON;
388 }
389 
390 /**
391  * Return the list of protocol decoder search paths.
392  *
393  * @return The list of search paths used when loading protocol decoders.
394  *
395  * @since 0.5.1
396  */
398 {
399  return g_slist_copy_deep(searchpaths, (GCopyFunc)g_strdup, NULL);
400 }
401 
402 /** @} */
No error.
int srd_init(const char *path)
Initialize libsigrokdecode.
Definition: srd.c:218
#define SRD_API
#define SRD_PACKAGE_VERSION_STRING
The libsigrokdecode package version ("major.minor.micro") as string.
Definition: version.h:51
Generic/unspecified error.
int srd_decoder_unload_all(void)
Unload all loaded protocol decoders.
Definition: decoder.c:1078
GSList * srd_buildinfo_libs_get(void)
Definition: version.c:149
int srd_session_destroy(struct srd_session *sess)
Destroy a decoding session.
Definition: session.c:331
The public libsigrokdecode header file to be used by frontends.
GSList * srd_searchpaths_get(void)
Return the list of protocol decoder search paths.
Definition: srd.c:397
#define SRD_PRIV
char * srd_buildinfo_host_get(void)
Definition: version.c:168
const char * srd_lib_version_string_get(void)
Get the libsigrokdecode library version number as a string.
Definition: version.c:144
#define SRD_LIB_VERSION_STRING
The libsigrokdecode libtool version ("current:revision:age") as string.
Definition: version.h:67
const char * srd_package_version_string_get(void)
Get the libsigrokdecode package version number as a string.
Definition: version.c:95
Python C API error.
int srd_exit(void)
Shutdown libsigrokdecode.
Definition: srd.c:306