summaryrefslogtreecommitdiff
path: root/libjava/gnu/gcj/tools/gc_analyze/MemoryAnalyze.java
blob: d56a71da31164af943bb71787cf9fcfa7273c054 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/* MemoryAnalyze.java -- Analyzes a libgcj heap dump.
   Copyright (C) 2007  Free Software Foundation

   This file is part of libgcj.

This software is copyrighted work licensed under the terms of the
Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
details.  */

package gnu.gcj.tools.gc_analyze;

import gnu.classpath.tools.getopt.FileArgumentCallback;
import gnu.classpath.tools.getopt.Option;
import gnu.classpath.tools.getopt.OptionException;
import gnu.classpath.tools.getopt.Parser;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

class MemoryAnalyze
{
  public MemoryAnalyze()
  {
  }

  private static NumberFormat numberFormat;
  private static boolean verbose;
  static String format(long number, int digits)
  {
    if (numberFormat == null)
      {
        numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setGroupingUsed(true);
      }
    String temp = numberFormat.format(number);
    int spaces = digits - temp.length();
    if (spaces < 0)
      spaces = 0;
    return "                                ".substring(0,spaces) + temp;
  }

  static void sorted_report(String description,
                            int total_space,
                            ArrayList<String> list,
                            Comparator<String> comparator)
  {
    System.out.println("*** " + description + " ***");
    System.out.println();
    System.out.println("  Total Size       Count       Size    Description");
    System.out.println("--------------     -----    --------   -----------------------------------");
    Collections.sort(list, comparator);
    for (Iterator it = list.iterator(); it.hasNext(); )
      {
        String v = (String)it.next();
        System.out.println(stripend(v));
      }
    System.out.println("--------------     -----    --------   -----------------------------------");
    System.out.println(format(total_space, 14));
    System.out.println();
    System.out.println();
  }

  private static String stripend(String s)
  {
    int n = s.lastIndexOf(" /");
    if (n > 0)
      return s.substring(0,n);
    return s;
  }

  static  class SubstringComparator implements Comparator<String>
  {
    private int begin, end;
    private boolean reverse;

    SubstringComparator(int begin, int end, boolean reverse)
    {
      this.begin = begin;
      this.end = end;
      this.reverse = reverse;
    }

    public int compare(String s1, String s2)
    {
      if (end == 0)
        s1 = s1.substring(begin);
      else
        s1 = s1.substring(begin, end);

      if (end == 0)
        s2 = s2.substring(begin);
      else
        s2 = s2.substring(begin, end);
      int i = s1.compareTo(s2);
      if (reverse)
        return -i;
      return i;
    }
  }

  static class OptionParser extends Parser
  {
    int filesFound;
	  
    OptionParser()
    {
      super("gc-analyze",
            "gc-analyze (" + System.getProperty("java.vm.version") + ")");

      add(new Option('d',
                     "Directory containing runtime objects",
                     "directory")
        {
          public void parsed(String argument) throws OptionException
          {
            ToolPrefix.pathPrefix = argument;			
          }
        });

      add(new Option('p',
                     "Binary tool prefix, prepended to nm and readelf to "
                     + "obtain target specific versions of these commands",
                     "prefix")
        {
          public void parsed(String argument) throws OptionException
          {
            ToolPrefix.toolPrefix = argument;			
          }
        });

      add(new Option("verbose", 'v',
                     "Verbose output; requires filename.bytes")
        {
          public void parsed(String argument) throws OptionException
          {
            verbose = true;			
          }
        });

      setHeader("usage: gc-analyze [-v] [-p tool-prefix] [-d <directory>] "
                + "filename");
    }
	  
    protected void validate() throws OptionException
    {
      if (filesFound != 1)
        throw new OptionException("Must specify exactly one filename");
    }
	  
    public String[] parse(String[] inArgs)
    {
      final ArrayList<String> fileResult = new ArrayList<String>();
      parse(inArgs, new FileArgumentCallback()
        {
          public void notifyFile(String fileArgument)
          {
            filesFound++;
            fileResult.add(fileArgument);
          }
        });
      return fileResult.toArray(new String[1]);
    }
  }
  
