DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (31ec81b5d7bb)

VCS Links

Line Code
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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsISupports.idl"

interface nsISimpleEnumerator;
interface nsIRunnable;
interface nsICancelableRunnable;

/*
 * Memory reporters measure Firefox's memory usage.  They are mainly used to
 * generate the about:memory page.  You should read
 * https://wiki.mozilla.org/Memory_Reporting before writing a memory
 * reporter.
 */

[scriptable, function, uuid(3a61be3b-b93b-461a-a4f8-388214f558b1)]
interface nsIMemoryReporterCallback : nsISupports
{
  /*
   * The arguments to the callback are as follows.
   *
   *
   * |process|  The name of the process containing this reporter.  Each
   * reporter initially has "" in this field, indicating that it applies to the
   * current process.  (This is true even for reporters in a child process.)
   * When a reporter from a child process is copied into the main process, the
   * copy has its 'process' field set appropriately.
   *
   *
   * |path|  The path that this memory usage should be reported under.  Paths
   * are '/'-delimited, eg. "a/b/c".
   *
   * Each reporter can be viewed as representing a leaf node in a tree.
   * Internal nodes of the tree don't have reporters.  So, for example, the
   * reporters "explicit/a/b", "explicit/a/c", "explicit/d/e", and
   * "explicit/d/f" define this tree:
   *
   *   explicit
   *   |--a
   *   |  |--b [*]
   *   |  \--c [*]
   *   \--d
   *      |--e [*]
   *      \--f [*]
   *
   * Nodes marked with a [*] have a reporter.  Notice that the internal
   * nodes are implicitly defined by the paths.
   *
   * Nodes within a tree should not overlap measurements, otherwise the
   * parent node measurements will be double-counted.  So in the example
   * above, |b| should not count any allocations counted by |c|, and vice
   * versa.
   *
   * All nodes within each tree must have the same units.
   *
   * If you want to include a '/' not as a path separator, e.g. because the
   * path contains a URL, you need to convert each '/' in the URL to a '\'.
   * Consumers of the path will undo this change.  Any other '\' character
   * in a path will also be changed.  This is clumsy but hasn't caused any
   * problems so far.
   *
   * The paths of all reporters form a set of trees.  Trees can be
   * "degenerate", i.e. contain a single entry with no '/'.
   *
   *
   * |kind|  There are three kinds of memory reporters.
   *
   *  - HEAP: reporters measuring memory allocated by the heap allocator,
   *    e.g. by calling malloc, calloc, realloc, memalign, operator new, or
   *    operator new[].  Reporters in this category must have units
   *    UNITS_BYTES.
   *
   *  - NONHEAP: reporters measuring memory which the program explicitly
   *    allocated, but does not live on the heap.  Such memory is commonly
   *    allocated by calling one of the OS's memory-mapping functions (e.g.
   *    mmap, VirtualAlloc, or vm_allocate).  Reporters in this category
   *    must have units UNITS_BYTES.
   *
   *  - OTHER: reporters which don't fit into either of these categories.
   *    They can have any units.
   *
   * The kind only matters for reporters in the "explicit" tree;
   * aboutMemory.js uses it to calculate "heap-unclassified".
   *
   *
   * |units|  The units on the reporter's amount.  One of the following.
   *
   *  - BYTES: The amount contains a number of bytes.
   *
   *  - COUNT: The amount is an instantaneous count of things currently in
   *    existence.  For instance, the number of tabs currently open would have
   *    units COUNT.
   *
   *  - COUNT_CUMULATIVE: The amount contains the number of times some event
   *    has occurred since the application started up.  For instance, the
   *    number of times the user has opened a new tab would have units
   *    COUNT_CUMULATIVE.
   *
   *    The amount returned by a reporter with units COUNT_CUMULATIVE must
   *    never decrease over the lifetime of the application.
   *
   *  - PERCENTAGE: The amount contains a fraction that should be expressed as
   *    a percentage.  NOTE!  The |amount| field should be given a value 100x
   *    the actual percentage;  this number will be divided by 100 when shown.
   *    This allows a fractional percentage to be shown even though |amount| is
   *    an integer.  E.g. if the actual percentage is 12.34%, |amount| should
   *    be 1234.
   *
   *    Values greater than 100% are allowed.
   *
   *
   * |amount|  The numeric value reported by this memory reporter.  Accesses
   * can fail if something goes wrong when getting the amount.
   *
   *
   * |description|  A human-readable description of this memory usage report.
   */
  void callback(in ACString process, in AUTF8String path, in int32_t kind,
                in int32_t units, in int64_t amount,
                in AUTF8String description, in nsISupports closure);
};

