Skip to content

Commit 6d49eec

Browse files
committed
xml: Cleanup libxml2 parser when exiting library
When libiio is unloaded (when the client program exits), cleanup libxml2 so that memory analyzer tools like Valgrind won't detect a memory leak. Signed-off-by: Paul Cercueil <[email protected]>
1 parent ebf3c7e commit 6d49eec

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

xml.c

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,3 +478,47 @@ struct iio_context * xml_create_context_mem(const char *xml, size_t len)
478478
xmlFreeDoc(doc);
479479
return ctx;
480480
}
481+
482+
483+
static void cleanup_libxml2_stuff(void)
484+
{
485+
/*
486+
* This function will be called only when the libiio library is
487+
* unloaded (e.g. when the program exits).
488+
*
489+
* Cleanup libxml2 so that memory analyzer tools like Valgrind won't
490+
* detect a memory leak.
491+
*/
492+
xmlCleanupParser();
493+
xmlMemoryDump();
494+
}
495+
496+
#if defined(_MSC_BUILD)
497+
#pragma section(".CRT$XCU", read)
498+
#define __CONSTRUCTOR(f, p) \
499+
static void f(void); \
500+
__declspec(allocate(".CRT$XCU")) void (*f##_)(void) = f; \
501+
__pragma(comment(linker,"/include:" p #f "_")) \
502+
static void f(void)
503+
#ifdef _WIN64
504+
#define _CONSTRUCTOR(f) __CONSTRUCTOR(f, "")
505+
#else
506+
#define _CONSTRUCTOR(f) __CONSTRUCTOR(f, "_")
507+
#endif
508+
#elif defined(__GNUC__)
509+
#define _CONSTRUCTOR(f) static void __attribute__((constructor)) f(void)
510+
#else
511+
#define _CONSTRUCTOR(f) static void f(void)
512+
#endif
513+
514+
_CONSTRUCTOR(initialize)
515+
{
516+
/*
517+
* When the library loads, register our destructor.
518+
* Do it here and not in the context creation function,
519+
* as it could otherwise end up registering the destructor
520+
* many times.
521+
*/
522+
atexit(cleanup_libxml2_stuff);
523+
}
524+
#undef _CONSTRUCTOR

0 commit comments

Comments
 (0)