  public static void main(String[] args)
  {
    class Info
    {
      int size;
      int count;
    }
    int total_space = 0;

    Parser optionParser = new OptionParser();
    
    String rest[] = optionParser.parse(args);
    
    String filename = rest[0];
    
    try
      {
        BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
        SymbolLookup lookup = new SymbolLookup(reader, filename + ".bytes");
        ObjectMap objectMap = new ObjectMap(reader);
        BlockMap blockMap = new BlockMap(reader);
        reader.close();

        // add info to item(s)
        // add item.klass
        for (Map.Entry<Long, ObjectMap.ObjectItem> me : objectMap)
        {
            ObjectMap.ObjectItem item = me.getValue();

            // try to get a klass (happens with intern'ed strings...)
            if (item.klass==0)
              {
                BytePtr p = lookup.getBytePtr(item.ptr, item.size);
                if (p!=null)
                  {
                    long vtable = p.getWord(0);
                    String sym =
                        lookup.getSymbolViaVtable(vtable - 2 * lookup.memoryMap.wordSize);
                    if (sym != null)
                      {
                        item.typeName = SymbolTable.demangleVTName(sym);
                      }
                    else if (vtable != 0)
                      {
                        // get klass from vtable
                        p = lookup.getBytePtr(vtable,
                                              lookup.memoryMap.wordSize);
                        if (p != null)
                          {
                            long klass = p.getWord(0);
                            item.klass = klass;
                          }
                      }
                  }
              }

            // figure out strings
            String class_name;
            if (null == item.typeName)
              {
                class_name =
                  MemoryAnalyze.getSymbolPretty(lookup, item, false);
                item.typeName = class_name;
              }
            else
              {
                class_name = item.typeName;
              }
            System.out.print("class_name=[" + class_name + "]");

            if (class_name.compareTo("_ZTVN4java4lang6StringE")==0
                || class_name.compareTo("java.lang.String")==0)
              {
                BytePtr p = lookup.getBytePtr(item.ptr, item.size);
                long data = p.getWord(1); 
                int boffset = p.getInt(2 * p.intsPerWord());
                int count = p.getInt(1 + 2 * p.intsPerWord());
                int hash = p.getInt(2 + 2 * p.intsPerWord());
                BytePtr chars = lookup.getBytePtr(data+boffset, count * 2);
                StringBuffer sb = new StringBuffer(count);
                for (int qq = 0; qq<count; qq++)
                  sb.append((char)chars.getShort(qq));
                int newhash = sb.toString().hashCode();
                if (newhash!=hash)
                  {
                    p.setInt(4, newhash);
                  }

                item.string = sb.toString();
                System.out.println(" value = \"" + item.string + "\"");
                if (data != item.ptr)
                  {
                    ObjectMap.ObjectItem next = objectMap.get(data);
                    if (next != null)
                      next.stringData = true;
                    else
                      System.out.println("String [" + item.string + "] at "
                                         + Long.toHexString(item.ptr)
                                         + " can't find array at " 
                                         + Long.toHexString(data));
                  }
              }
            else if (null != item.string)
              System.out.println(" value = \"" + item.string + "\"");
            else
              System.out.println();
          }


        HashMap<String, Info> map = new HashMap<String, Info>();
        for (Map.Entry<Long, ObjectMap.ObjectItem> me : objectMap)
          {
            ObjectMap.ObjectItem item = me.getValue();
            String name = getSymbolPretty(lookup, item, true);
            Info info = map.get(name);
            if (info == null)
              {
                info = new Info();
                info.count = 0;
                info.size = item.size;
                map.put(name, info);
              }
            info.count++;
            total_space += item.size;
          }

        ArrayList<String> list = new ArrayList<String>();
        for (Iterator it = map.entrySet().iterator(); it.hasNext(); )
          {
            Map.Entry me = (Map.Entry)it.next();
            String name = (String)me.getKey();
            Info info = (Info)me.getValue();

            StringBuffer sb = new StringBuffer();
            sb.append(format(info.count * info.size * 100 / total_space,
                             3));
            sb.append("%");
            sb.append(format(info.count * info.size, 10));
            sb.append(" = ");
            sb.append(format(info.count, 7));
            sb.append(" * ");
            sb.append(format(info.size, 9));
            sb.append(" - ");
            sb.append(name);
            list.add(sb.toString());
          }

        sorted_report("Memory Usage Sorted by Total Size",
                      total_space, list, new SubstringComparator(5,14,true));
        sorted_report("Memory Usage Sorted by Description",
                      total_space, list, new SubstringComparator(39,0,false));
        sorted_report("Memory Usage Sorted by Count",
                      total_space, list, new SubstringComparator(17,25,true));
        sorted_report("Memory Usage Sorted by Size",
                      total_space, list, new SubstringComparator(28,37,true));

        blockMap.dump();

        // dump raw memory
        if (verbose)
          {
            // analyze references
            for (Map.Entry<Long, ObjectMap.ObjectItem> me : objectMap)
              {
                long ptr = me.getKey();
                ObjectMap.ObjectItem item = me.getValue();
                BytePtr p = lookup.getBytePtr(ptr, item.size);
                if (p == null)
                  System.out.println("can't find ptr 0x"
                                     + Long.toHexString(ptr));
                else if (item.kind != 0) // not GC_PTRFREE
                  for (int i = 1;
                       i < item.size / lookup.memoryMap.wordSize; i++)
                    {
                      long maybe_ptr = p.getWord(i);
                      ObjectMap.ObjectItem item2 = objectMap.get(maybe_ptr);
                      if (item2 != null)
                        {
                          item2.pointed_by.add(item);
                          item.points_to.add(item2);
                        }
                    }
              }
            System.out.println();
            System.out.println("*** All Objects ***");
            System.out.println();

            for (Map.Entry<Long, ObjectMap.ObjectItem> me : objectMap)
            {
              long ptr = me.getKey();
              ObjectMap.ObjectItem item = me.getValue();
              String name = getSymbolPretty(lookup, item, false);
              System.out.print("0x" + Long.toHexString(ptr) + " - " + name
                               + " (" + item.size + ")");
              if (item.string != null)
        	System.out.println(" \"" + item.string + "\"");
              else
        	System.out.println();

              BytePtr p = lookup.getBytePtr(ptr, item.size);

              if (p == null)
                System.out.println(
                  "can't find memory; recently allocated from free list?");
              else
                p.dump();

              item.points_to.dump("  points to:", lookup);
              item.pointed_by.dump("  pointed to by:", lookup);
              System.out.println();
            }
          }
      }
    catch (IOException e)
      {
        e.printStackTrace();
      }
  }

