]> sigrok.org Git - libsigrokdecode.git/blame - srd.c
avr_isp: Add more parts
[libsigrokdecode.git] / srd.c
CommitLineData
190b71cf
BV
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
36784362 21#include <config.h>
f6c7eade
MC
22#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23#include "libsigrokdecode.h"
190b71cf
BV
24#include <glib.h>
25
26/** @cond PRIVATE */
27
ea81b49a
BV
28/* Python module search paths */
29SRD_PRIV GSList *searchpaths = NULL;
30
190b71cf 31/* session.c */
23a29d24
UH
32extern SRD_PRIV GSList *sessions;
33extern SRD_PRIV int max_session_id;
190b71cf 34
190b71cf
BV
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 *
3b884e85 65 * There is one mailing list for sigrok/libsigrokdecode: <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-devel">sigrok-devel</a>.
190b71cf
BV
66 *
67 * @section sec_irc IRC
68 *
69 * You can find the sigrok developers in the
0963cf62
GS
70 * <a href="ircs://irc.libera.chat/#sigrok">\#sigrok</a>
71 * IRC channel on Libera.Chat.
190b71cf
BV
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
40c6ac1d
DE
98static 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
7969d803 108 ret = SRD_OK; /* Just ignore non-existing directory. */
40c6ac1d
DE
109
110 g_free(decdir);
111
112 return ret;
113}
114
cdb49509
UH
115static 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).",
123 SRD_PACKAGE_VERSION_STRING, SRD_LIB_VERSION_STRING,
124 srd_package_version_string_get(), srd_lib_version_string_get());
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
a2860c19
UH
147static int print_searchpaths(void)
148{
149 PyObject *py_paths, *py_path, *py_bytes;
150 PyGILState_STATE gstate;
151 GString *s;
3481b5f7 152 GSList *l;
a2860c19
UH
153 int i;
154
3481b5f7
UH
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
a2860c19
UH
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);
3481b5f7 170 g_string_append(s, "Python system search paths:\n");
a2860c19
UH
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));
07560450 175 Py_DECREF(py_bytes);
a2860c19
UH
176 }
177 s->str[s->len - 1] = '\0';
178 srd_dbg("%s", s->str);
179 g_string_free(s, TRUE);
180
181 PyGILState_Release(gstate);
182
183 return SRD_OK;
184
185err:
3481b5f7 186 srd_err("Unable to query Python system search paths.");
a2860c19
UH
187 PyGILState_Release(gstate);
188
189 return SRD_ERR_PYTHON;
190}
191
190b71cf
BV
192/**
193 * Initialize libsigrokdecode.
194 *
195 * This initializes the Python interpreter, and creates and initializes
196 * a "sigrokdecode" Python module.
197 *
198 * Then, it searches for sigrok protocol decoders in the "decoders"
199 * subdirectory of the the libsigrokdecode installation directory.
200 * All decoders that are found are loaded into memory and added to an
201 * internal list of decoders, which can be queried via srd_decoder_list().
202 *
203 * The caller is responsible for calling the clean-up function srd_exit(),
204 * which will properly shut down libsigrokdecode and free its allocated memory.
205 *
206 * Multiple calls to srd_init(), without calling srd_exit() in between,
207 * are not allowed.
208 *
209 * @param path Path to an extra directory containing protocol decoders
210 * which will be added to the Python sys.path. May be NULL.
211 *
212 * @return SRD_OK upon success, a (negative) error code otherwise.
213 * Upon Python errors, SRD_ERR_PYTHON is returned. If the decoders
214 * directory cannot be accessed, SRD_ERR_DECODERS_DIR is returned.
215 * If not enough memory could be allocated, SRD_ERR_MALLOC is returned.
216 *
217 * @since 0.1.0
218 */
219SRD_API int srd_init(const char *path)
220{
40c6ac1d
DE
221 const char *const *sys_datadirs;
222 const char *env_path;
223 size_t i;
190b71cf 224 int ret;
190b71cf
BV
225
226 if (max_session_id != -1) {
227 srd_err("libsigrokdecode is already initialized.");
228 return SRD_ERR;
229 }
230
cdb49509
UH
231 print_versions();
232
190b71cf
BV
233 srd_dbg("Initializing libsigrokdecode.");
234
235 /* Add our own module to the list of built-in modules. */
236 PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
237
238 /* Initialize the Python interpreter. */
45883c6b 239 Py_InitializeEx(0);
190b71cf 240
40c6ac1d
DE
241 /* Locations relative to the XDG system data directories. */
242 sys_datadirs = g_get_system_data_dirs();
243 for (i = g_strv_length((char **)sys_datadirs); i > 0; i--) {
7969d803 244 ret = searchpath_add_xdg_dir(sys_datadirs[i - 1]);
40c6ac1d
DE
245 if (ret != SRD_OK) {
246 Py_Finalize();
247 return ret;
248 }
249 }
250#ifdef DECODERS_DIR
251 /* Hardcoded decoders install location, if defined. */
190b71cf
BV
252 if ((ret = srd_decoder_searchpath_add(DECODERS_DIR)) != SRD_OK) {
253 Py_Finalize();
254 return ret;
255 }
40c6ac1d
DE
256#endif
257 /* Location relative to the XDG user data directory. */
258 ret = searchpath_add_xdg_dir(g_get_user_data_dir());
259 if (ret != SRD_OK) {
260 Py_Finalize();
261 return ret;
262 }
190b71cf
BV
263
264 /* Path specified by the user. */
265 if (path) {
266 if ((ret = srd_decoder_searchpath_add(path)) != SRD_OK) {
267 Py_Finalize();
268 return ret;
269 }
270 }
271
272 /* Environment variable overrides everything, for debugging. */
ec5fc441
GS
273 /*
274 * TODO
275 * Is the comment still applicable and correct or up to date?
276 * This implementation adds paths which were specified by the
277 * env var. Which can shadow files in other locations, or can
278 * extend the set of available decoders. Which need not only
279 * serve for development, it is as beneficial to regular users.
280 * Without shadowing all other files still are found.
281 */
40c6ac1d 282 if ((env_path = g_getenv("SIGROKDECODE_DIR"))) {
190b71cf
BV
283 if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) {
284 Py_Finalize();
285 return ret;
286 }
287 }
1105c425
GS
288 env_path = g_getenv("SIGROKDECODE_PATH");
289 if (env_path) {
290 char **dir_list, **dir_iter, *dir_item;
291 dir_list = g_strsplit(env_path, G_SEARCHPATH_SEPARATOR_S, 0);
292 for (dir_iter = dir_list; *dir_iter; dir_iter++) {
293 dir_item = *dir_iter;
294 if (!dir_item || !*dir_item)
295 continue;
296 ret = srd_decoder_searchpath_add(dir_item);
297 if (ret != SRD_OK) {
298 Py_Finalize();
299 return ret;
300 }
301 }
302 g_strfreev(dir_list);
303 }
190b71cf 304
0c35c5c5
SS
305#if PY_VERSION_HEX < 0x03090000
306 /*
307 * Initialize and acquire the Python GIL. In Python 3.7+ this
308 * will be done implicitly as part of the Py_InitializeEx()
309 * call above. PyEval_InitThreads() was deprecated in 3.9.
310 */
514b2edc 311 PyEval_InitThreads();
0c35c5c5 312#endif
514b2edc
UH
313
314 /* Release the GIL (ignore return value, we don't need it here). */
315 (void)PyEval_SaveThread();
316
190b71cf
BV
317 max_session_id = 0;
318
a2860c19
UH
319 print_searchpaths();
320
190b71cf
BV
321 return SRD_OK;
322}
323
611a7340
JB
324static void srd_session_destroy_cb(void *arg, void *ignored)
325{
326 (void)ignored; // Prevent unused warning
327 srd_session_destroy((struct srd_session *)arg);
328}
329
190b71cf
BV
330/**
331 * Shutdown libsigrokdecode.
332 *
333 * This frees all the memory allocated for protocol decoders and shuts down
334 * the Python interpreter.
335 *
336 * This function should only be called if there was a (successful!) invocation
337 * of srd_init() before. Calling this function multiple times in a row, without
338 * any successful srd_init() calls in between, is not allowed.
339 *
340 * @return SRD_OK upon success, a (negative) error code otherwise.
341 *
342 * @since 0.1.0
343 */
344SRD_API int srd_exit(void)
345{
190b71cf
BV
346 srd_dbg("Exiting libsigrokdecode.");
347
611a7340
JB
348 g_slist_foreach(sessions, srd_session_destroy_cb, NULL);
349 g_slist_free(sessions);
350 sessions = NULL;
190b71cf
BV
351
352 srd_decoder_unload_all();
ea81b49a
BV
353 g_slist_free_full(searchpaths, g_free);
354 searchpaths = NULL;
190b71cf 355
514b2edc
UH
356 /*
357 * Acquire the GIL, otherwise Py_Finalize() might have issues.
358 * Ignore the return value, we don't need it here.
359 */
2071c4d3
UH
360 if (Py_IsInitialized())
361 (void)PyGILState_Ensure();
514b2edc 362
190b71cf
BV
363 /* Py_Finalize() returns void, any finalization errors are ignored. */
364 Py_Finalize();
365
514b2edc
UH
366 /* Note: No need to release the GIL since Python is shut down now. */
367
190b71cf
BV
368 max_session_id = -1;
369
370 return SRD_OK;
371}
372
373/**
374 * Add an additional search directory for the protocol decoders.
375 *
376 * The specified directory is prepended (not appended!) to Python's sys.path,
377 * in order to search for sigrok protocol decoders in the specified
378 * directories first, and in the generic Python module directories (and in
379 * the current working directory) last. This avoids conflicts if there are
380 * Python modules which have the same name as a sigrok protocol decoder in
381 * sys.path or in the current working directory.
382 *
383 * @param path Path to the directory containing protocol decoders which shall
384 * be added to the Python sys.path, or NULL.
385 *
386 * @return SRD_OK upon success, a (negative) error code otherwise.
387 *
388 * @private
190b71cf
BV
389 */
390SRD_PRIV int srd_decoder_searchpath_add(const char *path)
391{
392 PyObject *py_cur_path, *py_item;
514b2edc 393 PyGILState_STATE gstate;
190b71cf
BV
394
395 srd_dbg("Adding '%s' to module path.", path);
396
514b2edc
UH
397 gstate = PyGILState_Ensure();
398
190b71cf 399 py_cur_path = PySys_GetObject("path");
d8d40959 400 if (!py_cur_path)
514b2edc 401 goto err;
d8d40959
DE
402
403 py_item = PyUnicode_FromString(path);
404 if (!py_item) {
405 srd_exception_catch("Failed to create Unicode object");
514b2edc 406 goto err;
d8d40959
DE
407 }
408 if (PyList_Insert(py_cur_path, 0, py_item) < 0) {
409 srd_exception_catch("Failed to insert path element");
410 Py_DECREF(py_item);
514b2edc 411 goto err;
190b71cf 412 }
d8d40959 413 Py_DECREF(py_item);
190b71cf 414
514b2edc
UH
415 PyGILState_Release(gstate);
416
d8d40959 417 searchpaths = g_slist_prepend(searchpaths, g_strdup(path));
190b71cf
BV
418
419 return SRD_OK;
514b2edc
UH
420
421err:
422 PyGILState_Release(gstate);
423
424 return SRD_ERR_PYTHON;
190b71cf
BV
425}
426
4fde4be1
UH
427/**
428 * Return the list of protocol decoder search paths.
429 *
430 * @return The list of search paths used when loading protocol decoders.
431 *
432 * @since 0.5.1
433 */
434SRD_API GSList *srd_searchpaths_get(void)
435{
23db4503
UH
436 GSList *paths = NULL;
437
438 for (GSList *l = searchpaths; l; l = l->next)
439 paths = g_slist_append(paths, g_strdup(l->data));
440
441 return paths;
4fde4be1
UH
442}
443
190b71cf 444/** @} */