Showing posts with label memory-management. Show all posts
Showing posts with label memory-management. Show all posts

Wednesday, August 1, 2018

Memory Error in Python 3 and Windows 64

Leave a Comment

I know Memory Error related questions have been asked before, for example here, here, here, here, or here. And the suggested solutions always are to switch to Python 3 and/or to Window 64bit, or in case of faulty code, to fix the code. However, I am already on Python 3 and Win 64. I also can see from windows task manager that I have several GB of my 64GB of RAM still available when Python throw the Memory Error.

I have about 15 date-indexed, pandas data frames each with 14000 rows and on average 5000 columns of float data, and about 40-50% NaN values, that I read in from the hard drive. I can not simply drop NaNs because different columns have NaNs at different dates. Memory Error happens when I try to concatenate them with pd.concat(). So it's not a matter of some faulty code or while loop. If I leave some of the data frames out of concatenation, Memory Error does not happen in concatenation, but then when I try to do a Scikit learn decision tree analysis on the concatenated data, it happens.

My question is how can I get Python to use all the available memory and not throw Memory Error?

Edit: screenshots added IPython interpreter screenshot (I don't have Python 2 even installed): enter image description here

System information screenshot: enter image description here

1 Answers

Answers 1

Here are some links with snippets of information from them, I hope it helps.

How to give programs more RAM

Increase your pagefile. The pagefile is a section of the hard drive that is used as RAM by the processor and is also called Virtual Memory. Although it is not as fast as RAM because it is physically located on a hard drive, increasing it can sometimes increase program performance. To access it, open your Control Panel. Click "System," then "Advanced system settings," and then "Settings" in the "Performance" tab.

How do you set the memory usage for python programs

if u wanna limit the python vm memory usage,you can try this: 1、Linux, ulimit command to limit the memory usage on python 2、you can use resource module to limit the program memory usage; if u wanna speed up ur program though giving more memory to ur application, you could try this: 1\threading, multiprocessing 2\pypy 3\pysco on only python 2.5

Assign memory application

!.Right-click MY COMPUTER 2.Properties>Advanced>Performance>Settings>Advanced 3.Under, Virtual Memory check Paging File size,(if memory serves, the rule of thumb is 1/2 of total V. Memory may be used. If you use more, the paging file fights between the app. and the OS. Hope this help's

Allocate memory process server

Because some programs need more memory than others to work, you can use the Task Manager to allocate extra memory to specific processes in order to increase performance.

Others

http://stackoverflow.com/questions/1760025/limit-python-vm-memory

http://stackoverflow.com/questions/2308091/how-to-limit-python-heap-size

Read More

Saturday, April 28, 2018

How to find out the AD Junk present in the device?

Leave a Comment

I am trying to find out the Ad Junk present (Files which are Downloaded by the AD SDK of other apps).

This is what I have been able to find out till now -

I am loading the list of all the files in the devices and them checking them and grouping them like this

if (file.getPath().toLowerCase().endsWith(".temp") ) {       //Temp Files found                                    } else if (file.getName().endsWith(".apk") && file.canWrite())  {      //Apk Files found                    } 

There are many other cleaner which find out the junk files present in the Device. Even I am trying to achieve the same. Can any one help me on how to identify whether the file is an AD Junk file or not?

1 Answers

Answers 1

You can Delete Junk File by

File[] files = getBaseContext().getCacheDir().listFiles();         for (File file : files) {     file.delete(); } 

And Put this permissions in manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
Read More

Tuesday, March 6, 2018

TensorFlow memory use while running on GPU: why does it look like not all memory is used?

Leave a Comment

This is a follow-up to my question posted here: Memory error with larger images when running convolutional neural network using TensorFlow on AWS instance g2.2xlarge

I built a CNN model in Python using TensorFlow and run it on NVIDIA GRID K520 GPU. It runs fine with 64x64 images, but produces a memory error with 128x128 images (even when input consists of only 1 image).

The error says Ran out of memory trying to allocate 2.00GiB. 2GiB is the size of my first fully-connected layer (input: 128*128*2(channels) * output: 128*128 * 4 bytes = 2.14748 GB = 2.0 GiB).

From here, I can see that GRID K520 has 8GB = 7.45GiB memory. When I start running my code, I also see the output: Total memory: 3.94GiB, Free memory: 3.91GiB.

My question is, what is the relationship between all these numbers: if there are 7.45GiB of memory on GPU, why there are only 3.94GiB of total memory and most importantly, why GPU cannot allocate 2GiB memory, which is just above half of total memory? (I am not a computer scientist, so a detailed answer would be valuable.)

Some more specific information in case it is useful: I tried using allow_growth and per_process_gpu_memory_fraction. Still get the memory error, but also some memory stats (would really appreciate if someone could explain to me these numbers):

allow_growth = True Stats:  Limit:                  3878682624 InUse:                  2148557312 MaxInUse:               2148557312 NumAllocs:                      13 MaxAllocSize:           2147483648  allow_growth = False Stats:  Limit:                  3878682624 InUse:                  3878682624 MaxInUse:               3878682624 NumAllocs:                      13 MaxAllocSize:           3877822976  per_process_gpu_memory_fraction = 0.5 allow_growth = False Stats:  Limit:                  2116026368 InUse:                      859648 MaxInUse:                   859648 NumAllocs:                      12 MaxAllocSize:               409600  per_process_gpu_memory_fraction = 0.5 allow_growth = True Stats:  Limit:                  2116026368 InUse:                     1073664 MaxInUse:                  1073664 NumAllocs:                      12 MaxAllocSize:               623616 

--------
EDIT:
--------
Minimal working example: with dummy training set of the same size as the images I input and only one fully-connected layer (full model code is here). This example works with input of size

X_train = np.random.rand(1, 64, 64, 2) Y_train = np.random.rand(1, 64, 64) 

but doesn't work with input of size

X_train = np.random.rand(1, 128, 128, 2) Y_train = np.random.rand(1, 128, 128)  

Code:

import numpy as np import tensorflow as tf   # Dummy training set: X_train = np.random.rand(1, 128, 128, 2) Y_train = np.random.rand(1, 128, 128) print('X_train.shape at input = ', X_train.shape, ", Size = ",       X_train.shape[0] * X_train.shape[1] * X_train.shape[2]       * X_train.shape[3]) print('Y_train.shape at input = ', Y_train.shape, ", Size = ",       Y_train.shape[0] * Y_train.shape[1] * Y_train.shape[2])   def create_placeholders(n_H0, n_W0):      x = tf.placeholder(tf.float32, shape=[None, n_H0, n_W0, 2], name='x')     y = tf.placeholder(tf.float32, shape=[None, n_H0, n_W0], name='y')      return x, y   def forward_propagation(x):      x_temp = tf.contrib.layers.flatten(x)  # size (n_im, n_H0 * n_W0 * 2)     n_out = np.int(x.shape[1] * x.shape[2])  # size (n_im, n_H0 * n_W0)      # FC: input size (n_im, n_H0 * n_W0 * 2), output size (n_im, n_H0 * n_W0)     FC1 = tf.contrib.layers.fully_connected(         x_temp,         n_out,         activation_fn=tf.tanh,         normalizer_fn=None,         normalizer_params=None,         weights_initializer=tf.contrib.layers.xavier_initializer(),         weights_regularizer=None,         biases_initializer=None,         biases_regularizer=None,         reuse=True,         variables_collections=None,         outputs_collections=None,         trainable=True,         scope='fc1')      # Reshape output from FC layer into array of size (n_im, n_H0, n_W0, 1):     FC_M = tf.reshape(FC1, [tf.shape(x)[0], tf.shape(x)[1], tf.shape(x)[2], 1])      return FC_M   def compute_cost(FC_M, Y):      cost = tf.square(FC_M - Y)      return cost   def model(X_train, Y_train, learning_rate=0.0001, num_epochs=100):      (m, n_H0, n_W0, _) = X_train.shape      # Create Placeholders     X, Y = create_placeholders(n_H0, n_W0)      # Build the forward propagation     DECONV = forward_propagation(X)      # Add cost function to tf graph     cost = compute_cost(DECONV, Y)      # Backpropagation     optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)      # Initialize all the variables globally     init = tf.global_variables_initializer()      # Memory config     config = tf.ConfigProto()     config.gpu_options.allow_growth = True      # Start the session to compute the tf graph     with tf.Session(config = config) as sess:          # Initialization         sess.run(init)          # Training loop         for epoch in range(num_epochs):              _, temp_cost = sess.run([optimizer, cost],                                     feed_dict={X: X_train, Y: Y_train})              print ('EPOCH = ', epoch, 'COST = ', np.mean(temp_cost))   # Finally run the model model(X_train, Y_train, learning_rate=0.00002, num_epochs=5) 

Full error:

W tensorflow/core/common_runtime/bfc_allocator.cc:274] **************************************************************************************************** W tensorflow/core/common_runtime/bfc_allocator.cc:275] Ran out of memory trying to allocate 2.00GiB.  See logs for memory state. W tensorflow/core/framework/op_kernel.cc:983] Internal: Dst tensor is not initialized. E tensorflow/core/common_runtime/executor.cc:594] Executor failed to create kernel. Internal: Dst tensor is not initialized.      [[Node: zeros = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [32768,16384] values: [0 0 0]...>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]] Traceback (most recent call last):   File "myAutomap_MinExample.py", line 99, in <module>     num_epochs=5)   File "myAutomap_MinExample.py", line 85, in model     sess.run(init)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 767, in run     run_metadata_ptr)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 965, in _run     feed_dict_string, options, run_metadata)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1015, in _do_run     target_list, options, run_metadata)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1035, in _do_call     raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InternalError: Dst tensor is not initialized.      [[Node: zeros = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [32768,16384] values: [0 0 0]...>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]  Caused by op u'zeros', defined at:   File "myAutomap_MinExample.py", line 99, in <module>     num_epochs=5)   File "myAutomap_MinExample.py", line 72, in model     optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 289, in minimize     name=name)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 403, in apply_gradients     self._create_slots(var_list)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/rmsprop.py", line 103, in _create_slots     self._zeros_slot(v, "momentum", self._name)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 647, in _zeros_slot     named_slots[var] = slot_creator.create_zeros_slot(var, op_name)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/training/slot_creator.py", line 121, in create_zeros_slot     val = array_ops.zeros(primary.get_shape().as_list(), dtype=dtype)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.py", line 1352, in zeros     output = constant(zero, shape=shape, dtype=dtype, name=name)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 103, in constant     attrs={"value": tensor_value, "dtype": dtype_value}, name=name).outputs[0]   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2327, in create_op     original_op=self._default_original_op, op_def=op_def)   File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1226, in __init__     self._traceback = _extract_stack()  InternalError (see above for traceback): Dst tensor is not initialized.      [[Node: zeros = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [32768,16384] values: [0 0 0]...>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]] 

