Skip to content

Instantly share code, notes, and snippets.

@trevor-vaughan
Created June 20, 2017 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trevor-vaughan/8f28ac8d908b3379fa9cee97b910ac54 to your computer and use it in GitHub Desktop.
Save trevor-vaughan/8f28ac8d908b3379fa9cee97b910ac54 to your computer and use it in GitHub Desktop.
Get the largest stack size and application size of running apps. Written to get info for setting limits for Stack Clash
#!/usr/bin/ruby
# Get application and stack size of an application in a form useful for using
# with pam_limits
require 'json'
PAGE_SIZE = %x(getconf PAGESIZE).to_i
UID = Process.uid
mem_info = Hash.new
max_stack_entry = nil
max_stack_size = 0.0
max_address_entry = nil
max_address_size = 0.0
Dir.glob('/proc/*').each do |dir|
pid = File.basename(dir)
next unless pid =~ /^\d+$/
next unless File.directory?(dir)
unless UID == 0
next unless UID == File.stat("#{dir}/maps").uid
end
command = %x(cat #{dir}/comm).strip
mapfile = %x(cat #{dir}/maps)
address_size = (%x(ps -ho sz #{pid}).strip.to_i * PAGE_SIZE)
stack_size = 0.0
mapfile.each_line do |map|
info = map.split(/\s+/)
mem_start, mem_end = info.first.split('-').map{|x| x.to_i(16)}
mem_size = mem_end - mem_start
path = info.last
if path =~ /\[stack/
stack_size += mem_size
end
end
mem_info[command] ||= Hash.new
mem_info[command][pid] = {
:address_size => {
:b => address_size,
:kb => address_size/1024,
:mb => address_size/(1024**2),
:gb => address_size/(1024**3)
},
:stack_size => {
:b => stack_size,
:kb => stack_size/1024,
:mb => stack_size/(1024**2),
:gb => stack_size/(1024**3)
}
}
if address_size >= max_address_size
max_address_size = address_size
max_address_entry = {
command => mem_info[command]
}
end
if stack_size >= max_stack_size
max_stack_size = stack_size
max_stack_entry = {
command => mem_info[command]
}
end
end
#puts JSON.pretty_generate(mem_info)
puts 'Largest App: '
puts JSON.pretty_generate(max_address_entry)
puts 'Largest Stack: '
puts JSON.pretty_generate(max_stack_entry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment