From f0d8a0a2bfa7026423795f96b40d4d81094f8788 Mon Sep 17 00:00:00 2001 From: Peter Zhu Date: Mon, 22 Jul 2024 09:53:56 -0400 Subject: [PATCH] Fix memory leak in parser when loading non-ASCII file When loading a non-ASCII compatible file, an error is raised which causes memory leak. For example: require "tempfile" Tempfile.create do |f| f.write("# -*- coding: UTF-16BE -*-") f.flush 10.times do 20_000.times do begin load(f.path) rescue end end puts `ps -o rss= -p #{$$}` end end Before: 33904 49072 64528 79216 94576 109504 124768 139536 154928 170256 After: 19568 21296 21664 21728 22192 22256 22416 22272 22272 22272 --- parse.y | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/parse.y b/parse.y index ee454c766b..37f30a4881 100644 --- a/parse.y +++ b/parse.y @@ -9417,6 +9417,10 @@ parser_set_encode(struct parser_params *p, const char *name) rb_ary_unshift(excargs[2], rb_sprintf("%"PRIsVALUE":%d", p->ruby_sourcefile_string, p->ruby_sourceline)); VALUE exc = rb_make_exception(3, excargs); ruby_show_error_line(p, exc, &(YYLTYPE)RUBY_INIT_YYLLOC(), p->ruby_sourceline, p->lex.lastline); + + rb_ast_free(p->ast); + p->ast = NULL; + rb_exc_raise(exc); } enc = rb_enc_from_index(idx);