2 Answers

Answers 1

It would be good, if you can upload your code or at least a minimal example in order to see what is going on. Just looking at these numbers, it seems allow_growth is working as it should, that is, it is only allocating the amount of memory that it actually needs (the 2.148 GiB you calculated above).

Also can you provide the full console output of the error you are getting. My guess is, that you are confusing a non fatal warning message from the TF resource allocator for the actual error that's causing your program to fail.

Is this similar to the message that you are seeing? W tensorflow/core/common_runtime/bfc_allocator.cc:217] Allocator (GPU_1_bfc) ran out of memory trying to allocate 2.55GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.

Because this is just a warning that you may ignore unless you want to optimize the runtime performance of your code. It is not something that will cause your program to fail.

Answers 2

Looking the error log it looks like or you are running out of GPU memory or the tensor is not initiated at that point. You can try to insert Tensor::IsInitialized before the line that start the problem (99) to make sure it's the GPU, if it is, you may have some code still running in the GPU, from previous tries, make sure that is not happening. There is two discussions that I think may be relevant for your problem, here: https://github.com/tensorflow/tensorflow/issues/7025 and here: https://github.com/aymericdamien/TensorFlow-Examples/issues/38 Good luck

Read More

Sunday, February 4, 2018

Heroku Application Error - Memory quota exceeded on deploy - Scout shows 4,804,423 allocations

Leave a Comment

I'm trying to find a memory bloat on my Rails application on Heroku.

I've read a bunch of articles about memory bloats and tried Scout to diagnose the problem.

I'm following Christoffers question about Heroku rising memory, but i have a different problem. Mine is almost always after a deploy, then the memory usage rises and my app breaks.

Here's an example from the Heroku Metrics: enter image description here

As you can see, the deploy is completed an then after the first visit the app is breaking.

I've benchmarked what i could(checked my queries) but nothing slow is showing in development. Also it doesn't seem that it's one controller, it's just the first controller to be used after the deploy that breaks. I've tried several, and they all break when they are first to load.

Scout Dashboard - Memory Allocation Breakdown is showing this as an example of a time out request for CategoriesController:

Scout Dashboard - Memory Allocation Breakdown

The partial and layout are rendering as it should under the image


System

I'm running Rails 5.1.4 with Webpacker installed and configured for Angular 2. This means that i've added a Procfile in my root with:

web: bundle exec puma -p $PORT this is recommended by Heroku documentation

The app is deploying as it should with minor errors about ... has incorrect peer dependency ...


Healthy and sick log

I've tried to locate a healthy Heroku log and a sick Heroku log.

Please request if this has any interest.


Number of workers

I've read the article Ruby Memory Use and tried to decrease the number of workers to 1 in my config/puma.rb, but with no result.



Updated!

1 . Weird behaviour with the memory usage on Heroku:

enter image description here

It's starting after the daily restart around 100 MB but then after the timeout (first visit) the memory usage JUMPS to just beneath 500 MB.

  1. @grizzthedj mentioned the public folder. It is 27.1 MB because of the heavy PDF.js plugin.

I'm looking for help to locate this problem. What could this be? Do you have any idea - let my try it!

I've tried what i found possible and nothing has helped yet.

Any help will be appreciated.

You can find the app on my Github page

1 Answers

Answers 1

There could be a few possibilities here.

First off, I suspect that there may be an issue with your webpacker build pipeline.

In your post, you mention that your pdf.js is 27.1 MB when deployed. When I download that file from the website, it is only ~514 KB.

I don't know what your webpacker build task is doing, but I suspect it may modifying this file unintentionally(via some wild card rule perhaps).

Secondly, there are also 3 other .js files in your /public/packs/ directory that are 7+ MB each. Thats almost 50 MB of .js alone! There are also duplicate pdf.js files in your public folder:

/public/pdfjs/build/pdf.js /public/pdf_categories/build/pdf.js  

Hard to tell if these are the only issues, but for starters, I would do the following(if you are not doing already):

  1. Double check that your webpacker is not adding any bloat to your pdf.js
  2. Use webpacker to minify your .js and .css files
  3. Ensure that you are using gzip compression for all static assets.
Read More

Friday, February 2, 2018

Activity taking 140mb memory

Leave a Comment

I'm trying to create a social media application. But it's taking about 300mb memory. So i had 5 fragments containing posts on my homepage. And overall the memory usage was 250-300mb

Then for testing, I disabled those fragments but still home activity is consuming 140mb without any big operations.

So,

here is my class

public class HomePage extends AppCompatActivity {     private Drawer result = null;     private Boolean isCoverEdit = false, isProfileEdit = false;     String username;     private RelativeLayout splash;     private Toolbar toolbar;     private StorageReference mStorage;     private ProgressDialog progressDialog;     private ImageView searchBtn;     private AHBottomNavigationViewPager fragContainer;     private AHBottomNavigation bottomNavigation;     private ImageView postBtn;     private View child;     private ImageView cover;     private CircleImageView profilePic;     private TextView star;     private TextView id;     private PopupMenu p;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_home_page);         if (FirebaseAuth.getInstance().getCurrentUser() == null) {             Intent i = new Intent(HomePage.this, Login.class);             startActivity(i);             finish();         } else {             getUsername();             initiateViews();             setupOnClickListeners();             setupBottomNavigation();              mStorage = FirebaseStorage.getInstance().getReference();             progressDialog = new ProgressDialog(this);          }       } 