/*
 * An nsIMemoryReporter reports one or more memory measurements via a
 * callback function which is called once for each measurement.
 *
 * An nsIMemoryReporter that reports a single measurement is sometimes called a
 * "uni-reporter".  One that reports multiple measurements is sometimes called
 * a "multi-reporter".
 *
 * aboutMemory.js is the most important consumer of memory reports.  It
 * places the following constraints on reports.
 *
 * - There must be an "explicit" tree.  It represents non-overlapping
 *   regions of memory that have been explicitly allocated with an
 *   OS-level allocation (e.g. mmap/VirtualAlloc/vm_allocate) or a
 *   heap-level allocation (e.g. malloc/calloc/operator new).  Reporters
 *   in this tree must have kind HEAP or NONHEAP, units BYTES, and a
 *   description that is a sentence (i.e. starts with a capital letter and
 *   ends with a period, or similar).
 *
 * - The "redundant" tree is optional, and can be used for reports that are
 *   redundant w.r.t. other reports.  These are useful for telemetry, and are
 *   not shown in about:memory.  Reports in this tree are entirely
 *   unconstrained.
 *
 * - All other reports are unconstrained except that they must have a
 *   description that is a sentence.
 */
[scriptable, uuid(53248304-124b-43cd-99dc-6e5797b91618)]
interface nsIMemoryReporter : nsISupports
{
  /*
   * The name of the reporter.  Useful when only one reporter needs to be run.
   * Must be unique;  if reporters share names it's likely the wrong one will
   * be called in certain circumstances.
   */
  readonly attribute ACString name;

  /*
   * Run the reporter.
   */
  void collectReports(in nsIMemoryReporterCallback callback,
                      in nsISupports closure);

  /*
   * Kinds.  See the |kind| comment in nsIMemoryReporterCallback.
   */
  const int32_t KIND_NONHEAP = 0;
  const int32_t KIND_HEAP    = 1;
  const int32_t KIND_OTHER   = 2;

  /*
   * Units.  See the |units| comment in nsIMemoryReporterCallback.
   */
  const int32_t UNITS_BYTES = 0;
  const int32_t UNITS_COUNT = 1;
  const int32_t UNITS_COUNT_CUMULATIVE = 2;
  const int32_t UNITS_PERCENTAGE = 3;
};

[scriptable, builtinclass, uuid(4db7040a-16f9-4249-879b-fe72729c7ef5)]
interface nsIMemoryReporterManager : nsISupports
{
  /*
   * Return an enumerator of nsIMemoryReporters that are currently registered.
   */
  nsISimpleEnumerator enumerateReporters ();

  /*
   * Register the given nsIMemoryReporter.  After a reporter is registered,
   * it will be available via enumerateReporters().  The Manager service
   * will hold a strong reference to the given reporter.
   */
  void registerReporter (in nsIMemoryReporter reporter);

  /*
   * Unregister the given memory reporter.
   */
  void unregisterReporter (in nsIMemoryReporter reporter);

  /**
   * These functions should only be used for testing purposes.
   */
  void blockRegistration();
  void unblockRegistration();
  void registerReporterEvenIfBlocked(in nsIMemoryReporter aReporter);

  /*
   * Initialize.
   */
  void init ();

  /*
   * Get the resident size (aka. RSS, physical memory used).  This reporter
   * is special-cased because it's interesting and is available on most
   * platforms.  Accesses can fail.
   */
  readonly attribute int64_t resident;

  /*
   * Get the total size of explicit memory allocations, both at the OS-level
   * (eg. via mmap, VirtualAlloc) and at the heap level (eg. via malloc,
   * calloc, operator new).  (Nb: it covers all heap allocations, but will
   * miss any OS-level ones not covered by memory reporters.)  This reporter
   * is special-cased because it's interesting, and is difficult to compute
   * from JavaScript code.  Accesses can fail.
   */
  readonly attribute int64_t explicit;

  /*
   * This attribute indicates if moz_malloc_usable_size() works.
   */
  [infallible] readonly attribute boolean hasMozMallocUsableSize;

  /*
   * Run a series of GC/CC's in an attempt to minimize the application's memory
   * usage.  When we're finished, we invoke the given runnable if it's not
   * null.  Returns a reference to the runnable used for carrying out the task.
   */
  nsICancelableRunnable minimizeMemoryUsage(in nsIRunnable callback);
};

