Mortal and immortal symbols in Ruby

Symbols are now garbage collected.. or not

Tech - RubyCademy
Aug 20, 2020 · 3 min read

In this article, we’re going to explore the following topics:

  • symbols are unique
  • symbols since Ruby 2.2
  • exploiting a security breach using symbols

Please allow me to introduce here the platform that helped me to learn a big part of my knowledge about Ruby. Indeed, Pluralsight is an amazing platform.

With 50+ courses that cover various topics on Ruby and Ruby on Rails, it’s the best way to take your knowledge to the next level!

Try it for free 👇😉

Thank you for your time!

Symbols are unique

A symbol is a unique instance of the Symbol class which is generally used for identifying a specific resource. A resource can be a method, a variable, a hash key, a state, etc..

A symbol is unique because only one instance of the Symbol class can be created for a specific symbol in a running program

Here, we can see that the :pending symbol is only created once as the two calls to :pending.object_id return the same object identifier. Symbols are often compared to strings. But the main difference between them relies on the fact that a new String object is created for each created string — even if they’re identical

Now that we’re more familiar with symbols, let’s have a look to the changes provided by Ruby 2.2.

Symbol since Ruby 2.2

Ruby 2.2 introduced the notion of mortal/immortal symbols. Let’s have a look to the differences between these 2 concepts.

Immortal symbols are symbols that’ll never be garbage collected. They’re created when your code is dynamically modified. For example:

  • defining a new method using define_method
  • setting an instance variable using set_instance_variable
  • creating a constant or variable using const_set

Mortal symbol on the other hand are eligible for garbage collection. They’re created in any other cases. For example:

  • using to_sym
  • using symbol literals
  • etc..

Ok, now that we are more familiar with these 2 concepts, let’s see how immortal symbols can generate security issues.

Security breach using immortal symbols

It might not be a good idea to create immortal symbols from user inputs. Indeed, this would allow a malicious user to mount a DoS attack against your application by flooding it with unique strings, which will cause memory to grow indefinitely until the Ruby process is killed.

Indeed, as immortal symbols are not garbage collected, creating a huge amount of them can force your Ruby process to slow down.. or to be killed.

Conclusion

The notion of mortal symbol has been introduced in Ruby 2.2 to optimize the memory usage of Ruby programs. On the other hand, immortal symbols can generate security problems and you must use them in a completely safe environment. Avoid to use them when dealing with user interaction.

Thank you for taking the time to read this article.

Voilà!

RubyCademy

E-Learning platform for Ruby and Ruby on Rails