Functions

    private void initiateViews() {         splash = findViewById(R.id.splash);         searchBtn = findViewById(R.id.search);         fragContainer = findViewById(R.id.frame);         toolbar = findViewById(R.id.toolbar);         bottomNavigation = findViewById(R.id.bottom_navigation);         postBtn = findViewById(R.id.post);         child = getLayoutInflater().inflate(R.layout.header, null);         profilePic = child.findViewById(R.id.pic);         id = child.findViewById(R.id.id);         cover = child.findViewById(R.id.cover);         star = child.findViewById(R.id.karma);     }   private void getUsername() {         username = new UserData(this).getUsername();          if (username==null){             FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("username").addListenerForSingleValueEvent(new ValueEventListener() {                 @Override                 public void onDataChange(DataSnapshot dataSnapshot) {                     username = dataSnapshot.getValue(String.class);                     SharedPreferences settings = getSharedPreferences("AyePref", MODE_PRIVATE);                     SharedPreferences.Editor editor = settings.edit();                     editor.putString("username", username);                     editor.apply();                     setupNavigationDrawer();                     FirebaseDatabase.getInstance().getReference().child("userdata").child(username).child("token").setValue(FirebaseInstanceId.getInstance().getToken());                  }                  @Override                 public void onCancelled(DatabaseError databaseError) {                  }             });         }else {             setupNavigationDrawer();             FirebaseDatabase.getInstance().getReference().child("userdata").child(username).child("token").setValue(FirebaseInstanceId.getInstance().getToken());         }     }      private void setupNavigationDrawer() {         result = new DrawerBuilder()                 .withActivity(HomePage.this)                 .withHeader(child)                 .withDisplayBelowStatusBar(false)                 .withTranslucentStatusBar(false)                 .withDrawerLayout(R.layout.material_drawer_fits_not)                 .addDrawerItems(                         new PrimaryDrawerItem().withName("Favourites").withIcon(GoogleMaterial.Icon.gmd_forum),                         new PrimaryDrawerItem().withName("Settings").withIcon(GoogleMaterial.Icon.gmd_settings),                         new PrimaryDrawerItem().withName("Contact").withIcon(GoogleMaterial.Icon.gmd_contact_mail),                         new PrimaryDrawerItem().withName("Commands").withIcon(GoogleMaterial.Icon.gmd_help),                         new PrimaryDrawerItem().withName("Log Out").withIcon(GoogleMaterial.Icon.gmd_security)                 )                  .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {                     @Override                     public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {                         if (drawerItem instanceof Nameable) {                             FragmentTransaction t = getSupportFragmentManager().beginTransaction();                             switch (position) {                                 case 3:                                     final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);                                     emailIntent.setType("plain/text");                                     emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"ayesupport@yandex.com"});                                     startActivity(Intent.createChooser(emailIntent, "Send mail..."));                                     break;                                 case 5:                                      break;                                 case 2:                                     Intent i= new Intent(HomePage.this, SettingsActivity.class);                                     startActivity(i);                                     break;                                 case 4:                                     Intent i2 = new Intent(HomePage.this,CommandsPage.class);                                     startActivity(i2);                                     break;                              }                           }                          return false;                     }                 }).build();          FirebaseDatabase.getInstance().getReference().child("userdata").child(username).addListenerForSingleValueEvent(new ValueEventListener() {             @Override             public void onDataChange(DataSnapshot dataSnapshot) {                 try {                     Glide.with(HomePage.this).load(dataSnapshot.child("pic").getValue(String.class)).override(100,100).thumbnail(0.5f).into(profilePic);                     //Glide.with(HomePage.this).load(dataSnapshot.child("cover").getValue(String.class)).into(cover);                  } catch (Exception e) {                     e.printStackTrace();                 }                 id.setText(username);                 star.setText("4.7");              }              @Override             public void onCancelled(DatabaseError databaseError) {              }         });     }      private void setupBottomNavigation() {         AHBottomNavigationItem item1 = new AHBottomNavigationItem("Topics", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_whatshot));         AHBottomNavigationItem item2 = new AHBottomNavigationItem("Rooms", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_group_work));         AHBottomNavigationItem item3 = new AHBottomNavigationItem("Contacts", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_people));         AHBottomNavigationItem item4 = new AHBottomNavigationItem("Leaderboard", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_star));         AHBottomNavigationItem item5 = new AHBottomNavigationItem("Stats", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_insert_chart));         bottomNavigation.addItem(item1);         bottomNavigation.addItem(item2);         bottomNavigation.addItem(item3);         bottomNavigation.addItem(item4);         bottomNavigation.addItem(item5);         bottomNavigation.setInactiveColor(R.color.md_grey_800);         bottomNavigation.setAccentColor(R.color.md_grey_600);         bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_HIDE);         fragContainer.setOffscreenPageLimit(4);         HomePageAdapter adapter = new HomePageAdapter(getSupportFragmentManager());         setSupportActionBar(toolbar);         toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);         //fragContainer.setAdapter(adapter);         bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {             @Override             public boolean onTabSelected(int position, boolean wasSelected) {                 //fragContainer.setCurrentItem(position);                 return wasSelected;              }         });     } 

Full Class : here In that class no fragments are added but the memory usage is 120-140

Memory Usage

I'm sure, I'm repeating the same mistakes in all other activities or fragments. Once I know the problem I can fix it for other parts. Heap Dump

Need Help :(

3 Answers

Answers 1

I think it is normal. It is not eating 140MB of RAM actually. On new Android Monitor of AS3 numbers are a bit different than previous AS2. In the user guide here, it is written:

When compared to memory counts from the previous Android Monitor tool, the new Memory Profiler records your memory differently, so it might seem like your memory use is now higher. The Memory Profiler monitors some extra categories that increase the total, but if you only care about the Java heap memory, then the "Java" number should be similar to the value from the previous tool.

And although the Java number probably doesn't exactly match what you saw in Android Monitor, the new number accounts for all physical memory pages that have been allocated to your app's Java heap since it was forked from Zygote. So this provides an accurate representation of how much physical memory your app is actually using.

Currently, the Memory Profiler also shows some false-positive native memory usage in your app that actually belongs to the profiling tools. Up to 10MB of memory is added for ~100k objects. In a future version of the tools, these numbers will be filtered out of your data.

I used to see 200MB+ on my previous app that has 4 fragments with bottom navigation (and found nothing on Leakcanary).

Answers 2

maybe this can help ..

check your

  • cover image
  • profile picture
  • splash screen image

check the size of the images they can effect the memory so bad !

in your code you used

UCrop.of(absolutePath, Uri.parse(imageURI))                         .withAspectRatio(16, 9)                         .withMaxResultSize(1280, 720)                         .start(HomePage.this); 

it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x96 pixel thumbnail in an ImageView.

thats mean you must be specific or if you need this quality use it but make sure this will cost a lot of memory.

take a look here

Load a Scaled Down Version into Memory

and there if the images that u use in the project as a splash screen you can use a tools Optimize your images with a perfect balance in quality and file size.

Tools - check this :

TinyPNG - Smart PNG and JPEG compression

Optimizilla

Answers 3

I would recommend you to check you resources. The drawable folder may contain pictures and also check for musics. Check the splash image size, if there are musics, check the size of it and also for videos.

Read More

Monday, October 23, 2017

R memory not released in Windows

Leave a Comment

I am using RStudio in Windows 7 and I have a problem in releasing memory to the OS. Below is my code. In a for loop:

  • I read data through an API call of the Census.gov website and I use the package acs to save them in a .csv file via the temporary object table.
  • I remove the table (usual size: few MB), and I use the package pryr to check memory usage.

According to the function mem_used(), after the removal of table, R always returns to a constant memory usage; instead according to Windows Task Manager the memory allocation for rsession.exe (not Rstudio) increases at every iteration and it eventually crashes the rsession. The use of gc() does not help. I have read lots of similar questions around but it seems that the only solution to free memory is to restart the R session which seems silly. Any suggestion?

   library(acs)    library(pryr)     # for loop to extract tables from API and save them on API    for (i in 128:length(tablecodes)) {            tryCatch({table <- acs.fetch(table.number = tablecodes[i],endyear = 2014, span=5,                   geography = geo.make(state = "NY", county = "*", tract = "*"),                   key = "e24539dfe0e8a5c5bf99d78a2bb8138abaa3b851",col.names="pretty")},              error = function(e){print("Table skipped") })      # if the table is actually fetched then we save it      if (exists("table", mode="S4")) {                   print(paste("Table",i,"fetched")          if (!is.na(table)){                    write.csv(estimate(table),paste("./CENSUS_tables/NY/",tablecodes[i],".csv",sep = ""))                 }     print(mem_used())       print(mem_change(rm(table)))     gc()     }    } 

1 Answers

Answers 1

I was able to confirm the memory problem exists on Windows 7. (Running via VMware Fusion on MacOSX). It also appears to exist on MacOSX, though memory usage appears quite gradual [Unconfirmed but indicative of memory leak]. Slightly tricky with MacOSX as the OS compresses memory if it sees high usage.

Proposed Workaround:

My proposal in light of the above is to split the table download sets into smaller groups when you download from the US Census Bureau. Why? Well, looking at the code you are downloading the data to store in .CSV files. Hence, the workaround in the short term is to break up the list of tables you are downloading. Your program should be able to complete successfully across a set of runs.

One option is to create a wrapper RScript and have it run across N runs where each invokes a separate R session. i.e. Rscript invokes N RSessions in series, each session downloads N files

nb. Based on your code, and observed memory usage, my sense is you are downloading a lot of the tables, hence splitting up across R session(s) may be the best option.

nb. The following should work under cgiwin on Windows 7.

Invoke Script

Example: Download the primary tables 01 to 27 - if they do not exist skip...

!#/bin/bash  #Ref: https://censusreporter.org/topics/table-codes/ # Params: Primary Table Year Span  for CensusTableCode in $(seq -w 1 27) do   R --no-save -q --slave < ./PullCensus.R --args B"$CensusTableCode"001 2014 5 done 

PullCensus.R

if (!require(acs)) install.packages("acs") if (!require(pryr)) install.packages("pryr")  # You can obtain a US Census key from the developer site # "e24539dfe0e8a5c5bf99d78a2bb8138abaa3b851" api.key.install(key = "** Secret**")  setwd("~/dev/stackoverflow/37264919")  # Extract Table Structure # # B = Detailed Column Breakdown # 19 = Income (Households and Families) # 001 = # A - I = Race #  args <- commandArgs(trailingOnly = TRUE) # trailingOnly=TRUE means that only your arguments are returned  if ( length(args) != 0 ) {     tableCodes <- args[1]     defEndYear = args[2]     defSpan = args[3]   } else {   tableCodes <- c("B02001")   defEndYear = 2014   defSpan = 5 }  # for loop to extract tables from API and save them on API for (i in 1:length(tableCodes)) {   tryCatch(     table <- acs.fetch(table.number = tableCodes[i],                        endyear = defEndYear,                        span = defSpan,                        geography = geo.make(state = "NY",                                             county = "*",                                             tract = "*"),                        col.names = "pretty"),     error = function(e) { print("Table skipped")} )    # if the table is actually fetched then we save it   if (exists("table", mode = "S4"))   {     print(paste("Table", i, "fetched"))     if (!is.na(table))     {       write.csv(estimate(table), paste(defEndYear,"_",tableCodes[i], ".csv", sep = ""))     }     print(mem_used())     print(mem_change(rm(table)))     gc(reset = TRUE)     print(mem_used())   } } 

I hope the above helps by way of example. It is an approach. ;-)

T.

Next Steps:

I'll take a look at the package source to see if I can see what is actually wrong. Alternatively, you yourself may be able to narrow it down and file a bug against the package.


Background / Working Example:

My sense is that is might help to provide a working code example to frame the above workaround. Why? The intent here is to provide an example that people might use to test and consider what is happening. Why? Well, it makes it easier to understand your question and intent.

Essentially, (as I understand it) you are bulk downloading US Census data from the US Census website. The table codes are used to specify what data you wish to download. Ok, so I just created a set of table codes and tested the memory usage to see if memory starts to be consumed as you explained.

library(acs) library(pryr) library(tigris) library(stringr)  # to pad fips codes library(maptools)  # You can obtain a US Census key from the developer site # "e24539dfe0e8a5c5bf99d78a2bb8138abaa3b851" api.key.install(key = "<INSERT KEY HERE>")  # Table Codes # # While Census Reporter hopes to save you from the details, you may be # interested to understand some of the rationale behind American Community # Survey table identifiers. # # Detailed Tables # # The bulk of the American Community Survey is the over 1400 detailed data # tables. These tables have reference codes, and knowing how the codes are # structured can be helpful in knowing which table to use. # # Codes start with either the letter B or C, followed by two digits for the # table subject, then 3 digits that uniquely identify the table. (For a small # number of technical tables the unique identifier is 4 digits.) In some cases # additional letters for racial iterations and Puerto Rico-specific tables. # # Full and Collapsed Tables # # Tables beginning with B have the most detailed column breakdown, while a # C table for the same numbers will have fewer columns. For example, the # B02003 table ("Detailed Race") has 71 columns, while the "collapsed # version," C02003 has only 19 columns. While your instinct may be to want # as much data as possible, sometimes choosing the C table can simplify # your analysis. # # Table subjects # # The first two digits after B/C indicate the broad subject of a table. # Note that many tables have more than one subject, but this reflects the # main subject. # # 01 Age and Sex # 02 Race # 03 Hispanic Origin # 04 Ancestry # 05 Foreign Born; Citizenship; Year or Entry; Nativity # 06 Place of Birth07Residence 1 Year Ago; Migration # 08 Journey to Work; Workers' Characteristics; Commuting # 09 Children; Household Relationship # 10 Grandparents; Grandchildren # 11 Household Type; Family Type; Subfamilies # 12 Marital Status and History13Fertility # 14 School Enrollment # 15 Educational Attainment # 16 Language Spoken at Home and Ability to Speak English # 17 Poverty # 18 Disability # 19 Income (Households and Families) # 20 Earnings (Individuals) # 21 Veteran Status # 22 Transfer Programs (Public Assistance) # 23 Employment Status; Work Experience; Labor Force # 24 Industry; Occupation; Class of Worker # 25 Housing Characteristics # 26 Group Quarters # 27 Health Insurance # # Three groups of tables reflect technical details about how the Census is # administered. In general, you probably don't need to look at these too # closely, but if you need to check for possible weaknesses in your data # analysis, they may come into play. # # 00 Unweighted Count # 98 Quality Measures # 99 Imputations # # Race and Latino Origin # # Many tables are provided in multiple racial tabulations. If a table code # ends in a letter from A-I, that code indicates that the table universe is # restricted to a subset based on responses to the race or # Hispanic/Latino-origin questions. # # Here is a guide to those codes: # #   A White alone #   B Black or African American Alone #   C American Indian and Alaska Native Alone #   D Asian Alone #   E Native Hawaiian and Other Pacific Islander Alone #   F Some Other Race Alone #   G Two or More Races #   H White Alone, Not Hispanic or Latino #   I Hispanic or Latino   setwd("~/dev/stackoverflow/37264919")  # Extract Table Structure # # B = Detailed Column Breakdown # 19 = Income (Households and Families) # 001 = # A - I = Race # tablecodes <- c("B19001", "B19001A", "B19001B", "B19001C", "B19001D",                 "B19001E", "B19001F", "B19001G", "B19001H", "B19001I" )  # for loop to extract tables from API and save them on API for (i in 1:length(tablecodes)) {   print(tablecodes[i])   tryCatch(     table <- acs.fetch(table.number = tablecodes[i],                        endyear = 2014,                        span = 5,                        geography = geo.make(state = "NY",                                             county = "*",                                             tract = "*"),                        col.names = "pretty"),     error = function(e) { print("Table skipped")} )    # if the table is actually fetched then we save it   if (exists("table", mode="S4"))   {     print(paste("Table", i, "fetched"))     if (!is.na(table))     {       write.csv(estimate(table), paste("T",tablecodes[i], ".csv", sep = ""))     }     print(mem_used())     print(mem_change(rm(table)))     gc()     print(mem_used())   } } 

Runtime Output

> library(acs) > library(pryr) > library(tigris) > library(stringr)  # to pad fips codes > library(maptools) > # You can obtain a US Census key from the developer site > # "e24539dfe0e8a5c5bf99d78a2bb8138abaa3b851" > api.key.install(key = "...secret...") >  ... > setwd("~/dev/stackoverflow/37264919") >  > # Extract Table Structure > # > # B = Detailed Column Breakdown > # 19 = Income (Households and Families) > # 001 = > # A - I = Race > # > tablecodes <- c("B19001", "B19001A", "B19001B", "B19001C", "B19001D", +                 "B19001E", "B19001F", "B19001G", "B19001H", "B19001I" ) >  > # for loop to extract tables from API and save them on API > for (i in 1:length(tablecodes)) + { +   print(tablecodes[i]) +   tryCatch( +     table <- acs.fetch(table.number = tablecodes[i], +                        endyear = 2014, +                        span = 5, +                        geography = geo.make(state = "NY", +                                             county = "*", +                                             tract = "*"), +                        col.names = "pretty"), +     error = function(e) { print("Table skipped")} ) +  +   # if the table is actually fetched then we save it +   if (exists("table", mode="S4")) +   { +     print(paste("Table", i, "fetched")) +     if (!is.na(table)) +     { +       write.csv(estimate(table), paste("T",tablecodes[i], ".csv", sep = "")) +     } +     print(mem_used()) +     print(mem_change(rm(table))) +     gc() +     print(mem_used()) +   } + } [1] "B19001" [1] "Table 1 fetched" 95.4 MB -1.88 MB 93.6 MB [1] "B19001A" [1] "Table 2 fetched" 95.4 MB -1.88 MB 93.6 MB [1] "B19001B" [1] "Table 3 fetched" 95.5 MB -1.88 MB 93.6 MB [1] "B19001C" [1] "Table 4 fetched" 95.5 MB -1.88 MB 93.6 MB [1] "B19001D" [1] "Table 5 fetched" 95.5 MB -1.88 MB 93.6 MB [1] "B19001E" [1] "Table 6 fetched" 95.5 MB -1.88 MB 93.6 MB [1] "B19001F" [1] "Table 7 fetched" 95.5 MB -1.88 MB 93.6 MB [1] "B19001G" [1] "Table 8 fetched" 95.5 MB -1.88 MB 93.6 MB [1] "B19001H" [1] "Table 9 fetched" 95.5 MB -1.88 MB 93.6 MB [1] "B19001I" [1] "Table 10 fetched" 95.5 MB -1.88 MB 93.6 MB 

Output files

>ll total 8520 drwxr-xr-x@ 13 hidden  staff   442B Oct 17 20:41 . drwxr-xr-x@ 40 hidden  staff   1.3K Oct 17 23:17 .. -rw-r--r--@  1 hidden  staff   4.4K Oct 17 23:43 37264919.R -rw-r--r--@  1 hidden  staff   492K Oct 17 23:50 TB19001.csv -rw-r--r--@  1 hidden  staff   472K Oct 17 23:51 TB19001A.csv -rw-r--r--@  1 hidden  staff   414K Oct 17 23:51 TB19001B.csv -rw-r--r--@  1 hidden  staff   387K Oct 17 23:51 TB19001C.csv -rw-r--r--@  1 hidden  staff   403K Oct 17 23:51 TB19001D.csv -rw-r--r--@  1 hidden  staff   386K Oct 17 23:51 TB19001E.csv -rw-r--r--@  1 hidden  staff   402K Oct 17 23:51 TB19001F.csv -rw-r--r--@  1 hidden  staff   393K Oct 17 23:52 TB19001G.csv -rw-r--r--@  1 hidden  staff   465K Oct 17 23:44 TB19001H.csv -rw-r--r--@  1 hidden  staff   417K Oct 17 23:44 TB19001I.csv 
Read More

Sunday, October 15, 2017

Memory usage in JVM profiler vs. Mac OS X Activity Monitor

Leave a Comment

I've been profiling my java application and have been confused about the reported memory usage of my application (run via eclipse). It's always very different to the memory usage reported by the profiler, and doesn't really even match itself.

The JVM flags for the application are:

-Xmx1G   -Xms1G 	  -XX:MaxMetaspaceSize=256M  -XX:CompressedClassSpaceSize=256M

This image shows that the reported memory of the process "java" is 1.67GB. When I double click on that process, the breakdown shows 1.15GB of "Real Memory Size" and the various other memory metrics.

Reported Mac OS X memory usage

Flight recorder shows that the application adheres to its 1GB heap size. I have carried out tests that show that it also adheres to its metaspace limits.

Flight Recorder memory usage

My question is two fold: 1) Any idea why reported memory usage is so different between the process (as reported by Mac OS X) and the profiler? 2) Any idea why there's a disparity between memory shown in Activity Monitor and the breakdown of the process memory?

1 Answers

Answers 1

1) Real memory is everything together: heap + stack + MetaSpace (formerly PermGen) + CompressedClassSpaceSize + etc. You limit the heap to 1GiB as shown by Flight Recorder. The OS shows everything together, not just the heap, that is where this disparity originates. It is not OS/JVM specific (i.e., try it on *nix, Windows, you will see the same).

2) That is OS specific. For Mac OS see this very detailed answer