%{C++

#include "nsStringGlue.h"

// Note that the memory reporters are held in an nsCOMArray, which means
// that individual reporters should be referenced with |nsIMemoryReporter *|
// instead of nsCOMPtr<nsIMemoryReporter>.

XPCOM_API(nsresult) NS_RegisterMemoryReporter(nsIMemoryReporter* aReporter);
XPCOM_API(nsresult) NS_UnregisterMemoryReporter(nsIMemoryReporter* aReporter);

#if defined(MOZ_DMD)
namespace mozilla {
namespace dmd {
// This runs all the memory reporters but does nothing with the results;  i.e.
// it does the minimal amount of work possible for DMD to do its thing.
void RunReporters();
}
}

#if !defined(MOZ_MEMORY)
#error "MOZ_DMD requires MOZ_MEMORY"
#endif

#include "DMD.h"

#define MOZ_REPORT(ptr)          mozilla::dmd::Report(ptr)
#define MOZ_REPORT_ON_ALLOC(ptr) mozilla::dmd::ReportOnAlloc(ptr)

#else

#define MOZ_REPORT(ptr)
#define MOZ_REPORT_ON_ALLOC(ptr)

#endif  // defined(MOZ_DMD)

// Functions generated via this macro should be used by all traversal-based
// memory reporters.  Such functions return |moz_malloc_size_of(ptr)|;  this
// will always be zero on some obscure platforms.
//
// You might be wondering why we have a macro that creates multiple functions
// that differ only in their name, instead of a single
// MemoryReporterMallocSizeOf function.  It's mostly to help with DMD
// integration, though it sometimes also helps with debugging and temporary ad
// hoc profiling.  The function name chosen doesn't matter greatly, but it's
// best to make it similar to the path used by the relevant memory
// reporter(s).
#define NS_MEMORY_REPORTER_MALLOC_SIZEOF_FUN(fn)                              \
  static size_t fn(const void* aPtr)                                          \
  {                                                                           \
      MOZ_REPORT(aPtr);                                                       \
      return moz_malloc_size_of(aPtr);                                        \
  }

// Functions generated by the next two macros should be used by wrapping
// allocators that report heap blocks as soon as they are allocated and
// unreport them as soon as they are freed.  Such allocators are used in cases
// where we have third-party code that we cannot modify.  The two functions
// must always be used in tandem.
#define NS_MEMORY_REPORTER_MALLOC_SIZEOF_ON_ALLOC_FUN(fn)                     \
  static size_t fn(const void* aPtr)                                          \
  {                                                                           \
      MOZ_REPORT_ON_ALLOC(aPtr);                                              \
      return moz_malloc_size_of(aPtr);                                        \
  }
#define NS_MEMORY_REPORTER_MALLOC_SIZEOF_ON_FREE_FUN(fn)                      \
  static size_t fn(const void* aPtr)                                          \
  {                                                                           \
      return moz_malloc_size_of(aPtr);                                        \
  }

namespace mozilla {

// The following base class reduces the amount of boilerplate code required for
// memory uni-reporters.  You just need to provide the following.
// - The constant values: nameAndPath (which serves as both the reporters name,
//   and the path in its single report), kind, units, and description.  They
//   are passed to the MemoryUniReporter constructor.
// - A (private) Amount() or (public) GetAmount() method.  It can use the
//   MallocSizeOf method if necessary.  (There is also
//   MallocSizeOfOn{Alloc,Free}, which can be useful.)  Use Amount() if the
//   reporter is infallible, and GetAmount() otherwise.  (If you fail to
//   provide one or the other, you'll get assertion failures when the memory
//   reporter runs.)
//
// The class name of subclasses should match the path, minus the "explicit"
// (if present), and with "Reporter" at the end.  For example:
// - "explicit/dom/xyzzy"     --> DOMXyzzyReporter
// - "js-compartments/system" --> JSCompartmentsSystemReporter
//
class MemoryUniReporter : public nsIMemoryReporter
{
public:
  MemoryUniReporter(const char* aNameAndPath, int32_t aKind, int32_t aUnits,
                    const char* aDescription)
    : mNameAndPath(aNameAndPath)
    , mKind(aKind)
    , mUnits(aUnits)
    , mDescription(aDescription)
  {}

  virtual ~MemoryUniReporter() {}

  NS_DECL_THREADSAFE_ISUPPORTS

  NS_IMETHOD GetName(nsACString& aName)
  {
    aName.Assign(mNameAndPath);
    return NS_OK;
  }

  NS_IMETHOD CollectReports(nsIMemoryReporterCallback* aCallback,
                            nsISupports* aClosure)
  {
    int64_t amount;
    nsresult rv = GetAmount(&amount);
    NS_ENSURE_SUCCESS(rv, rv);

    return aCallback->Callback(EmptyCString(), mNameAndPath, mKind, mUnits,
                               amount, mDescription, aClosure);
  }

protected:
  NS_IMETHOD GetAmount(int64_t* aAmount)
  {
    *aAmount = Amount();
    return NS_OK;
  }

  virtual int64_t Amount()
  {
    // We only reach here if neither GetAmount() nor Amount() was overridden.
    MOZ_ASSERT(false);
    return 0;
  }

  NS_MEMORY_REPORTER_MALLOC_SIZEOF_FUN(MallocSizeOf)
  NS_MEMORY_REPORTER_MALLOC_SIZEOF_ON_ALLOC_FUN(MallocSizeOfOnAlloc)
  NS_MEMORY_REPORTER_MALLOC_SIZEOF_ON_FREE_FUN(MallocSizeOfOnFree)

  const nsCString mNameAndPath;
  const int32_t   mKind;
  const int32_t   mUnits;
  const nsCString mDescription;
};

// This CRTP class handles several details of wrapping allocators and should
// be preferred to manually counting with MOZ_DEFINE_MALLOC_SIZE_OF_ON_ALLOC
// and MOZ_DEFINE_MALLOC_SIZE_OF_ON_FREE.  The typical use is in a memory
// reporter for a particular third party library:
//
//   class MyMemoryReporter : public CountingAllocatorBase<MyMemoryReporter>
//   {
//     ...
//     NS_IMETHODIMP
//     CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData)
//     {
//        return MOZ_COLLECT_REPORTER(
//          "explicit/path/to/somewhere", KIND_HEAP, UNITS_BYTES,
//          MemoryAllocated(),
//          "A description of what we are reporting."
//     }
//   };
//
//   ...somewhere later in the code...
//   SetThirdPartyMemoryFunctions(MyMemoryReporter::CountingAlloc,
//                                MyMemoryReporter::CountingFree);
template<typename T>
class CountingAllocatorBase
{
public:
  CountingAllocatorBase()
  {
#ifdef DEBUG
    // There must be only one instance of this class, due to |sAmount| being
    // static.
    static bool hasRun = false;
    MOZ_ASSERT(!hasRun);
    hasRun = true;
#endif
  }

  static size_t
  MemoryAllocated()
  {
    return sAmount;
  }

  static void*
  CountingMalloc(size_t size)
  {
    void* p = malloc(size);
    sAmount += MallocSizeOfOnAlloc(p);
    return p;
  }

  static void*
  CountingCalloc(size_t nmemb, size_t size)
  {
    void* p = calloc(nmemb, size);
    sAmount += MallocSizeOfOnAlloc(p);
    return p;
  }

  static void*
  CountingRealloc(void* p, size_t size)
  {
    size_t oldsize = MallocSizeOfOnFree(p);
    void *pnew = realloc(p, size);
    if (pnew) {
      size_t newsize = MallocSizeOfOnAlloc(pnew);
      sAmount += newsize - oldsize;
    } else if (size == 0) {
      // We asked for a 0-sized (re)allocation of some existing pointer
      // and received NULL in return.  0-sized allocations are permitted
      // to either return NULL or to allocate a unique object per call (!).
      // For a malloc implementation that chooses the second strategy,
      // that allocation may fail (unlikely, but possible).
      //
      // Given a NULL return value and an allocation size of 0, then, we
      // don't know if that means the original pointer was freed or if
      // the allocation of the unique object failed.  If the original
      // pointer was freed, then we have nothing to do here.  If the
      // allocation of the unique object failed, the original pointer is
      // still valid and we ought to undo the decrement from above.
      // However, we have no way of knowing how the underlying realloc
      // implementation is behaving.  Assuming that the original pointer
      // was freed is the safest course of action.  We do, however, need
      // to note that we freed memory.
      sAmount -= oldsize;
    } else {
      // realloc failed.  The amount allocated hasn't changed.
    }
    return pnew;
  }

  static void
  CountingFree(void* p)
  {
    sAmount -= MallocSizeOfOnFree(p);
    free(p);
  }

private:
  // |sAmount| can be (implicitly) accessed by multiple threads, so it
  // must be thread-safe.
  static Atomic<size_t> sAmount;

  NS_MEMORY_REPORTER_MALLOC_SIZEOF_ON_ALLOC_FUN(MallocSizeOfOnAlloc)
  NS_MEMORY_REPORTER_MALLOC_SIZEOF_ON_FREE_FUN(MallocSizeOfOnFree)
};

} // namespace mozilla

%}