From 0bde50b4e56beb936d9e00ddad0767c73aefb4d5 Mon Sep 17 00:00:00 2001 From: Quinton Miller Date: Wed, 8 Nov 2023 18:15:32 +0800 Subject: [PATCH] Check for invalid integers in compiler's CLI (#13959) --- src/compiler/crystal/command.cr | 5 +++-- src/compiler/crystal/command/playground.cr | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/compiler/crystal/command.cr b/src/compiler/crystal/command.cr index 8341b41d9f3b..2c5492445e0b 100644 --- a/src/compiler/crystal/command.cr +++ b/src/compiler/crystal/command.cr @@ -503,7 +503,8 @@ class Crystal::Command compiler.release! end opts.on("-O LEVEL", "Optimization mode: 0 (default), 1, 2, 3") do |level| - compiler.optimization_mode = Compiler::OptimizationMode.from_value?(level.to_i) || raise Error.new("Unknown optimization mode #{level}") + optimization_mode = level.to_i?.try { |v| Compiler::OptimizationMode.from_value?(v) } + compiler.optimization_mode = optimization_mode || raise Error.new("Invalid optimization mode: #{level}") end end @@ -524,7 +525,7 @@ class Crystal::Command compiler.single_module = true end opts.on("--threads NUM", "Maximum number of threads to use") do |n_threads| - compiler.n_threads = n_threads.to_i + compiler.n_threads = n_threads.to_i? || raise Error.new("Invalid thread count: #{n_threads}") end unless run opts.on("--target TRIPLE", "Target triple") do |triple| diff --git a/src/compiler/crystal/command/playground.cr b/src/compiler/crystal/command/playground.cr index 5869dee9a0a2..b7a2666a1a5a 100644 --- a/src/compiler/crystal/command/playground.cr +++ b/src/compiler/crystal/command/playground.cr @@ -11,7 +11,9 @@ class Crystal::Command opts.banner = "Usage: crystal play [options] [file]\n\nOptions:" opts.on("-p PORT", "--port PORT", "Runs the playground on the specified port") do |port| - server.port = port.to_i + port = port.to_i? + raise Error.new("Invalid port number: #{port}") unless port && Socket::IPAddress.valid_port?(port) + server.port = port end opts.on("-b HOST", "--binding HOST", "Binds the playground to the specified IP") do |host|