Read More

Thursday, August 10, 2017

Android cache background process is increasing continuously

Leave a Comment

In my android application named "PriceDekho" the cache background process takes too much space. First when i start the application the application takes arround 30MB (I think its OK) but the problem is when i surfing the application pages then this size is increasing continuously upto (200 MB). This appliction "Cache background process" also varying with the mobile RAM size. If the mobile RAM size is 2GB then this application "Cache background process" size goes upto 500 to 700 MB.

My application is having only 5 to 6 screens. I just need to stabilize the cached background size.

How can i clear the application cached size? Please help.

enter image description here

enter image description here

2 Answers

Answers 1

It sounds like you have memory leaks which the Garbage Collector can not remove. For example if you need to have a reference to the Context from a non-context class which is never released there. Most of the time Android Studio will point those out but you can try to use LeakCanary and search for them.

Add the dependency

dependencies {    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'  } 

and use it in your Application class. Create one if you don't have it already.

public class ExampleApplication extends Application {    @Override public void onCreate() {     super.onCreate();     if (LeakCanary.isInAnalyzerProcess(this)) {       // This process is dedicated to LeakCanary for heap analysis.       // You should not init your app in this process.       return;     }     LeakCanary.install(this);     // Normal app init code...   } } 

Answers 2

Cache background process surely varies with the RAM size as the system will allow more data to be cached if more memory is available.

However, the increasing pattern in memory usage by the application may either be due to memory leaks or huge objects being created in the background. The Garbage collector is not an all weather friend and may tend to ignore memory leaks due to programmatic mistakes.

As there is no code posted for review, some trivial questions to ask would be:

  • Is there a lot of image processing being done using bitmaps? If yes, are those bitmaps being recycled ?
  • Is your application using the context judiciously, that is avoiding usage of the application context, unless required ?
  • Are the listeners being unregistered, if any ?

    As suggested above, LeakCanary will surely be much useful in this case, surely more than the Android Monitor.

Read More

Wednesday, July 5, 2017

Finding memory leak

Leave a Comment

I have a web application that I wrote using a lot of different 3rd party components, a CMS and of course my code. For some reason I get out of memory exception.

Script threw an exception: Out of memory

I tried to find out what is going on. This is what I've found:

  • I ran the test with 50 threads to call 15 pages of my web-application. Memory seems fine. The IIS process is using only 400 MB of RAM

  • I've added a space in web.config and suddenly my IIS process started to grow to more than a GB in 30 minutes. Visual studio could not take snapshot of my memory since it is too big (really?!) So I've installed ANTS memory profiler but it says that my application is using only around 300 MBANTS only 300 MB

IIS process takes 1 GB [1]: https://i.stack.imgur.com/Ig8pY.png

I stopped the test after some minutes but the memory has not released.

(ANTS profiler stopped working so I've restarted it) 422MB after release IIS 1.2GB Summary 4MB of strings

It doesn't seem like the application is using 100-200MB memory specially that I am using output caching for my controllers. What I don't understand is why memory consumed by IIS is growing all the time and what is wrong

Update

My application has been restarted automatically with a crash in W3WP causing IIS to release the memory while my stress was not running for a while:

Application: w3wp.exe Framework Version: v4.0.30319 Description: The process was terminated due to an internal error in the .NET Runtime at IP 5A3A86F1 (5A0F0000) with exit code 80131506.

and

Faulting application name: w3wp.exe, version: 10.0.15063.0, time stamp: 0xacce422f Faulting module name: clr.dll, version: 4.7.2098.0, time stamp: 0x59028d36 Exception code: 0xc0000005 Fault offset: 0x002b86f1 Faulting process id: 0x50a4 Faulting application start time: 0x01d2ee688f323893 Faulting application path: C:\WINDOWS\SysWOW64\inetsrv\w3wp.exe Faulting module path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll Report Id: 4362ddc5-f8d7-4441-8916-3830f9268b3a Faulting package full name: Faulting package-relative application ID:

enter image description here

Update 2

I ran DebugDiag and I've stress tested the site until it consumed around 3.5 GB of my RAM.

enter image description here

And Chakra is a Microsoft's library.

enter image description here enter image description here

So now I have 2 questions.

  1. Is it the ChakraCore that has leak or is it the one that is using/allocating it? How to define which library?

2- It says 27,000 allocations. Does it mean that there are still 27,000 in the memory or some of them might be allocated and then disposed?

3- It still doesn't tell me anything about the rest of 3GB of consumed RAM. it i only 600 MB in total (private+virtual).

4 Answers

Answers 1

In your analysis, I see that the .net analysis is not done correctly. Are you doing analysis in the same machine where you have captured the memory dump ?

For debugdiag to work correctly, you have to have the same version of .net framework (of the application) installed on the analyzing machine as well.

Also Please do not do native memory leak dump like this ,unless it is not figured out unmanaged leak.From the analysis of yours, it looks like this is managed leak.

When you changed the web.config file,it causes an Application domain unload and reload

Let's do step by step

  1. Using DebugDiag(capture consecutive hang dumps)
    • Launch DebugDiag Collection and Go to the Processes tab debugdiag process tab
    • Start your stress test
    • check the memory usage and once it reaches say 1 GB,capture a hang dump
      • right click on the w3wp.exe process
      • choose the option Create Full Memory dump capture full memory hang dump
    • Capture another dump at 2 GB and one at 3.5 GB
    • You should have dumps captured in the folder C:\ProgramFiles\DebugDiag\Logs\Misc\
    • Right click on the dump file and choose the option Analyse .NET Memory Issue Analyse .net memory issue

Now compare the analysis of each dump file(1 GB,2 GB, 3.5 GB), it should tell you which .NET objects are increasing and not getting garbage collected.

In the memory analysis, you should see CLR Information****,.NET GC Heap Information ,Most memory Consuming .NET Objects etc like below. This will come if your .net symbols are correctly identified by debugdiag analysis

CLR Information  CLR version = 4.6.1648.0  Microsoft.Diagnostics.Runtime version = 0.9.2.0 .NET GC Heap Information Number of GC Heaps: 4  Heap Size 0x4001ce8 (67,116,264)  Heap Size 0x3d5cca0 (64,343,200)  Heap Size 0x3f8b0d0 (66,629,840)  Heap Size 0x3ccb0d0 (63,746,256)  GC Heap Size 249.71 MBytes   Total Commit Size  249 MB  Total Reserved Size    17158 MB   40 most memory consuming .NET object types  System.Char[]   193.01 MBytes    (12450 objects ) Free      45.21 MBytes    (4760 objects ) System.String      1.56 MBytes    (18072 objects )  ==============trimmed out ======================= 

DebugDaig Automated analysis should give following

  1. **Errors or Warnings **- pay close attention to warning or errors displayed by debugdiag analysis on the top of the report.
  2. .NET GC Heap Information - Total Commit Size - This will roughly equal to your .net memory usage.
  3. 40 most memory consuming .NET object types -This can be used to compare against your memory increase in consecutive dumps. This will tell you which objects are causing issue.Sometimes some objects you are not using at all will be coming and might be coming from some third party library.Or you will see objects which you yourself have created
  4. Top Objects in the Finalizer queue - This will give you any clue if your finalizer may be blocked .Objects.Some similar issues are discussed here and here
  5. Objects on the Large Object Heap - This causes memory fragmentation and large object heap contaisn objects which are more than 85K in size.
  6. Size of Cache, Datatables,Application domains,Dynamic assemblies etc. It's not a good idea to have large number of application domain in one process

Please note that sometimes the debugdiag automated analysis cannot figure out the root cause and needs manual analysis using windbg. DebugDiag analysis,please refer this video.

Hope this helps!

Answers 2

Since it appears you can reproduce your issue, sometimes the simplest approach is to remove things you think might be the root cause, and test again (unless you need a lot of time to see if it grows a lot or not?)

At some point the bug will stop happening, and you'll know what bit of code was responsible.

However, depending on your code base, it's not always easy to remove code and still have something that you can test (i.e. without crashing the application).

Answers 3

When it comes to fixing memory leaks there are two steps.

  1. Finding where the memory leak is.
  2. Fixing the memory leak.

Normally the first step is tricky. So, I would recommend to go ahead with ANTS memory profiler and first find what exact instances are growing.

Profiling an ASP.NET application on IIS

In your question you have shown the class list result which includes even classes with system namespace. To clean up the noise, you can select "Show Only Classes with source" option.

enter image description here

Then follow the follwing steps.

  1. Take a base snapshot before you perform any operations.
  2. Perform the operations you suspect that have memory leaks.
  3. Take couple of more snapshots until you get a fairly stable snapshot.
  4. Compare the last snapshot with the base and see what instances are growing.

Answers 4

You mentioned "I've added a space in web.config and suddenly my IIS process started to grow to more than a GB in 30 minutes". In which web.config tag have you appended this space. What part of your code uses it. Is that part of your code unable to handle some exception without causing memory leak. Use PerfView (Dump GC heap) to analyze the dump. This can exactly tell, the object of what kind is taking up this much of memory. In older versions of .net, it would be objects on large object heap (big arrays) or open and mis-handled db connections and files.

https://channel9.msdn.com/Series/PerfView-Tutorial/Tutorial-10-Investigating-NET-Heap-Memory-Leaks-Part1-Collecting-the-data

https://channel9.msdn.com/Series/PerfView-Tutorial/Tutorial-11-Investigating-NET-Heap-Memory-Leaks-Part2-Analyzing-the-data

Read More

Friday, April 14, 2017

Get address of allocated memory by pointer to a base class for non-polymorphic types

Leave a Comment

simple multi-inheritance

struct A {}; struct B {}; struct C : A, B {}; 

or virtual inheritance

struct B {}; struct C : virtual B {}; 

Please note types are not polymorphic.

Custom memory allocation:

template <typedef T, typename... Args> T* custom_new(Args&& args...) {     void* ptr = custom_malloc(sizeof(T));     return new(ptr) T(std::forward<Args>(args)...); }  template <typedef T> void custom_delete(T* obj) {     if (!obj)         return obj;      void* ptr = get_allocated_ptr(obj); // here     assert(std::is_polymorphic_v<T> || ptr == obj);     obj->~T();     custom_free(ptr); // heap corruption if assert ^^ failed }  B* b = custom_new<C>(); // b != address of allocated memory custom_delete(b); // UB 

How can I implement get_allocated_ptr for non polymorphic types? For polymorphic types dynamic_cast<void*> does the job.

Alternatively I could check that obj is a pointer to a base class as deleting a non polymorphic object by a pointer to base class is UB. I don't know how to do this or if it's possible at all.

operator delete properly deallocates memory in such cases (e.g. VC++), though standard says it's UB. How does it do this? compiler-specific feature?

3 Answers

Answers 1

You actually have a more serious problem than getting the address of the full object. Consider this example:

struct Base {   std::string a; };  struct Derived : Base {   std::string b; };  Base* p = custom_new<Derived>(); custom_delete(p); 

In this example, custom_delete will actually free the correct address (static_cast<void*>(static_cast<Derived*>(p)) == static_cast<void*>(p)), but the line obj->~T() will invoke the destructor for Base, meaning that the b field is leaked.


So Don't Do That

Instead of returning a raw pointer from custom_new, return an object that is bound to the type T and that knows how to delete it. For example:

template <class T> struct CustomDeleter {   void operator()(T* object) const   {     object->~T();     custom_free(object);    } };  template <typename T> using CustomPtr = std::unique_ptr<T, CustomDeleter<T>>;  template <typename T, typename... Args> CustomPtr<T> custom_new(Args&&... args) {   void* ptr = custom_malloc(sizeof(T));   try   {     return CustomPtr<T>{ new(ptr) T(std::forward<Args>(args)...) };   }   catch (...)   {     custom_free(ptr);     throw;   } } 

Now it's impossible to accidentally free the wrong address and call the wrong destructor because the only code that calls custom_free knows the complete type of the thing that it's deleting.

Note: Beware of the unique_ptr::reset(pointer) method. This method is extremely dangerous when using a custom deleter since the onus is on the caller to supply a pointer that was allocated in the correct way. The compiler can't help if the method is called with an invalid pointer.


Passing Around Base Pointers

It may be that you want to both pass a base pointer to a function and give that function responsibility for freeing the object. In this case, you need to use type erasure to hide the type of the object from consumers while retaining knowledge of its most derived type internally. The easiest way to do that is with a std::shared_ptr. For example:

struct Base {   int a; };  struct Derived : Base {   int b; };  CustomPtr<Derived> unique_derived = custom_new<Derived>();  std::shared_ptr<Base> shared_base = std::shared_ptr<Derived>{ std::move(unique_derived) }; 

Now you can freely pass around shared_base and when the final reference is released, the complete Derived object will be destroyed and its correct address passed to custom_free. If you don't like the semantics of shared_ptr, it's fairly straightforward to create a type erasing pointer with unique_ptr semantics.

Note: One downside to this approach is that the shared_ptr requires a separate allocation for its control block (which won't use custom_malloc). With a little more work, you can get around that. You'd need to create a custom allocator that wraps custom_malloc and custom_free and then use std::allocate_shared to create your objects.


Complete Working Example

#include <memory> #include <iostream>  void* custom_malloc(size_t size) {   void* mem = ::operator new(size);   std::cout << "allocated object at " << mem << std::endl;   return mem; }  void custom_free(void* mem) {   std::cout << "freeing memory at " << mem << std::endl;   ::operator delete(mem); }  template <class T> struct CustomDeleter {   void operator()(T* object) const   {     object->~T();     custom_free(object);    } };  template <typename T> using CustomPtr = std::unique_ptr<T, CustomDeleter<T>>;  template <typename T, typename... Args> CustomPtr<T> custom_new(Args&&... args) {   void* ptr = custom_malloc(sizeof(T));   try   {           return CustomPtr<T>{ new(ptr) T(std::forward<Args>(args)...) };   }   catch (...)   {     custom_free(ptr);     throw;   } }  struct Base {   int a;   ~Base()   {     std::cout << "destroying Base" << std::endl;   } };  struct Derived : Base {   int b;   ~Derived()   {     std::cout << "detroying Derived" << std::endl;   } };  int main() {   // Since custom_new has returned a unique_ptr with a deleter bound to the   // type Derived, we cannot accidentally free the wrong thing.   CustomPtr<Derived> unique_derived = custom_new<Derived>();    // If we want to get a pointer to the base class while retaining the ability   // to correctly delete the object, we can use type erasure.  std::shared_ptr   // will do the trick, but it's easy enough to write a similar class without   // the sharing semantics.   std::shared_ptr<Base> shared_base = std::shared_ptr<Derived>{ std::move(unique_derived) };    // Notice that when we release the shared_base pointer, we destroy the complete   // object.   shared_base.reset(); } 

Answers 2

You can do that only using dynamic_cast and static type of T has to be polymorphic. Otherwise look at this code:

struct A { int a; }; struct B { int b; }; struct C : A, B {};  B *b1 = new C, *b2 = new B; 

If you try to delete by pointer to B, there is no way to know if b1 or b2 needs to be adjusted to get_allocated_ptr. One way or another you need B to be polymorphic to get pointer to most derived object.

Answers 3

What about a virtual interface that all structs inherit from, which returns the pointer at which the object was allocated? I had to make some changes to make the code compile. Both the multiple inheritance and virtual inheritance cases work:

#include <iostream> #include <type_traits> #include <cassert>  struct H { public:     void* getHeader() { return header; }     void setHeader(void* ptr) { header = ptr; } private:     void* header; };  // multiple inheritance case //struct A : public virtual H { int a;}; //struct B : public virtual H { int b;}; //struct C : A, B { };  // virtual inheritance case struct B : public virtual H { int b; }; struct C : virtual B {};  template <typename T, typename ...Args> T* custom_new(Args&&... args) {     void* ptr = malloc(sizeof(T));     T* obj = new(ptr) T(std::forward<Args>(args)...);     obj->setHeader(ptr);     return obj; }  template <typename T> void* get_allocated_ptr(T* obj) {     return obj->getHeader(); }  template <typename T> void custom_delete(T* obj) {     void* ptr = get_allocated_ptr(obj); // here //  assert(std::is_polymorphic<T>::value || ptr == obj); // had to comment     obj->~T();     free(ptr); // heap corruption if assert ^^ failed }  using namespace std; int main(int argc, char *argv[]) {     C* c = custom_new<C>(); // b != address of allocated memory     std::cout << "PTR \t\t= " << c << std::endl;     auto b = static_cast<B*>(c);     std::cout << "CAST PTR \t= " << b << std::endl;     std::cout << "ALLOCATED PTR \t= " << get_allocated_ptr(b) << std::endl;      custom_delete(b); // UB } 

You can run this with either hierarchy, and the output is something like

PTR             = 0x7f9fd4d00b90 CAST PTR        = 0x7f9fd4d00b98 ALLOCATED PTR   = 0x7f9fd4d00b90 

although in the multiple inheritance case the pointers differ by 16 bits rather than 8 (because of the two integers).

This implementation could be improved by using templates to enable custom_new and the other functions only for structs inheriting from the H interface.

Read More

Thursday, February 9, 2017

Clearing the “cached” memory in /proc/meminfo without drop_caches

Leave a Comment

I have an embedded system running 2.6.10 linux kernel (I know!) and I noticed that as the system stays up for longer periods of time, the "cached" usage of RAM - as seen in /proc/meminfo - increases linearly. Sometimes it reaches up to 70% of total RAM and the system crashes.

  1. I don't know why this space wasn't automatically re-claimed by the kernel during low memory conditions. I thought the "cached" memory, though used, is still considered readily "available".

  2. In order to atleast manually reclaim this space, I would have to tweak the drop_caches setting in /proc/sys/vm/. However, this feature was only introduce in the 2.6.16 kernel.

Since a large part of what's in "cached" is the page cache, file and inode caches, is there any way to forefully reclaim them without the drop_caches feature? I've tried sync, but that didn't help at all.

I've googled a lot about this but couldn't find any resources that don't somehow rely on the drop_caches feature.

EDIT:

Following advice from a few other threads, I ran a test that wrote to the on-board flash partition every seconds and I see both the dentry and size-64 fields go up in /proc/slabinfo (at the rate of 1 per loop of the bash script). However, I didn't notice any increase in the Cached memory usage.

MORE INFO:

I must mention that the root directory itself is in ramfs. I do have a flash chip that we read/write from, but too frequently. I've pasted the meminfo and slabinfo taken sometime before the crash. Notice how the active and cached fields add to greater than the total available memory!

MemTotal:       256708 kB MemFree:          4896 kB Buffers:             0 kB Cached:         181892 kB SwapCached:          0 kB Active:         178140 kB Inactive:        46496 kB HighTotal:           0 kB HighFree:            0 kB LowTotal:       256708 kB LowFree:          4896 kB SwapTotal:           0 kB SwapFree:            0 kB Dirty:               0 kB Writeback:           0 kB Mapped:          56656 kB Slab:            11252 kB CommitLimit:    128352 kB Committed_AS:   175668 kB PageTables:        908 kB VmallocTotal:   737280 kB VmallocUsed:    113084 kB VmallocChunk:   624100 kB  slabinfo - version: 2.1 # name            <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab> : tunables <batchcount> <limit> <sharedfactor> : slabdata <active_slabs> <num_slabs> <sharedavail> rwsem_lock_cache       0      0     64   59    1 : tunables  120   60    0 : slabdata      0      0      0 rwsem_owner_cache     16     59     64   59    1 : tunables  120   60    0 : slabdata      1      1      0 rwsem_sap_cache        0      0    128   30    1 : tunables  120   60    0 : slabdata      0      0      0 pss_node_cache         0      0     32  113    1 : tunables  120   60    0 : slabdata      0      0      0 mts-sapinfo-cache      0      0   1152    7    2 : tunables   24   12    0 : slabdata      0      0      0 mts-sap-desc-cache     34     36    448    9    1 : tunables   54   27    0 : slabdata      4      4      0 mts-qentry-cache       5     59     64   59    1 : tunables  120   60    0 : slabdata      1      1      0 mts-rcpnt-cache        1      1   5568    1    2 : tunables    8    4    0 : slabdata      1      1      0 rpc_buffers            8      8   2048    2    1 : tunables   24   12    0 : slabdata      4      4      0 rpc_tasks              8     24    160   24    1 : tunables  120   60    0 : slabdata      1      1      0 rpc_inode_cache        0      0    416    9    1 : tunables   54   27    0 : slabdata      0      0      0 unix_sock             70     70    384   10    1 : tunables   54   27    0 : slabdata      7      7      0 tcp_tw_bucket          0      0     96   40    1 : tunables  120   60    0 : slabdata      0      0      0 tcp_bind_bucket       25    203     16  203    1 : tunables  120   60    0 : slabdata      1      1      0 tcp_open_request       2     59     64   59    1 : tunables  120   60    0 : slabdata      1      1      0 inet_peer_cache        4     59     64   59    1 : tunables  120   60    0 : slabdata      1      1      0 ip_fib_alias          23    203     16  203    1 : tunables  120   60    0 : slabdata      1      1      0 ip_fib_hash           23    113     32  113    1 : tunables  120   60    0 : slabdata      1      1      0 ip_dst_cache          34     45    256   15    1 : tunables  120   60    0 : slabdata      3      3      0 arp_cache             13     24    160   24    1 : tunables  120   60    0 : slabdata      1      1      0 raw_sock               8      8    480    8    1 : tunables   54   27    0 : slabdata      1      1      0 udp_sock               7      8    480    8    1 : tunables   54   27    0 : slabdata      1      1      0 tcp_sock              29     36   1024    4    1 : tunables   54   27    0 : slabdata      9      9      0 flow_cache             0      0     96   40    1 : tunables  120   60    0 : slabdata      0      0      0 cfq_ioc_pool           0      0     24  145    1 : tunables  120   60    0 : slabdata      0      0      0 cfq_pool               0      0    104   37    1 : tunables  120   60    0 : slabdata      0      0      0 crq_pool               0      0     52   72    1 : tunables  120   60    0 : slabdata      0      0      0 deadline_drq           0      0     48   78    1 : tunables  120   60    0 : slabdata      0      0      0 as_arq                 4     63     60   63    1 : tunables  120   60    0 : slabdata      1      1      0 mqueue_inode_cache      1      8    480    8    1 : tunables   54   27    0 : slabdata      1      1      0 jffs2_inode_cache     24    145     24  145    1 : tunables  120   60    0 : slabdata      1      1      0 jffs2_node_frag    36493  36576     28  127    1 : tunables  120   60    0 : slabdata    288    288      0 jffs2_raw_node_ref  52018  52171     16  203    1 : tunables  120   60    0 : slabdata    257    257      0 jffs2_tmp_dnode        0      0     24  145    1 : tunables  120   60    0 : slabdata      0      0      0 jffs2_raw_inode        0      0     68   56    1 : tunables  120   60    0 : slabdata      0      0      0 jffs2_raw_dirent       0      0     40   92    1 : tunables  120   60    0 : slabdata      0      0      0 jffs2_full_dnode   36494  36540     16  203    1 : tunables  120   60    0 : slabdata    180    180      0 jffs2_i               13     24    328   12    1 : tunables   54   27    0 : slabdata      2      2      0 nfs_write_data        36     36    448    9    1 : tunables   54   27    0 : slabdata      4      4      0 nfs_read_data         32     36    448    9    1 : tunables   54   27    0 : slabdata      4      4      0 nfs_inode_cache        0      0    544    7    1 : tunables   54   27    0 : slabdata      0      0      0 nfs_page               0      0     64   59    1 : tunables  120   60    0 : slabdata      0      0      0 dnotify_cache          0      0     20  169    1 : tunables  120   60    0 : slabdata      0      0      0 kioctx                 0      0    192   20    1 : tunables  120   60    0 : slabdata      0      0      0 kiocb                  0      0    128   30    1 : tunables  120   60    0 : slabdata      0      0      0 fasync_cache           0      0     16  203    1 : tunables  120   60    0 : slabdata      0      0      0 shmem_inode_cache    169    170    384   10    1 : tunables   54   27    0 : slabdata     17     17      0 posix_timers_cache      0      0    100   39    1 : tunables  120   60    0 : slabdata      0      0      0 uid_cache              0      0     64   59    1 : tunables  120   60    0 : slabdata      0      0      0 blkdev_ioc             0      0     24  145    1 : tunables  120   60    0 : slabdata      0      0      0 blkdev_queue          25     30    368   10    1 : tunables   54   27    0 : slabdata      3      3      0 blkdev_requests        4     28    140   28    1 : tunables  120   60    0 : slabdata      1      1      0 biovec-(256)         256    256   3072    2    2 : tunables   24   12    0 : slabdata    128    128      0 biovec-128           256    260   1536    5    2 : tunables   24   12    0 : slabdata     52     52      0 biovec-64            256    260    768    5    1 : tunables   54   27    0 : slabdata     52     52      0 biovec-16            256    260    192   20    1 : tunables  120   60    0 : slabdata     13     13      0 biovec-4             256    295     64   59    1 : tunables  120   60    0 : slabdata      5      5      0 biovec-1             256    406     16  203    1 : tunables  120   60    0 : slabdata      2      2      0 bio                  256    295     64   59    1 : tunables  120   60    0 : slabdata      5      5      0 file_lock_cache       65     80     96   40    1 : tunables  120   60    0 : slabdata      2      2      0 sock_inode_cache     121    121    352   11    1 : tunables   54   27    0 : slabdata     11     11      0 skbuff_head_cache    560    560    192   20    1 : tunables  120   60    0 : slabdata     28     28      0 sock                   9     12    320   12    1 : tunables   54   27    0 : slabdata      1      1      0 proc_inode_cache    1196   1196    304   13    1 : tunables   54   27    0 : slabdata     92     92      0 sigqueue              26     26    148   26    1 : tunables  120   60    0 : slabdata      1      1      0 radix_tree_node     2030   2030    276   14    1 : tunables   54   27    0 : slabdata    145    145      0 bdev_cache             1      9    416    9    1 : tunables   54   27    0 : slabdata      1      1      0 mnt_cache             20     40     96   40    1 : tunables  120   60    0 : slabdata      1      1      0 inode_cache         2665   2665    288   13    1 : tunables   54   27    0 : slabdata    205    205      0 dentry_cache        4147   4147    136   29    1 : tunables  120   60    0 : slabdata    143    143      0 filp                1380   1440    160   24    1 : tunables  120   60    0 : slabdata     60     60      0 names_cache            4      4   4096    1    1 : tunables   24   12    0 : slabdata      4      4      0 idr_layer_cache       97    116    136   29    1 : tunables  120   60    0 : slabdata      4      4      0 buffer_head            0      0     48   78    1 : tunables  120   60    0 : slabdata      0      0      0 mm_struct             44     49    544    7    1 : tunables   54   27    0 : slabdata      7      7      0 vm_area_struct      3452   3680     84   46    1 : tunables  120   60    0 : slabdata     80     80      0 fs_cache              45    113     32  113    1 : tunables  120   60    0 : slabdata      1      1      0 files_cache           42     45    416    9    1 : tunables   54   27    0 : slabdata      5      5      0 signal_cache          57     60    256   15    1 : tunables  120   60    0 : slabdata      4      4      0 sighand_cache         55     60   1312    3    1 : tunables   24   12    0 : slabdata     20     20      0 task_struct           96    100    960    4    1 : tunables   54   27    0 : slabdata     25     25      0 anon_vma            1273   1356      8  339    1 : tunables  120   60    0 : slabdata      4      4      0 size-131072(DMA)       0      0 131072    1   32 : tunables    8    4    0 : slabdata      0      0      0 size-131072            1      1 131072    1   32 : tunables    8    4    0 : slabdata      1      1      0 size-65536(DMA)        0      0  65536    1   16 : tunables    8    4    0 : slabdata      0      0      0 size-65536             0      0  65536    1   16 : tunables    8    4    0 : slabdata      0      0      0 size-32768(DMA)        0      0  32768    1    8 : tunables    8    4    0 : slabdata      0      0      0 size-32768             1      1  32768    1    8 : tunables    8    4    0 : slabdata      1      1      0 size-16384(DMA)        0      0  16384    1    4 : tunables    8    4    0 : slabdata      0      0      0 size-16384             8      8  16384    1    4 : tunables    8    4    0 : slabdata      8      8      0 size-8192(DMA)         0      0   8192    1    2 : tunables    8    4    0 : slabdata      0      0      0 size-8192              3      3   8192    1    2 : tunables    8    4    0 : slabdata      3      3      0 size-4096(DMA)         0      0   4096    1    1 : tunables   24   12    0 : slabdata      0      0      0 size-4096            278    278   4096    1    1 : tunables   24   12    0 : slabdata    278    278      0 size-2048(DMA)         0      0   2048    2    1 : tunables   24   12    0 : slabdata      0      0      0 size-2048            292    292   2048    2    1 : tunables   24   12    0 : slabdata    146    146      0 size-1024(DMA)         0      0   1024    4    1 : tunables   54   27    0 : slabdata      0      0      0 size-1024             60     60   1024    4    1 : tunables   54   27    0 : slabdata     15     15      0 size-512(DMA)          0      0    512    8    1 : tunables   54   27    0 : slabdata      0      0      0 size-512             216    216    512    8    1 : tunables   54   27    0 : slabdata     27     27      0 size-256(DMA)          0      0    256   15    1 : tunables  120   60    0 : slabdata      0      0      0 size-256              76     90    256   15    1 : tunables  120   60    0 : slabdata      6      6      0 size-192(DMA)          0      0    192   20    1 : tunables  120   60    0 : slabdata      0      0      0 size-192             139    140    192   20    1 : tunables  120   60    0 : slabdata      7      7      0 size-128(DMA)          0      0    128   30    1 : tunables  120   60    0 : slabdata      0      0      0 size-128             857    870    128   30    1 : tunables  120   60    0 : slabdata     29     29      0 size-96(DMA)           0      0     96   40    1 : tunables  120   60    0 : slabdata      0      0      0 size-96             1049   1080     96   40    1 : tunables  120   60    0 : slabdata     27     27      0 size-64(DMA)           0      0     64   59    1 : tunables  120   60    0 : slabdata      0      0      0 size-64             4425   4425     64   59    1 : tunables  120   60    0 : slabdata     75     75      0 size-32(DMA)           0      0     32  113    1 : tunables  120   60    0 : slabdata      0      0      0 size-32             4633   4633     32  113    1 : tunables  120   60    0 : slabdata     41     41      0 kmem_cache           120    120    128   30    1 : tunables  120   60    0 : slabdata      4      4      0 

1 Answers

Answers 1

I think you have a tmpfs/ramfs filling up somewhere. Due to the way tmpfs/ramfs works, the space used by files on a tmpfs is counted as "Cached" by the Linux kernel. A file on a tmpfs/ramfs is essentially nothing more than an unbacked cache entry.

# echo 1 > /proc/sys/vm/drop_caches # grep '^Cached' /proc/meminfo Cached:          1341824 kB # dd if=/dev/zero of=/tmp/testfile bs=1G count=4 4+0 records in 4+0 records out 4294967296 bytes (4.3 GB) copied, 1.33696 s, 3.2 GB/s # grep '^Cached' /proc/meminfo Cached:          5543480 kB # echo 1 > /proc/sys/vm/drop_caches # grep '^Cached' /proc/meminfo Cached:          5494072 kB # rm /tmp/testfile # grep '^Cached' /proc/meminfo Cached:          1306488 kB 

This is "cache" memory that Linux can't reclaim automatically since it isn't backed by any real persistent storage. As you can see in the example, even drop_caches wouldn't help you.

So have a look in /proc/mounts for any tmpfs/ramfs that are mounted and monitor which of those are filling up.

Read More

Thursday, May 5, 2016

Relation between memory host and memory arguments xms and xmx from Java

Leave a Comment

I have the following host with the memory details:

$free -m              total       used       free     shared    buffers     cached Mem:          7872       7579        292         17        483       3983 -/+ buffers/cache:       3112       4759  Swap:         2047         14       2033 

I have a java app running with the params -Xms200m -Xmx200m, could someone please explain me why the VCZ is 3800076 and the RSS is 241304 (which is more of the Java params)

from the ps -aux command:

66345     6773  0.2  2.9 3800076 241304 ?      Sl   Apr1  12:06 /apps/myapps/myapp1/java/bin/java -Xms200m -Xmx200m 

1 Answers

Answers 1

Memory used by Java process (as seen by the OS) is not only limited to Java Heap. There are a lot more memory areas that should be also counted:

  • Metaspace (where class metadata resides);
  • Code Cache (storage for JIT-compiled methods and all the generated code);
  • Direct ByteBuffers;
  • Memory-mapped files, including files mapped by JVM, e.g. all JAR files on the classpath;
  • Thread stacks;
  • JVM code itself and all the dynamic libraries loaded by Java Runtime;
  • Other internal JVM structures.

Use NativeMemoryTracking JDK feature to get the detailed breakdown of memory areas used by JVM:

java -XX:NativeMemoryTracking=detail -XX:+UnlockDiagnosticVMOptions -XX:+PrintNMTStatistics 
Read More

Wednesday, April 20, 2016

How to see memory layout of my program in C during run-time?

Leave a Comment

I would like to see Memory layout of my program in C so that i can understand all the different segments of the Memory practically during run-time like change in BSS or Heap for ex ?

3 Answers

Answers 1

In Linux, for process PID, look at /proc/PID/maps and /proc/PID/smaps pseudofiles. (The process itself can use /proc/self/maps and /proc/self/smaps.)

Their contents are documented in man 5 proc.


Here's an example of how you might read the contents into a linked list of address range structures.

mem-stats.h:

#ifndef   MEM_STATS_H #define   MEM_STATS_H #include <stdlib.h> #include <sys/types.h>  #define PERMS_READ               1U #define PERMS_WRITE              2U #define PERMS_EXEC               4U #define PERMS_SHARED             8U #define PERMS_PRIVATE           16U  typedef struct address_range address_range; struct address_range {     struct address_range    *next;     void                    *start;     size_t                   length;     unsigned long            offset;     dev_t                    device;     ino_t                    inode;     unsigned char            perms;     char                     name[]; };  address_range *mem_stats(pid_t); void free_mem_stats(address_range *);  #endif /* MEM_STATS_H */ 

mem-stats.c:

#define _POSIX_C_SOURCE 200809L #define _BSD_SOURCE #include <stdlib.h> #include <sys/types.h> #include <string.h> #include <stdio.h> #include <errno.h> #include "mem-stats.h"  void free_mem_stats(address_range *list) {     while (list) {         address_range *curr = list;          list = list->next;          curr->next = NULL;         curr->length = 0;         curr->perms = 0U;         curr->name[0] = '\0';          free(curr);     } }  address_range *mem_stats(pid_t pid) {     address_range *list = NULL;     char          *line = NULL;     size_t         size = 0;     FILE          *maps;      if (pid > 0) {         char namebuf[128];         int  namelen;          namelen = snprintf(namebuf, sizeof namebuf, "/proc/%ld/maps", (long)pid);         if (namelen < 12) {             errno = EINVAL;             return NULL;         }          maps = fopen(namebuf, "r");     } else         maps = fopen("/proc/self/maps", "r");      if (!maps)         return NULL;      while (getline(&line, &size, maps) > 0) {         address_range *curr;         char           perms[8];         unsigned int   devmajor, devminor;         unsigned long  addr_start, addr_end, offset, inode;         int            name_start = 0;         int            name_end = 0;          if (sscanf(line, "%lx-%lx %7s %lx %u:%u %lu %n%*[^\n]%n",                          &addr_start, &addr_end, perms, &offset,                          &devmajor, &devminor, &inode,                          &name_start, &name_end) < 7) {             fclose(maps);             free(line);             free_mem_stats(list);             errno = EIO;             return NULL;         }          if (name_end <= name_start)             name_start = name_end = 0;          curr = malloc(sizeof (address_range) + (size_t)(name_end - name_start) + 1);         if (!curr) {             fclose(maps);             free(line);             free_mem_stats(list);             errno = ENOMEM;             return NULL;         }          if (name_end > name_start)             memcpy(curr->name, line + name_start, name_end - name_start);         curr->name[name_end - name_start] = '\0';          curr->start = (void *)addr_start;         curr->length = addr_end - addr_start;         curr->offset = offset;         curr->device = makedev(devmajor, devminor);         curr->inode = (ino_t)inode;          curr->perms = 0U;         if (strchr(perms, 'r'))             curr->perms |= PERMS_READ;         if (strchr(perms, 'w'))             curr->perms |= PERMS_WRITE;         if (strchr(perms, 'x'))             curr->perms |= PERMS_EXEC;         if (strchr(perms, 's'))             curr->perms |= PERMS_SHARED;         if (strchr(perms, 'p'))             curr->perms |= PERMS_PRIVATE;          curr->next = list;         list = curr;     }      free(line);      if (!feof(maps) || ferror(maps)) {         fclose(maps);         free_mem_stats(list);         errno = EIO;         return NULL;     }     if (fclose(maps)) {         free_mem_stats(list);         errno = EIO;         return NULL;     }      errno = 0;     return list; } 

An example program to use the above, example.c:

#include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <errno.h> #include "mem-stats.h"  int main(int argc, char *argv[]) {     int  arg, pid;     char dummy;      if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {         fprintf(stderr, "\n");         fprintf(stderr, "Usage: %s [ -h | --help ]\n", argv[0]);         fprintf(stderr, "       %s PID\n", argv[0]);         fprintf(stderr, "\n");         fprintf(stderr, "You can use PID 0 as an alias for the command itself.\n");         fprintf(stderr, "\n");         return EXIT_SUCCESS;     }      for (arg = 1; arg < argc; arg++)         if (sscanf(argv[arg], " %i %c", &pid, &dummy) == 1) {             address_range *list, *curr;              if (!pid)                 pid = getpid();              list = mem_stats((pid_t)pid);             if (!list) {                 fprintf(stderr, "Cannot obtain memory usage of process %d: %s.\n", pid, strerror(errno));                 return EXIT_FAILURE;             }              printf("Process %d:\n", pid);             for (curr = list; curr != NULL; curr = curr->next)                 printf("\t%p .. %p: %s\n", curr->start, (void *)((char *)curr->start + curr->length), curr->name);             printf("\n");             fflush(stdout);              free_mem_stats(list);          } else {             fprintf(stderr, "%s: Invalid PID.\n", argv[arg]);             return EXIT_FAILURE;         }      return EXIT_SUCCESS; } 

and a Makefile to make building it simple:

CC      := gcc CFLAGS  := -Wall -Wextra -O2 -fomit-frame-pointer LDFLAGS :=  PROGS   := example  .PHONY: all clean  all: clean $(PROGS)  clean:     rm -f *.o $(PROGS)  %.o: %.c     $(CC) $(CFLAGS) -c $^  example: mem-stats.o example.o     $(CC) $(CFLAGS) $^ $(LDFLAGS) -o $@ 

Note that the three indented lines in the Makefile above must use tab characters, not spaces. It seems that the editor here converts tabs to spaces, so you need to fix that, for example by using

sed -e 's|^  *|\t|' -i Makefile 

If you don't fix the indentation, and use spaces in a Makefile, you'll see an error message similar to *** missing separator. Stop.

Some editors automatically convert a tab keypress into a number of spaces, so you may need to delve into the editor settings of whatever editor you use. Often, editors keep a pasted tab character intact, so you can always try pasting a tab from another program.

To compile and run, save the above files and run

make ./example 0 

to print the memory ranges used by the example program itself. If you want to see, say, the memory ranges used by your PulseAudio daemon, run

./example $(ps -o pid= -C pulseaudio) 

Note that standard access restrictions apply. A normal user can only see the memory ranges of the processes that run as that user; otherwise you need superuser privileges (sudo or similar).

Answers 2

Another alternative is pmap tool which dumps the process memory mapping details:

    pmap [ -x | -d ] [ -q ] pids...     pmap -V 

pmap is part of procps collection.

Also if you are interest in physical mapping, you can take a look at pagemap, which is made available in recent Linux Kernel to let process know it's physical memory info. It might be useful for user space driver development where user space process need to find physical address of a buffer as DMA destination.

https://www.kernel.org/doc/Documentation/vm/pagemap.txt

Answers 3

If you're on Linux use gcore to get a static core dump, it's part of gdb...

gcore $pid > Corefile 

or

gcore -o core_dump $pid 

To debug a running program attach to it using gdb

gdb -p 1234 

then poke around in it. To see how it's layed out

(gdb) maint info sections Exec file:     `/home/foo/program', file type elf32-i386.  [0]     0x8048134->0x8048147 at 0x00000134: .interp ALLOC LOAD READONLY DATA HAS_CONTENTS  [1]     0x8048148->0x8048168 at 0x00000148: .note.ABI-tag ALLOC LOAD READONLY DATA HAS_CONTENTS  [2]     0x8048168->0x804818c at 0x00000168: .note.gnu.build-id ALLOC LOAD   ..... ..... [23]     0x8049a40->0x8049ad1 at 0x00000a40: .data ALLOC LOAD DATA HAS_CONTENTS [24]     0x8049ad1->0x8049ad4 at 0x00000ad1: .bss ALLOC 

To poke around in registers use

(gdb) info all-registers eax            0xfffffdfc   -516 ecx            0x0  0 edx            0x1  1 ebx            0xffeedc28   -1123288 esp            0xffeedc0c   0xffeedc0c ebp            0xffeedc78   0xffeedc78 esi            0x1308   4872 edi            0x45cf   17871 .... snipped 

If you want to see the assembly used for a particular function use disassemble. It can also be used with addresses in memory.

(gdb) disassemble main Dump of assembler code for function main:    0x080483f0 <+0>: lea    0x4(%esp),%ecx    0x080483f4 <+4>: and    $0xfffffff0,%esp    0x080483f7 <+7>: mov    $0x8048780,%edx    0x080483fc <+12>:    pushl  -0x4(%ecx)    0x080483ff <+15>:    push   %ebp    0x08048400 <+16>:    mov    %esp,%ebp    ....    .... 
Read More