read_xml() leaks parser resources after malformed-XML errors (LSan, xml2 1.6.0)

Abierto
#483 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
48/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
r

Línea de trabajo

Start with src/xml2_doc.cpp, especially doc_parse_file() and doc_parse_raw(), where parsing currently calls libxml2. Read the parser cleanup and error handling there, then run the malformed XML reproducer under AddressSanitizer with leak detection enabled. Done means caught parsing errors release native parser allocations; the issue also describes regression checks for file, raw, connection, Unicode, warning, and HTML inputs.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Repeatedly reading malformed XML leaks native parser allocations even when the R errors are caught and gc() is called. The reproducer below requires only xml2, not DDIwR (where this was originally found).

Environment
  • Linux x86_64, R 4.5.3, GCC 13.3
  • xml2 1.6.0, libxml2 2.9.14
  • AddressSanitizer preloaded with detect_leaks=1
  • The candidate patched xml2 build additionally uses -fsanitize=address,undefined,float-cast-overflow.
Reproducer

Save as reproduce-parser-leak.R and run in a fresh R process:

library(xml2)
cat("xml2:", as.character(packageVersion("xml2")), "libxml2:", as.character(xml2:::libxml2_version()), "\n")
local({
    path <- tempfile(fileext = ".xml")
    on.exit(unlink(path), add = TRUE)
    writeLines("<root><child></root>", path)

    for (iteration in seq_len(100L)) {
        result <- tryCatch(read_xml(path), error = identity)
        stopifnot(inherits(result, "error"))
    }
})
gc()
gc()

Example invocation in the tested Linux environment, with the appropriate xml2 library first in R_LIBS:

R_HOME=/usr/lib/R \
R_LIBS=/path/to/library \
LD_PRELOAD="$(gcc -print-file-name=libasan.so)" \
ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 \
UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 \
/usr/lib/R/bin/exec/R --vanilla --slave -f reproduce-parser-leak.R
Actual and expected results

With unpatched xml2 1.6.0, all 100 expected R errors are caught, but LeakSanitizer exits with status 1. An abbreviated allocation trace is:

Direct leak of 74448 byte(s) in 99 object(s) allocated from:
    #0 0x7fffff1ef9c7 in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
    #1 0x7ffff6281cb4 in xmlReadFile (/lib/x86_64-linux-gnu/libxml2.so.2+0x5bcb4) (BuildId: fc25d42e66a1d1da059ad4124c6660cc09f805e1)
    #2 0x7ffff640f444 in doc_parse_file /tmp/RtmpKIfwNx/R.INSTALLc634beaa52/xml2/src/xml2_doc.cpp:202
    #3 0x7ffffed82d01  (/lib/libR.so+0x104d01) (BuildId: 1fbe1b150ea0210f6c30b1745080e7d09cc074b2)
...
SUMMARY: AddressSanitizer: 4784274 byte(s) leaked in 3465 allocation(s).

The expected result is an R parsing error with native parser resources released. Allocation counts may vary with platform and conservative reachability at process exit.

Analysis and candidate fix

Source analysis suggests that raising an R error from the native structured-error callback exits libxml2 before its parser cleanup finishes. The candidate patch below captures parser diagnostics, returns from parsing before raising R conditions, and uses explicit parser-context ownership and R_UnwindProtect cleanup. Merely freeing the context during an immediate callback jump was insufficient for some temporary allocations.

With the candidate patch, the same reproducer exits 0 with no ASan/UBSan/LeakSanitizer diagnostics. Additional local regression checks cover malformed file/raw/connection inputs, valid Unicode XML, warnings promoted to errors, and HTML parsing.

The patch is against the CRAN xml2 1.6.0 source archive (SHA-256 b0660edab0a839866a0cccd44721c54d497000fd6577a25106a33280318bf579).

Candidate patch: xml2-1.6.0-parser-cleanup.patch
--- a/src/xml2_doc.cpp
+++ b/src/xml2_doc.cpp
@@ -6,6 +6,7 @@
 #include "xml2_types.h"
 #include "xml2_utils.h"
 #include <cstring>
+#include <cstdlib>
 
 // [[export]]
 extern "C" SEXP  xml_parse_options_() {
@@ -180,37 +181,160 @@
 #undef HAS_IGNORE_ENC
 }
 
+// Defer R conditions until libxml2 has released its temporary parser buffers.
+struct ParseError {
+  xmlError error;
+  ParseError* next;
+};
+
+struct ParseContext {
+  xmlParserCtxtPtr parser;
+  SEXP output;
+  const char* path;
+  const char* bytes;
+  int size;
+  const char* encoding;
+  const char* base_url;
+  bool as_html;
+  int options;
+  ParseError* errors;
+  ParseError* last_error;
+  bool out_of_memory;
+};
+
+static void release_parser(ParseContext* context) {
+  if (context->parser == NULL) {
+    return;
+  }
+  if (context->parser->myDoc != NULL) {
+    xmlFreeDoc(context->parser->myDoc);
+    context->parser->myDoc = NULL;
+  }
+  if (context->as_html) {
+    htmlFreeParserCtxt(context->parser);
+  } else {
+    xmlFreeParserCtxt(context->parser);
+  }
+  context->parser = NULL;
+}
+
+static void cleanup_parse(void* data, Rboolean) {
+  ParseContext* context = static_cast<ParseContext*>(data);
+  release_parser(context);
+  while (context->errors != NULL) {
+    ParseError* error = context->errors;
+    context->errors = error->next;
+    xmlResetError(&error->error);
+    free(error);
+  }
+}
+
+#if LIBXML_VERSION >= 21200
+static void capture_parse_error(void* data, const xmlError* error) {
+#else
+static void capture_parse_error(void* data, xmlError* error) {
+#endif
+#if LIBXML_VERSION >= 21300
+  ParseContext* context = static_cast<ParseContext*>(data);
+#else
+  xmlParserCtxtPtr parser = static_cast<xmlParserCtxtPtr>(data);
+  ParseContext* context = static_cast<ParseContext*>(parser->_private);
+#endif
+  ParseError* record = static_cast<ParseError*>(calloc(1, sizeof(ParseError)));
+  if (record == NULL || xmlCopyError(const_cast<xmlError*>(error), &record->error) != 0) {
+    if (record != NULL) {
+      xmlResetError(&record->error);
+      free(record);
+    }
+    context->out_of_memory = true;
+    xmlStopParser(context->parser);
+    return;
+  }
+  if (context->last_error == NULL) {
+    context->errors = record;
+  } else {
+    context->last_error->next = record;
+  }
+  context->last_error = record;
+  if (error->level > XML_ERR_ERROR) {
+    xmlStopParser(context->parser);
+  }
+}
+
+static SEXP parse_document(void* data) {
+  ParseContext* context = static_cast<ParseContext*>(data);
+  context->parser = context->as_html ? htmlNewParserCtxt() : xmlNewParserCtxt();
+  if (context->parser == NULL) {
+    Rf_error("Failed to allocate XML parser context");
+  }
+
+#if LIBXML_VERSION >= 21300
+  xmlCtxtSetErrorHandler(context->parser, capture_parse_error, context);
+#else
+  context->parser->_private = context;
+  context->parser->sax->serror = capture_parse_error;
+#endif
+
+  xmlDoc* document;
+  if (context->path != NULL) {
+    document = context->as_html ?
+      htmlCtxtReadFile(context->parser, context->path, context->encoding, context->options) :
+      xmlCtxtReadFile(context->parser, context->path, context->encoding, context->options);
+  } else {
+    document = context->as_html ?
+      htmlCtxtReadMemory(context->parser, context->bytes, context->size,
+        context->base_url, context->encoding, context->options) :
+      xmlCtxtReadMemory(context->parser, context->bytes, context->size,
+        context->base_url, context->encoding, context->options);
+  }
+
+  // The R pointer owns any returned document before warnings can become errors.
+  R_SetExternalPtrAddr(context->output, document);
+  context->parser->myDoc = NULL;
+  release_parser(context);
+
+  if (context->out_of_memory) {
+    Rf_error("Failed to allocate XML parser diagnostic");
+  }
+  for (ParseError* error = context->errors; error != NULL; error = error->next) {
+    char* message = error->error.message;
+    if (message == NULL) {
+      message = const_cast<char*>("XML parsing failed");
+    } else {
+      size_t length = strlen(message);
+      if (length > 0 && message[length - 1] == '\n') {
+        message[length - 1] = '\0';
+      }
+    }
+    if (error->error.level <= XML_ERR_ERROR) {
+      Rf_warning("%s [%i]", message, error->error.code);
+    } else {
+      Rf_error("%s [%i]", message, error->error.code);
+    }
+  }
+  if (document == NULL) {
+    if (context->path != NULL) {
+      Rf_error("Failed to parse %s", context->path);
+    }
+    Rf_error("Failed to parse text");
+  }
+  return context->output;
+}
+
 // [[export]]
 extern "C" SEXP doc_parse_file(
     SEXP path_sxp,
     SEXP encoding_sxp,
     SEXP as_html_sxp,
     SEXP options_sxp) {
-
-  const char* path = CHAR(STRING_ELT(path_sxp, 0));
   const char* encoding = CHAR(STRING_ELT(encoding_sxp, 0));
-  bool as_html = LOGICAL(as_html_sxp)[0];
-  int options = INTEGER(options_sxp)[0];
-  xmlDoc* pDoc;
-  if (as_html) {
-    pDoc = htmlReadFile(
-      path,
-      encoding[0] == '\0' ? NULL : encoding,
-      options
-    );
-  } else {
-    pDoc = xmlReadFile(
-      path,
-      encoding[0] == '\0' ? NULL : encoding,
-      options
-    );
-  }
-
-  if (pDoc == NULL) {
-    Rf_error("Failed to parse %s", path);
-  }
-
-  return SEXP(XPtrDoc(pDoc));
+  SEXP output = PROTECT(SEXP(XPtrDoc(static_cast<xmlDoc*>(NULL))));
+  ParseContext context = {NULL, output, CHAR(STRING_ELT(path_sxp, 0)), NULL, 0,
+    encoding[0] == '\0' ? NULL : encoding, NULL,
+    static_cast<bool>(LOGICAL(as_html_sxp)[0]), INTEGER(options_sxp)[0], NULL, NULL, false};
+  R_UnwindProtect(parse_document, &context, cleanup_parse, &context, NULL);
+  UNPROTECT(1);
+  return output;
 }
 
 // [[export]]
@@ -220,39 +344,16 @@
     SEXP base_url_sxp,
     SEXP as_html_sxp,
     SEXP options_sxp) {
-
-  BEGIN_CPP
-  std::string encoding(CHAR(STRING_ELT(encoding_sxp, 0)));
-  std::string base_url(CHAR(STRING_ELT(base_url_sxp, 0)));
-  bool as_html = LOGICAL(as_html_sxp)[0];
-  int options = INTEGER(options_sxp)[0];
-
-  xmlDoc* pDoc;
-  if (as_html) {
-    pDoc = htmlReadMemory(
-      (const char *) RAW(x),
-      Rf_length(x),
-      base_url == "" ? NULL : base_url.c_str(),
-      encoding == "" ? NULL : encoding.c_str(),
-      options
-    );
-  } else {
-    pDoc = xmlReadMemory(
-      (const char *) RAW(x),
-      Rf_length(x),
-      base_url == "" ? NULL : base_url.c_str(),
-      encoding == "" ? NULL : encoding.c_str(),
-      options
-    );
-  }
-
-  if (pDoc == NULL) {
-    Rf_error("Failed to parse text");
-  }
-
-  return SEXP(XPtrDoc(pDoc));
-
-  END_CPP
+  const char* encoding = CHAR(STRING_ELT(encoding_sxp, 0));
+  const char* base_url = CHAR(STRING_ELT(base_url_sxp, 0));
+  SEXP output = PROTECT(SEXP(XPtrDoc(static_cast<xmlDoc*>(NULL))));
+  ParseContext context = {NULL, output, NULL, reinterpret_cast<const char*>(RAW(x)),
+    Rf_length(x), encoding[0] == '\0' ? NULL : encoding,
+    base_url[0] == '\0' ? NULL : base_url,
+    static_cast<bool>(LOGICAL(as_html_sxp)[0]), INTEGER(options_sxp)[0], NULL, NULL, false};
+  R_UnwindProtect(parse_document, &context, cleanup_parse, &context, NULL);
+  UNPROTECT(1);
+  return output;
 }
 
 // [[export]]
