Skip to content

Commit

Permalink
Reject encodings determined at runtime as source code encodings
Browse files Browse the repository at this point in the history
The encodings determined at runtime are affected by the runtime
environment, such as the OS and locale, while the file contents are
not.
  • Loading branch information
nobu committed Jan 11, 2024
1 parent 0480c07 commit 3d3bc02
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
11 changes: 10 additions & 1 deletion parse.y
Original file line number Diff line number Diff line change
Expand Up @@ -9477,11 +9477,20 @@ parser_encode_length(struct parser_params *p, const char *name, long len)
static void
parser_set_encode(struct parser_params *p, const char *name)
{
int idx = rb_enc_find_index(name);
rb_encoding *enc;
VALUE excargs[3];

const char *wrong = 0;
switch (*name) {
case 'e': case 'E': wrong = "external"; break;
case 'i': case 'I': wrong = "internal"; break;
case 'f': case 'F': wrong = "filesystem"; break;
case 'l': case 'L': wrong = "locale"; break;
}
if (wrong && STRCASECMP(name, wrong) == 0) goto unknown;
int idx = rb_enc_find_index(name);
if (idx < 0) {
unknown:
excargs[1] = rb_sprintf("unknown encoding name: %s", name);
error:
excargs[0] = rb_eArgError;
Expand Down
28 changes: 28 additions & 0 deletions test/ruby/test_parse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,34 @@ def test_magic_comment
END
end
assert_equal(__ENCODING__, x)

assert_raise(ArgumentError) do
EnvUtil.with_default_external(Encoding::US_ASCII) {eval <<-END, nil, __FILE__, __LINE__+1}
# coding = external
x = __ENCODING__
END
end

assert_raise(ArgumentError) do
EnvUtil.with_default_internal(Encoding::US_ASCII) {eval <<-END, nil, __FILE__, __LINE__+1}
# coding = internal
x = __ENCODING__
END
end

assert_raise(ArgumentError) do
eval <<-END, nil, __FILE__, __LINE__+1
# coding = filesystem
x = __ENCODING__
END
end

assert_raise(ArgumentError) do
eval <<-END, nil, __FILE__, __LINE__+1
# coding = locale
x = __ENCODING__
END
end
end

def test_utf8_bom
Expand Down

0 comments on commit 3d3bc02

Please sign in to comment.