  public static String kindToName(int kind)
  {
    String name;
    switch (kind)
      {
      case 0:
        name = "GC_PTRFREE";
        break;
      case 1:
        name = "GC_NORMAL";
        break;
      case 2:
        name = "GC_UNCOLLECTABLE";
        break;
      case 3:
        name = "GC_AUUNCOLLCTABLE";
        break;
      case 4:
        name = "(Java)";
        break;
      case 5:
        name = "(Java Debug)";
        break;
      case 6:
        name = "(Java Array)";
        break;
      default:
        name = "(Kind " + kind + ")";
        break;
      }
    return name;
  }

  public static String getSymbolPretty(SymbolLookup lookup,
                                       ObjectMap.ObjectItem item,
                                       boolean bsize)
    throws IOException
  {
    
    String name = item.typeName;
    
    if (name == null)
      name = lookup.getSymbol(item.klass);
    
    if (name == null)
      {
      	String v = lookup.decodeUTF8(item.ptr, item.size);
      	if (null != v)
      	  {
      	    name = "UTF8Const";
      	    item.string = v;
      	  }
      }
    
    if (name == null)
      {
        name = kindToName(item.kind);
      }
    if (item.kind==6)
      name += "[" + format(item.data, 0) + "]";
    if (bsize)
      name = name + " / " + format(item.size, 7);
    return name;
  }
}