Additional parser cleanup regression script
# Run with the patched xml2 library first in R_LIBS. Under Linux ASan, preload
# libasan and enable ASAN_OPTIONS=detect_leaks=1 to verify native cleanup.
local({
    if (requireNamespace("DDIwR", quietly = TRUE)) {
        loadNamespace("DDIwR")
    }

    path <- tempfile(fileext = ".xml")
    on.exit(unlink(path), add = TRUE)
    malformed <- c(
        "<root><child></root>",
        "<root><child/></root>trailing",
        "<root attribute='unterminated>"
    )
    readers <- list(
        file = function(bytes) {
            return(xml2::read_xml(path, options = c("HUGE", "NOBLANKS")))
        },
        raw = function(bytes) {
            return(xml2::read_xml(bytes, base_url = path))
        },
        connection = function(bytes) {
            connection <- file(path, "rb")
            on.exit(close(connection), add = TRUE)

            return(xml2::read_xml(connection, base_url = path))
        }
    )

    for (iteration in seq_len(20L)) {
        for (text in malformed) {
            bytes <- charToRaw(text)
            writeBin(bytes, path)

            for (reader in readers) {
                failure <- tryCatch(reader(bytes), error = identity)
                stopifnot(inherits(failure, "error"))
                stopifnot(nzchar(conditionMessage(failure)))
            }
        }
    }

    writeBin(charToRaw('<root><child>café &amp; text</child></root>'), path)

    for (reader in readers) {
        document <- reader(readBin(path, "raw", n = file.info(path)$size))
        stopifnot(identical(xml2::xml_text(document), "café & text"))
    }

    # A warning promoted to an error must also release the active parser.
    tryCatch(withCallingHandlers(
        xml2::read_xml('<root xmlns="relative"><child/></root>'),
        warning = function(warning) {
            stop(conditionMessage(warning), call. = FALSE)
        }
    ), error = function(error) {
        invisible(NULL)
    })
    stopifnot(identical(xml2::xml_name(xml2::read_html("<p>Text</p>")), "html"))
})

gc()
gc()
cat("Parser cleanup regression checks passed.\n")

Related historical reports: #144 (closed), describing an open file after a malformed-XML error, and #102, concerning other ASan leaks. This report adds current native-memory evidence and a proposed fix.

Lenguaje dominante
R
Estrellas
227
Forks
86
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de r-lib/xml2

Todos los issues de r-lib/xml2

Issues similares

Más issues de R

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.