keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
mcellteam/mcell
libs/jsoncpp/example/readFromString/readFromString.cpp
.cpp
1,094
38
#include "json/json.h" #include <iostream> /** * \brief Parse a raw string into Value object using the CharReaderBuilder * class, or the legacy Reader class. * Example Usage: * $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString * $./readFromString * colin * 20 */ int main() { const std::string rawJson = R"({"Age": 20, "Name": "colin"})"; const auto rawJsonLength = static_cast<int>(rawJson.length()); constexpr bool shouldUseOldWay = false; JSONCPP_STRING err; Json::Value root; if (shouldUseOldWay) { Json::Reader reader; reader.parse(rawJson, root); } else { Json::CharReaderBuilder builder; const std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root, &err)) { std::cout << "error" << std::endl; return EXIT_FAILURE; } } const std::string name = root["Name"].asString(); const int age = root["Age"].asInt(); std::cout << name << std::endl; std::cout << age << std::endl; return EXIT_SUCCESS; }
C++
3D
mcellteam/mcell
libs/jsoncpp/example/stringWrite/stringWrite.cpp
.cpp
785
34
#include "json/json.h" #include <iostream> /** \brief Write a Value object to a string. * Example Usage: * $g++ stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite * $./stringWrite * { * "action" : "run", * "data" : * { * "number" : 1 * } * } */ int main() { Json::Value root; Json::Value data; constexpr bool shouldUseOldWay = false; root["action"] = "run"; data["number"] = 1; root["data"] = data; if (shouldUseOldWay) { Json::FastWriter writer; const std::string json_file = writer.write(root); std::cout << json_file << std::endl; } else { Json::StreamWriterBuilder builder; const std::string json_file = Json::writeString(builder, root); std::cout << json_file << std::endl; } return EXIT_SUCCESS; }
C++
3D
mcellteam/mcell
libs/jsoncpp/example/readFromStream/readFromStream.cpp
.cpp
727
31
#include "json/json.h" #include <fstream> #include <iostream> /** \brief Parse from stream, collect comments and capture error info. * Example Usage: * $g++ readFromStream.cpp -ljsoncpp -std=c++11 -o readFromStream * $./readFromStream * // comment head * { * // comment before * "key" : "value" * } * // comment after * // comment tail */ int main(int argc, char* argv[]) { Json::Value root; std::ifstream ifs; ifs.open(argv[1]); Json::CharReaderBuilder builder; builder["collectComments"] = true; JSONCPP_STRING errs; if (!parseFromStream(builder, ifs, &root, &errs)) { std::cout << errs << std::endl; return EXIT_FAILURE; } std::cout << root << std::endl; return EXIT_SUCCESS; }
C++
3D
mcellteam/mcell
libs/jsoncpp/example/streamWrite/streamWrite.cpp
.cpp
500
23
#include "json/json.h" #include <iostream> /** \brief Write the Value object to a stream. * Example Usage: * $g++ streamWrite.cpp -ljsoncpp -std=c++11 -o streamWrite * $./streamWrite * { * "Age" : 20, * "Name" : "robin" * } */ int main() { Json::Value root; Json::StreamWriterBuilder builder; const std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); root["Name"] = "robin"; root["Age"] = 20; writer->write(root, &std::cout); return EXIT_SUCCESS; }
C++
3D
mcellteam/mcell
libs/win_getopt/win_getopt.h
.h
18,500
654
#ifndef __GETOPT_H__ /** * DISCLAIMER * This file is part of the mingw-w64 runtime package. * * The mingw-w64 runtime package and its code is distributed in the hope that it * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Sponsored in part by the Defense Advanced Research Projects * Agency (DARPA) and Air Force Research Laboratory, Air Force * Materiel Command, USAF, under agreement number F39502-99-1-0512. */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #pragma warning(disable:4996) #define __GETOPT_H__ /* All the headers include this file. */ #include <crtdefs.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdio.h> //#include <windows.h> #ifdef __cplusplus extern "C" { #endif #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ #ifdef REPLACE_GETOPT int opterr = 1; /* if error message should be printed */ int optind = 1; /* index into parent argv vector */ int optopt = '?'; /* character checked for validity */ #undef optreset /* see getopt.h */ #define optreset __mingw_optreset int optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #endif //extern int optind; /* index of first non-option in argv */ //extern int optopt; /* single option character, as parsed */ //extern int opterr; /* flag to enable built-in diagnostics... */ // /* (user may set to zero, to suppress) */ // //extern char *optarg; /* pointer to argument of current option */ #define PRINT_ERROR ((opterr) && (*options != ':')) #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ /* return values */ #define BADCH (int)'?' #define BADARG ((*options == ':') ? (int)':' : (int)'?') #define INORDER (int)1 #ifndef __CYGWIN__ #define __progname __argv[0] #else extern char __declspec(dllimport) *__progname; #endif #ifdef __CYGWIN__ static char EMSG[] = ""; #else #define EMSG "" #endif static int getopt_internal(int, char * const *, const char *, const struct option *, int *, int); static int parse_long_options(char * const *, const char *, const struct option *, int *, int); static int gcd(int, int); static void permute_args(int, int, int, char * const *); static char *place = EMSG; /* option letter processing */ /* XXX: set optreset to 1 rather than these two */ static int nonopt_start = -1; /* first non option argument (for permute) */ static int nonopt_end = -1; /* first option after non options (for permute) */ /* Error messages */ static const char recargchar[] = "option requires an argument -- %c"; static const char recargstring[] = "option requires an argument -- %s"; static const char ambig[] = "ambiguous option -- %.*s"; static const char noarg[] = "option doesn't take an argument -- %.*s"; static const char illoptchar[] = "unknown option -- %c"; static const char illoptstring[] = "unknown option -- %s"; static void _vwarnx(const char *fmt,va_list ap) { (void)fprintf(stderr,"%s: ",__progname); if (fmt != NULL) (void)vfprintf(stderr,fmt,ap); (void)fprintf(stderr,"\n"); } static void warnx(const char *fmt,...) { va_list ap; va_start(ap,fmt); _vwarnx(fmt,ap); va_end(ap); } /* * Compute the greatest common divisor of a and b. */ static int gcd(int a, int b) { int c; c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return (b); } /* * Exchange the block from nonopt_start to nonopt_end with the block * from nonopt_end to opt_end (keeping the same order of arguments * in each block). */ static void permute_args(int panonopt_start, int panonopt_end, int opt_end, char * const *nargv) { int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; char *swap; /* * compute lengths of blocks and number and size of cycles */ nnonopts = panonopt_end - panonopt_start; nopts = opt_end - panonopt_end; ncycle = gcd(nnonopts, nopts); cyclelen = (opt_end - panonopt_start) / ncycle; for (i = 0; i < ncycle; i++) { cstart = panonopt_end+i; pos = cstart; for (j = 0; j < cyclelen; j++) { if (pos >= panonopt_end) pos -= nnonopts; else pos += nopts; swap = nargv[pos]; /* LINTED const cast */ ((char **) nargv)[pos] = nargv[cstart]; /* LINTED const cast */ ((char **)nargv)[cstart] = swap; } } } #ifdef REPLACE_GETOPT /* * getopt -- * Parse argc/argv argument vector. * * [eventually this will replace the BSD getopt] */ int getopt(int nargc, char * const *nargv, const char *options) { /* * We don't pass FLAG_PERMUTE to getopt_internal() since * the BSD getopt(3) (unlike GNU) has never done this. * * Furthermore, since many privileged programs call getopt() * before dropping privileges it makes sense to keep things * as simple (and bug-free) as possible. */ return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); } #endif /* REPLACE_GETOPT */ //extern int getopt(int nargc, char * const *nargv, const char *options); #ifdef _BSD_SOURCE /* * BSD adds the non-standard `optreset' feature, for reinitialisation * of `getopt' parsing. We support this feature, for applications which * proclaim their BSD heritage, before including this header; however, * to maintain portability, developers are advised to avoid it. */ # define optreset __mingw_optreset extern int optreset; #endif #ifdef __cplusplus } #endif /* * POSIX requires the `getopt' API to be specified in `unistd.h'; * thus, `unistd.h' includes this header. However, we do not want * to expose the `getopt_long' or `getopt_long_only' APIs, when * included in this manner. Thus, close the standard __GETOPT_H__ * declarations block, and open an additional __GETOPT_LONG_H__ * specific block, only when *not* __UNISTD_H_SOURCED__, in which * to declare the extended API. */ #endif /* !defined(__GETOPT_H__) */ #if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) #define __GETOPT_LONG_H__ #ifdef __cplusplus extern "C" { #endif struct option /* specification for a long form option... */ { const char *name; /* option name, without leading hyphens */ int has_arg; /* does it take an argument? */ int *flag; /* where to save its status, or NULL */ int val; /* its associated status value */ }; enum /* permitted values for its `has_arg' field... */ { no_argument = 0, /* option never takes an argument */ required_argument, /* option always requires an argument */ optional_argument /* option may take an argument */ }; /* * parse_long_options -- * Parse long options in argc/argv argument vector. * Returns -1 if short_too is set and the option does not match long_options. */ static int parse_long_options(char * const *nargv, const char *options, const struct option *long_options, int *idx, int short_too) { char *current_argv, *has_equal; size_t current_argv_len; int i, ambiguous, match; #define IDENTICAL_INTERPRETATION(_x, _y) \ (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \ long_options[(_x)].flag == long_options[(_y)].flag && \ long_options[(_x)].val == long_options[(_y)].val) current_argv = place; match = -1; ambiguous = 0; optind++; if ((has_equal = strchr(current_argv, '=')) != NULL) { /* argument found (--option=arg) */ current_argv_len = has_equal - current_argv; has_equal++; } else current_argv_len = strlen(current_argv); for (i = 0; long_options[i].name; i++) { /* find matching long option */ if (strncmp(current_argv, long_options[i].name, current_argv_len)) continue; if (strlen(long_options[i].name) == current_argv_len) { /* exact match */ match = i; ambiguous = 0; break; } /* * If this is a known short option, don't allow * a partial match of a single character. */ if (short_too && current_argv_len == 1) continue; if (match == -1) /* partial match */ match = i; else if (!IDENTICAL_INTERPRETATION(i, match)) ambiguous = 1; } if (ambiguous) { /* ambiguous abbreviation */ if (PRINT_ERROR) warnx(ambig, (int)current_argv_len, current_argv); optopt = 0; return (BADCH); } if (match != -1) { /* option found */ if (long_options[match].has_arg == no_argument && has_equal) { if (PRINT_ERROR) warnx(noarg, (int)current_argv_len, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; return (BADARG); } if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) { if (has_equal) optarg = has_equal; else if (long_options[match].has_arg == required_argument) { /* * optional argument doesn't use next nargv */ optarg = nargv[optind++]; } } if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) { /* * Missing argument; leading ':' indicates no error * should be generated. */ if (PRINT_ERROR) warnx(recargstring, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; --optind; return (BADARG); } } else { /* unknown option */ if (short_too) { --optind; return (-1); } if (PRINT_ERROR) warnx(illoptstring, current_argv); optopt = 0; return (BADCH); } if (idx) *idx = match; if (long_options[match].flag) { *long_options[match].flag = long_options[match].val; return (0); } else return (long_options[match].val); #undef IDENTICAL_INTERPRETATION } /* * getopt_internal -- * Parse argc/argv argument vector. Called by user level routines. */ static int getopt_internal(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx, int flags) { char *oli; /* option letter list index */ int optchar, short_too; static int posixly_correct = -1; if (options == NULL) return (-1); /* * XXX Some GNU programs (like cvs) set optind to 0 instead of * XXX using optreset. Work around this braindamage. */ if (optind == 0) optind = optreset = 1; /* * Disable GNU extensions if POSIXLY_CORRECT is set or options * string begins with a '+'. * * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or * optreset != 0 for GNU compatibility. */ if (posixly_correct == -1 || optreset != 0) posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); if (*options == '-') flags |= FLAG_ALLARGS; else if (posixly_correct || *options == '+') flags &= ~FLAG_PERMUTE; if (*options == '+' || *options == '-') options++; optarg = NULL; if (optreset) nonopt_start = nonopt_end = -1; start: if (optreset || !*place) { /* update scanning pointer */ optreset = 0; if (optind >= nargc) { /* end of argument vector */ place = EMSG; if (nonopt_end != -1) { /* do permutation, if we have to */ permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } else if (nonopt_start != -1) { /* * If we skipped non-options, set optind * to the first of them. */ optind = nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } if (*(place = nargv[optind]) != '-' || (place[1] == '\0' && strchr(options, '-') == NULL)) { place = EMSG; /* found non-option */ if (flags & FLAG_ALLARGS) { /* * GNU extension: * return non-option as argument to option 1 */ optarg = nargv[optind++]; return (INORDER); } if (!(flags & FLAG_PERMUTE)) { /* * If no permutation wanted, stop parsing * at first non-option. */ return (-1); } /* do permutation */ if (nonopt_start == -1) nonopt_start = optind; else if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); nonopt_start = optind - (nonopt_end - nonopt_start); nonopt_end = -1; } optind++; /* process next argument */ goto start; } if (nonopt_start != -1 && nonopt_end == -1) nonopt_end = optind; /* * If we have "-" do nothing, if "--" we are done. */ if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { optind++; place = EMSG; /* * We found an option (--), so if we skipped * non-options, we have to permute. */ if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } } /* * Check long options if: * 1) we were passed some * 2) the arg is not just "-" * 3) either the arg starts with -- we are getopt_long_only() */ if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) { short_too = 0; if (*place == '-') place++; /* --foo long option */ else if (*place != ':' && strchr(options, *place) != NULL) short_too = 1; /* could be short option too */ optchar = parse_long_options(nargv, options, long_options, idx, short_too); if (optchar != -1) { place = EMSG; return (optchar); } } if ((optchar = (int)*place++) == (int)':' || (optchar == (int)'-' && *place != '\0') || (oli = (char*)strchr(options, optchar)) == NULL) { /* * If the user specified "-" and '-' isn't listed in * options, return -1 (non-option) as per POSIX. * Otherwise, it is an unknown option character (or ':'). */ if (optchar == (int)'-' && *place == '\0') return (-1); if (!*place) ++optind; if (PRINT_ERROR) warnx(illoptchar, optchar); optopt = optchar; return (BADCH); } if (long_options != NULL && optchar == 'W' && oli[1] == ';') { /* -W long-option */ if (*place) /* no space */ /* NOTHING */; else if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) warnx(recargchar, optchar); optopt = optchar; return (BADARG); } else /* white space */ place = nargv[optind]; optchar = parse_long_options(nargv, options, long_options, idx, 0); place = EMSG; return (optchar); } if (*++oli != ':') { /* doesn't take argument */ if (!*place) ++optind; } else { /* takes (optional) argument */ optarg = NULL; if (*place) /* no white space */ optarg = place; else if (oli[1] != ':') { /* arg not optional */ if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) warnx(recargchar, optchar); optopt = optchar; return (BADARG); } else optarg = nargv[optind]; } place = EMSG; ++optind; } /* dump back option letter */ return (optchar); } /* * getopt_long -- * Parse argc/argv argument vector. */ int getopt_long(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE)); } /* * getopt_long_only -- * Parse argc/argv argument vector. */ int getopt_long_only(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE|FLAG_LONGONLY)); } //extern int getopt_long(int nargc, char * const *nargv, const char *options, // const struct option *long_options, int *idx); //extern int getopt_long_only(int nargc, char * const *nargv, const char *options, // const struct option *long_options, int *idx); /* * Previous MinGW implementation had... */ #ifndef HAVE_DECL_GETOPT /* * ...for the long form API only; keep this for compatibility. */ # define HAVE_DECL_GETOPT 1 #endif #ifdef __cplusplus } #endif #endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */
Unknown
3D
mcellteam/mcell
libs/gperftools/ltmain.sh
.sh
324,737
11,171
#! /bin/sh ## DO NOT EDIT - This file generated from ./build-aux/ltmain.in ## by inline-source v2014-01-03.01 # libtool (GNU libtool) 2.4.6 # Provide generalized library-building support services. # Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996 # Copyright (C) 1996-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. PROGRAM=libtool PACKAGE=libtool VERSION=2.4.6 package_revision=2.4.6 ## ------ ## ## Usage. ## ## ------ ## # Run './libtool --help' for help with using this script from the # command line. ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # After configure completes, it has a better idea of some of the # shell tools we need than the defaults used by the functions shared # with bootstrap, so set those here where they can still be over- # ridden by the user, but otherwise take precedence. : ${AUTOCONF="autoconf"} : ${AUTOMAKE="automake"} ## -------------------------- ## ## Source external libraries. ## ## -------------------------- ## # Much of our low-level functionality needs to be sourced from external # libraries, which are installed to $pkgauxdir. # Set a version string for this script. scriptversion=2015-01-20.17; # UTC # General shell script boiler plate, and helper functions. # Written by Gary V. Vaughan, 2004 # Copyright (C) 2004-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # As a special exception to the GNU General Public License, if you distribute # this file as part of a program or library that is built using GNU Libtool, # you may include this file under the same distribution terms that you use # for the rest of that program. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please report bugs or propose patches to gary@gnu.org. ## ------ ## ## Usage. ## ## ------ ## # Evaluate this file near the top of your script to gain access to # the functions and variables defined here: # # . `echo "$0" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh # # If you need to override any of the default environment variable # settings, do that before evaluating this file. ## -------------------- ## ## Shell normalisation. ## ## -------------------- ## # Some shells need a little help to be as Bourne compatible as possible. # Before doing anything else, make sure all that help has been provided! DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi # NLS nuisances: We save the old values in case they are required later. _G_user_locale= _G_safe_locale= for _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test set = \"\${$_G_var+set}\"; then save_$_G_var=\$$_G_var $_G_var=C export $_G_var _G_user_locale=\"$_G_var=\\\$save_\$_G_var; \$_G_user_locale\" _G_safe_locale=\"$_G_var=C; \$_G_safe_locale\" fi" done # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Make sure IFS has a sensible default sp=' ' nl=' ' IFS="$sp $nl" # There are apparently some retarded systems that use ';' as a PATH separator! if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi ## ------------------------- ## ## Locate command utilities. ## ## ------------------------- ## # func_executable_p FILE # ---------------------- # Check that FILE is an executable regular file. func_executable_p () { test -f "$1" && test -x "$1" } # func_path_progs PROGS_LIST CHECK_FUNC [PATH] # -------------------------------------------- # Search for either a program that responds to --version with output # containing "GNU", or else returned by CHECK_FUNC otherwise, by # trying all the directories in PATH with each of the elements of # PROGS_LIST. # # CHECK_FUNC should accept the path to a candidate program, and # set $func_check_prog_result if it truncates its output less than # $_G_path_prog_max characters. func_path_progs () { _G_progs_list=$1 _G_check_func=$2 _G_PATH=${3-"$PATH"} _G_path_prog_max=0 _G_path_prog_found=false _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:} for _G_dir in $_G_PATH; do IFS=$_G_save_IFS test -z "$_G_dir" && _G_dir=. for _G_prog_name in $_G_progs_list; do for _exeext in '' .EXE; do _G_path_prog=$_G_dir/$_G_prog_name$_exeext func_executable_p "$_G_path_prog" || continue case `"$_G_path_prog" --version 2>&1` in *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;; *) $_G_check_func $_G_path_prog func_path_progs_result=$func_check_prog_result ;; esac $_G_path_prog_found && break 3 done done done IFS=$_G_save_IFS test -z "$func_path_progs_result" && { echo "no acceptable sed could be found in \$PATH" >&2 exit 1 } } # We want to be able to use the functions in this file before configure # has figured out where the best binaries are kept, which means we have # to search for them ourselves - except when the results are already set # where we skip the searches. # Unless the user overrides by setting SED, search the path for either GNU # sed, or the sed that truncates its output the least. test -z "$SED" && { _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for _G_i in 1 2 3 4 5 6 7; do _G_sed_script=$_G_sed_script$nl$_G_sed_script done echo "$_G_sed_script" 2>/dev/null | sed 99q >conftest.sed _G_sed_script= func_check_prog_sed () { _G_path_prog=$1 _G_count=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo '' >> conftest.nl "$_G_path_prog" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "sed gsed" func_check_prog_sed $PATH:/usr/xpg4/bin rm -f conftest.sed SED=$func_path_progs_result } # Unless the user overrides by setting GREP, search the path for either GNU # grep, or the grep that truncates its output the least. test -z "$GREP" && { func_check_prog_grep () { _G_path_prog=$1 _G_count=0 _G_path_prog_max=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo 'GREP' >> conftest.nl "$_G_path_prog" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "grep ggrep" func_check_prog_grep $PATH:/usr/xpg4/bin GREP=$func_path_progs_result } ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # All uppercase variable names are used for environment variables. These # variables can be overridden by the user before calling a script that # uses them if a suitable command of that name is not already available # in the command search PATH. : ${CP="cp -f"} : ${ECHO="printf %s\n"} : ${EGREP="$GREP -E"} : ${FGREP="$GREP -F"} : ${LN_S="ln -s"} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} ## -------------------- ## ## Useful sed snippets. ## ## -------------------- ## sed_dirname='s|/[^/]*$||' sed_basename='s|^.*/||' # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='s|\([`"$\\]\)|\\\1|g' # Same as above, but do not quote variable references. sed_double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s|[].[^$\\*\/]|\\&|g' # Sed substitution that converts a w32 file name or path # that contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-'\' parameter expansions in output of sed_double_quote_subst that # were '\'-ed in input to the same. If an odd number of '\' preceded a # '$' in input to sed_double_quote_subst, that '$' was protected from # expansion. Since each input '\' is now two '\'s, look for any number # of runs of four '\'s followed by two '\'s and then a '$'. '\' that '$'. _G_bs='\\' _G_bs2='\\\\' _G_bs4='\\\\\\\\' _G_dollar='\$' sed_double_backslash="\ s/$_G_bs4/&\\ /g s/^$_G_bs2$_G_dollar/$_G_bs&/ s/\\([^$_G_bs]\\)$_G_bs2$_G_dollar/\\1$_G_bs2$_G_bs$_G_dollar/g s/\n//g" ## ----------------- ## ## Global variables. ## ## ----------------- ## # Except for the global variables explicitly listed below, the following # functions in the '^func_' namespace, and the '^require_' namespace # variables initialised in the 'Resource management' section, sourcing # this file will not pollute your global namespace with anything # else. There's no portable way to scope variables in Bourne shell # though, so actually running these functions will sometimes place # results into a variable named after the function, and often use # temporary variables in the '^_G_' namespace. If you are careful to # avoid using those namespaces casually in your sourcing script, things # should continue to work as you expect. And, of course, you can freely # overwrite any of the functions or variables defined here before # calling anything to customize them. EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. # Allow overriding, eg assuming that you follow the convention of # putting '$debug_cmd' at the start of all your functions, you can get # bash to show function call trace with: # # debug_cmd='eval echo "${FUNCNAME[0]} $*" >&2' bash your-script-name debug_cmd=${debug_cmd-":"} exit_cmd=: # By convention, finish your script with: # # exit $exit_status # # so that you can set exit_status to non-zero if you want to indicate # something went wrong during execution without actually bailing out at # the point of failure. exit_status=$EXIT_SUCCESS # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath=$0 # The name of this program. progname=`$ECHO "$progpath" |$SED "$sed_basename"` # Make sure we have an absolute progpath for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=`$ECHO "$progpath" |$SED "$sed_dirname"` progdir=`cd "$progdir" && pwd` progpath=$progdir/$progname ;; *) _G_IFS=$IFS IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS=$_G_IFS test -x "$progdir/$progname" && break done IFS=$_G_IFS test -n "$progdir" || progdir=`pwd` progpath=$progdir/$progname ;; esac ## ----------------- ## ## Standard options. ## ## ----------------- ## # The following options affect the operation of the functions defined # below, and should be set appropriately depending on run-time para- # meters passed on the command line. opt_dry_run=false opt_quiet=false opt_verbose=false # Categories 'all' and 'none' are always available. Append any others # you will pass as the first argument to func_warning from your own # code. warning_categories= # By default, display warnings according to 'opt_warning_types'. Set # 'warning_func' to ':' to elide all warnings, or func_fatal_error to # treat the next displayed warning as a fatal error. warning_func=func_warn_and_continue # Set to 'all' to display all warnings, 'none' to suppress all # warnings, or a space delimited list of some subset of # 'warning_categories' to display only the listed warnings. opt_warning_types=all ## -------------------- ## ## Resource management. ## ## -------------------- ## # This section contains definitions for functions that each ensure a # particular resource (a file, or a non-empty configuration variable for # example) is available, and if appropriate to extract default values # from pertinent package files. Call them using their associated # 'require_*' variable to ensure that they are executed, at most, once. # # It's entirely deliberate that calling these functions can set # variables that don't obey the namespace limitations obeyed by the rest # of this file, in order that that they be as useful as possible to # callers. # require_term_colors # ------------------- # Allow display of bold text on terminals that support it. require_term_colors=func_require_term_colors func_require_term_colors () { $debug_cmd test -t 1 && { # COLORTERM and USE_ANSI_COLORS environment variables take # precedence, because most terminfo databases neglect to describe # whether color sequences are supported. test -n "${COLORTERM+set}" && : ${USE_ANSI_COLORS="1"} if test 1 = "$USE_ANSI_COLORS"; then # Standard ANSI escape sequences tc_reset='' tc_bold=''; tc_standout='' tc_red=''; tc_green='' tc_blue=''; tc_cyan='' else # Otherwise trust the terminfo database after all. test -n "`tput sgr0 2>/dev/null`" && { tc_reset=`tput sgr0` test -n "`tput bold 2>/dev/null`" && tc_bold=`tput bold` tc_standout=$tc_bold test -n "`tput smso 2>/dev/null`" && tc_standout=`tput smso` test -n "`tput setaf 1 2>/dev/null`" && tc_red=`tput setaf 1` test -n "`tput setaf 2 2>/dev/null`" && tc_green=`tput setaf 2` test -n "`tput setaf 4 2>/dev/null`" && tc_blue=`tput setaf 4` test -n "`tput setaf 5 2>/dev/null`" && tc_cyan=`tput setaf 5` } fi } require_term_colors=: } ## ----------------- ## ## Function library. ## ## ----------------- ## # This section contains a variety of useful functions to call in your # scripts. Take note of the portable wrappers for features provided by # some modern shells, which will fall back to slower equivalents on # less featureful shells. # func_append VAR VALUE # --------------------- # Append VALUE onto the existing contents of VAR. # We should try to minimise forks, especially on Windows where they are # unreasonably slow, so skip the feature probes when bash or zsh are # being used: if test set = "${BASH_VERSION+set}${ZSH_VERSION+set}"; then : ${_G_HAVE_ARITH_OP="yes"} : ${_G_HAVE_XSI_OPS="yes"} # The += operator was introduced in bash 3.1 case $BASH_VERSION in [12].* | 3.0 | 3.0*) ;; *) : ${_G_HAVE_PLUSEQ_OP="yes"} ;; esac fi # _G_HAVE_PLUSEQ_OP # Can be empty, in which case the shell is probed, "yes" if += is # useable or anything else if it does not work. test -z "$_G_HAVE_PLUSEQ_OP" \ && (eval 'x=a; x+=" b"; test "a b" = "$x"') 2>/dev/null \ && _G_HAVE_PLUSEQ_OP=yes if test yes = "$_G_HAVE_PLUSEQ_OP" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_append () { $debug_cmd eval "$1+=\$2" }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_append () { $debug_cmd eval "$1=\$$1\$2" } fi # func_append_quoted VAR VALUE # ---------------------------- # Quote VALUE and append to the end of shell variable VAR, separated # by a space. if test yes = "$_G_HAVE_PLUSEQ_OP"; then eval 'func_append_quoted () { $debug_cmd func_quote_for_eval "$2" eval "$1+=\\ \$func_quote_for_eval_result" }' else func_append_quoted () { $debug_cmd func_quote_for_eval "$2" eval "$1=\$$1\\ \$func_quote_for_eval_result" } fi # func_append_uniq VAR VALUE # -------------------------- # Append unique VALUE onto the existing contents of VAR, assuming # entries are delimited by the first character of VALUE. For example: # # func_append_uniq options " --another-option option-argument" # # will only append to $options if " --another-option option-argument " # is not already present somewhere in $options already (note spaces at # each end implied by leading space in second argument). func_append_uniq () { $debug_cmd eval _G_current_value='`$ECHO $'$1'`' _G_delim=`expr "$2" : '\(.\)'` case $_G_delim$_G_current_value$_G_delim in *"$2$_G_delim"*) ;; *) func_append "$@" ;; esac } # func_arith TERM... # ------------------ # Set func_arith_result to the result of evaluating TERMs. test -z "$_G_HAVE_ARITH_OP" \ && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \ && _G_HAVE_ARITH_OP=yes if test yes = "$_G_HAVE_ARITH_OP"; then eval 'func_arith () { $debug_cmd func_arith_result=$(( $* )) }' else func_arith () { $debug_cmd func_arith_result=`expr "$@"` } fi # func_basename FILE # ------------------ # Set func_basename_result to FILE with everything up to and including # the last / stripped. if test yes = "$_G_HAVE_XSI_OPS"; then # If this shell supports suffix pattern removal, then use it to avoid # forking. Hide the definitions single quotes in case the shell chokes # on unsupported syntax... _b='func_basename_result=${1##*/}' _d='case $1 in */*) func_dirname_result=${1%/*}$2 ;; * ) func_dirname_result=$3 ;; esac' else # ...otherwise fall back to using sed. _b='func_basename_result=`$ECHO "$1" |$SED "$sed_basename"`' _d='func_dirname_result=`$ECHO "$1" |$SED "$sed_dirname"` if test "X$func_dirname_result" = "X$1"; then func_dirname_result=$3 else func_append func_dirname_result "$2" fi' fi eval 'func_basename () { $debug_cmd '"$_b"' }' # func_dirname FILE APPEND NONDIR_REPLACEMENT # ------------------------------------------- # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. eval 'func_dirname () { $debug_cmd '"$_d"' }' # func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT # -------------------------------------------------------- # Perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # For efficiency, we do not delegate to the functions above but instead # duplicate the functionality here. eval 'func_dirname_and_basename () { $debug_cmd '"$_b"' '"$_d"' }' # func_echo ARG... # ---------------- # Echo program name prefixed message. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname: $_G_line" done IFS=$func_echo_IFS } # func_echo_all ARG... # -------------------- # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_echo_infix_1 INFIX ARG... # ------------------------------ # Echo program name, followed by INFIX on the first line, with any # additional lines not showing INFIX. func_echo_infix_1 () { $debug_cmd $require_term_colors _G_infix=$1; shift _G_indent=$_G_infix _G_prefix="$progname: $_G_infix: " _G_message=$* # Strip color escape sequences before counting printable length for _G_tc in "$tc_reset" "$tc_bold" "$tc_standout" "$tc_red" "$tc_green" "$tc_blue" "$tc_cyan" do test -n "$_G_tc" && { _G_esc_tc=`$ECHO "$_G_tc" | $SED "$sed_make_literal_regex"` _G_indent=`$ECHO "$_G_indent" | $SED "s|$_G_esc_tc||g"` } done _G_indent="$progname: "`echo "$_G_indent" | $SED 's|.| |g'`" " ## exclude from sc_prohibit_nested_quotes func_echo_infix_1_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_infix_1_IFS $ECHO "$_G_prefix$tc_bold$_G_line$tc_reset" >&2 _G_prefix=$_G_indent done IFS=$func_echo_infix_1_IFS } # func_error ARG... # ----------------- # Echo program name prefixed message to standard error. func_error () { $debug_cmd $require_term_colors func_echo_infix_1 " $tc_standout${tc_red}error$tc_reset" "$*" >&2 } # func_fatal_error ARG... # ----------------------- # Echo program name prefixed message to standard error, and exit. func_fatal_error () { $debug_cmd func_error "$*" exit $EXIT_FAILURE } # func_grep EXPRESSION FILENAME # ----------------------------- # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $debug_cmd $GREP "$1" "$2" >/dev/null 2>&1 } # func_len STRING # --------------- # Set func_len_result to the length of STRING. STRING may not # start with a hyphen. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_len () { $debug_cmd func_len_result=${#1} }' else func_len () { $debug_cmd func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` } fi # func_mkdir_p DIRECTORY-PATH # --------------------------- # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { $debug_cmd _G_directory_path=$1 _G_dir_list= if test -n "$_G_directory_path" && test : != "$opt_dry_run"; then # Protect directory names starting with '-' case $_G_directory_path in -*) _G_directory_path=./$_G_directory_path ;; esac # While some portion of DIR does not yet exist... while test ! -d "$_G_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. _G_dir_list=$_G_directory_path:$_G_dir_list # If the last portion added has no slash in it, the list is done case $_G_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop _G_directory_path=`$ECHO "$_G_directory_path" | $SED -e "$sed_dirname"` done _G_dir_list=`$ECHO "$_G_dir_list" | $SED 's|:*$||'` func_mkdir_p_IFS=$IFS; IFS=: for _G_dir in $_G_dir_list; do IFS=$func_mkdir_p_IFS # mkdir can fail with a 'File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$_G_dir" 2>/dev/null || : done IFS=$func_mkdir_p_IFS # Bail out if we (or some other process) failed to create a directory. test -d "$_G_directory_path" || \ func_fatal_error "Failed to create '$1'" fi } # func_mktempdir [BASENAME] # ------------------------- # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, BASENAME is the basename for that directory. func_mktempdir () { $debug_cmd _G_template=${TMPDIR-/tmp}/${1-$progname} if test : = "$opt_dry_run"; then # Return a directory name, but don't create it in dry-run mode _G_tmpdir=$_G_template-$$ else # If mktemp works, use that first and foremost _G_tmpdir=`mktemp -d "$_G_template-XXXXXXXX" 2>/dev/null` if test ! -d "$_G_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race _G_tmpdir=$_G_template-${RANDOM-0}$$ func_mktempdir_umask=`umask` umask 0077 $MKDIR "$_G_tmpdir" umask $func_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$_G_tmpdir" || \ func_fatal_error "cannot create temporary directory '$_G_tmpdir'" fi $ECHO "$_G_tmpdir" } # func_normal_abspath PATH # ------------------------ # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. func_normal_abspath () { $debug_cmd # These SED scripts presuppose an absolute path with a trailing slash. _G_pathcar='s|^/\([^/]*\).*$|\1|' _G_pathcdr='s|^/[^/]*||' _G_removedotparts=':dotsl s|/\./|/|g t dotsl s|/\.$|/|' _G_collapseslashes='s|/\{1,\}|/|g' _G_finalslash='s|/*$|/|' # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_removedotparts" -e "$_G_collapseslashes" -e "$_G_finalslash"` while :; do # Processed it all yet? if test / = "$func_normal_abspath_tpath"; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result"; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_append func_normal_abspath_result "/$func_normal_abspath_tcomponent" ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_notquiet ARG... # -------------------- # Echo program name prefixed message only when not in quiet mode. func_notquiet () { $debug_cmd $opt_quiet || func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_relative_path SRCDIR DSTDIR # -------------------------------- # Set func_relative_path_result to the relative path from SRCDIR to DSTDIR. func_relative_path () { $debug_cmd func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=$func_dirname_result if test -z "$func_relative_path_tlibdir"; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test -n "$func_stripname_result"; then func_append func_relative_path_result "/$func_stripname_result" fi # Normalisation. If bindir is libdir, return '.' else relative path. if test -n "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result" func_relative_path_result=$func_stripname_result fi test -n "$func_relative_path_result" || func_relative_path_result=. : } # func_quote_for_eval ARG... # -------------------------- # Aesthetically quote ARGs to be evaled later. # This function returns two values: # i) func_quote_for_eval_result # double-quoted, suitable for a subsequent eval # ii) func_quote_for_eval_unquoted_result # has all characters that are still active within double # quotes backslashified. func_quote_for_eval () { $debug_cmd func_quote_for_eval_unquoted_result= func_quote_for_eval_result= while test 0 -lt $#; do case $1 in *[\\\`\"\$]*) _G_unquoted_arg=`printf '%s\n' "$1" |$SED "$sed_quote_subst"` ;; *) _G_unquoted_arg=$1 ;; esac if test -n "$func_quote_for_eval_unquoted_result"; then func_append func_quote_for_eval_unquoted_result " $_G_unquoted_arg" else func_append func_quote_for_eval_unquoted_result "$_G_unquoted_arg" fi case $_G_unquoted_arg in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and variable expansion # for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") _G_quoted_arg=\"$_G_unquoted_arg\" ;; *) _G_quoted_arg=$_G_unquoted_arg ;; esac if test -n "$func_quote_for_eval_result"; then func_append func_quote_for_eval_result " $_G_quoted_arg" else func_append func_quote_for_eval_result "$_G_quoted_arg" fi shift done } # func_quote_for_expand ARG # ------------------------- # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { $debug_cmd case $1 in *[\\\`\"]*) _G_arg=`$ECHO "$1" | $SED \ -e "$sed_double_quote_subst" -e "$sed_double_backslash"` ;; *) _G_arg=$1 ;; esac case $_G_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") _G_arg=\"$_G_arg\" ;; esac func_quote_for_expand_result=$_G_arg } # func_stripname PREFIX SUFFIX NAME # --------------------------------- # strip PREFIX and SUFFIX from NAME, and store in func_stripname_result. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_stripname () { $debug_cmd # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary variable first. func_stripname_result=$3 func_stripname_result=${func_stripname_result#"$1"} func_stripname_result=${func_stripname_result%"$2"} }' else func_stripname () { $debug_cmd case $2 in .*) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%\\\\$2\$%%"`;; *) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%$2\$%%"`;; esac } fi # func_show_eval CMD [FAIL_EXP] # ----------------------------- # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} func_quote_for_expand "$_G_cmd" eval "func_notquiet $func_quote_for_expand_result" $opt_dry_run || { eval "$_G_cmd" _G_status=$? if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_show_eval_locale CMD [FAIL_EXP] # ------------------------------------ # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} $opt_quiet || { func_quote_for_expand "$_G_cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || { eval "$_G_user_locale $_G_cmd" _G_status=$? eval "$_G_safe_locale" if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_tr_sh # ---------- # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { $debug_cmd case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED -e 's/^\([0-9]\)/_\1/' -e 's/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_verbose ARG... # ------------------- # Echo program name prefixed message in verbose mode only. func_verbose () { $debug_cmd $opt_verbose && func_echo "$*" : } # func_warn_and_continue ARG... # ----------------------------- # Echo program name prefixed warning message to standard error. func_warn_and_continue () { $debug_cmd $require_term_colors func_echo_infix_1 "${tc_red}warning$tc_reset" "$*" >&2 } # func_warning CATEGORY ARG... # ---------------------------- # Echo program name prefixed warning message to standard error. Warning # messages can be filtered according to CATEGORY, where this function # elides messages where CATEGORY is not listed in the global variable # 'opt_warning_types'. func_warning () { $debug_cmd # CATEGORY must be in the warning_categories list! case " $warning_categories " in *" $1 "*) ;; *) func_internal_error "invalid warning category '$1'" ;; esac _G_category=$1 shift case " $opt_warning_types " in *" $_G_category "*) $warning_func ${1+"$@"} ;; esac } # func_sort_ver VER1 VER2 # ----------------------- # 'sort -V' is not generally available. # Note this deviates from the version comparison in automake # in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a # but this should suffice as we won't be specifying old # version formats or redundant trailing .0 in bootstrap.conf. # If we did want full compatibility then we should probably # use m4_version_compare from autoconf. func_sort_ver () { $debug_cmd printf '%s\n%s\n' "$1" "$2" \ | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n } # func_lt_ver PREV CURR # --------------------- # Return true if PREV and CURR are in the correct order according to # func_sort_ver, otherwise false. Use it like this: # # func_lt_ver "$prev_ver" "$proposed_ver" || func_fatal_error "..." func_lt_ver () { $debug_cmd test "x$1" = x`func_sort_ver "$1" "$2" | $SED 1q` } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: #! /bin/sh # Set a version string for this script. scriptversion=2014-01-07.03; # UTC # A portable, pluggable option parser for Bourne shell. # Written by Gary V. Vaughan, 2010 # Copyright (C) 2010-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please report bugs or propose patches to gary@gnu.org. ## ------ ## ## Usage. ## ## ------ ## # This file is a library for parsing options in your shell scripts along # with assorted other useful supporting features that you can make use # of too. # # For the simplest scripts you might need only: # # #!/bin/sh # . relative/path/to/funclib.sh # . relative/path/to/options-parser # scriptversion=1.0 # func_options ${1+"$@"} # eval set dummy "$func_options_result"; shift # ...rest of your script... # # In order for the '--version' option to work, you will need to have a # suitably formatted comment like the one at the top of this file # starting with '# Written by ' and ending with '# warranty; '. # # For '-h' and '--help' to work, you will also need a one line # description of your script's purpose in a comment directly above the # '# Written by ' line, like the one at the top of this file. # # The default options also support '--debug', which will turn on shell # execution tracing (see the comment above debug_cmd below for another # use), and '--verbose' and the func_verbose function to allow your script # to display verbose messages only when your user has specified # '--verbose'. # # After sourcing this file, you can plug processing for additional # options by amending the variables from the 'Configuration' section # below, and following the instructions in the 'Option parsing' # section further down. ## -------------- ## ## Configuration. ## ## -------------- ## # You should override these variables in your script after sourcing this # file so that they reflect the customisations you have added to the # option parser. # The usage line for option parsing errors and the start of '-h' and # '--help' output messages. You can embed shell variables for delayed # expansion at the time the message is displayed, but you will need to # quote other shell meta-characters carefully to prevent them being # expanded when the contents are evaled. usage='$progpath [OPTION]...' # Short help message in response to '-h' and '--help'. Add to this or # override it after sourcing this library to reflect the full set of # options your script accepts. usage_message="\ --debug enable verbose shell tracing -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -v, --verbose verbosely report processing --version print version information and exit -h, --help print short or long help message and exit " # Additional text appended to 'usage_message' in response to '--help'. long_help_message=" Warning categories include: 'all' show all warnings 'none' turn off all the warnings 'error' warnings are treated as fatal errors" # Help message printed before fatal option parsing errors. fatal_help="Try '\$progname --help' for more information." ## ------------------------- ## ## Hook function management. ## ## ------------------------- ## # This section contains functions for adding, removing, and running hooks # to the main code. A hook is just a named list of of function, that can # be run in order later on. # func_hookable FUNC_NAME # ----------------------- # Declare that FUNC_NAME will run hooks added with # 'func_add_hook FUNC_NAME ...'. func_hookable () { $debug_cmd func_append hookable_fns " $1" } # func_add_hook FUNC_NAME HOOK_FUNC # --------------------------------- # Request that FUNC_NAME call HOOK_FUNC before it returns. FUNC_NAME must # first have been declared "hookable" by a call to 'func_hookable'. func_add_hook () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not accept hook functions." ;; esac eval func_append ${1}_hooks '" $2"' } # func_remove_hook FUNC_NAME HOOK_FUNC # ------------------------------------ # Remove HOOK_FUNC from the list of functions called by FUNC_NAME. func_remove_hook () { $debug_cmd eval ${1}_hooks='`$ECHO "\$'$1'_hooks" |$SED "s| '$2'||"`' } # func_run_hooks FUNC_NAME [ARG]... # --------------------------------- # Run all hook functions registered to FUNC_NAME. # It is assumed that the list of hook functions contains nothing more # than a whitespace-delimited list of legal shell function names, and # no effort is wasted trying to catch shell meta-characters or preserve # whitespace. func_run_hooks () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not support hook funcions.n" ;; esac eval _G_hook_fns=\$$1_hooks; shift for _G_hook in $_G_hook_fns; do eval $_G_hook '"$@"' # store returned options list back into positional # parameters for next 'cmd' execution. eval _G_hook_result=\$${_G_hook}_result eval set dummy "$_G_hook_result"; shift done func_quote_for_eval ${1+"$@"} func_run_hooks_result=$func_quote_for_eval_result } ## --------------- ## ## Option parsing. ## ## --------------- ## # In order to add your own option parsing hooks, you must accept the # full positional parameter list in your hook function, remove any # options that you action, and then pass back the remaining unprocessed # options in '<hooked_function_name>_result', escaped suitably for # 'eval'. Like this: # # my_options_prep () # { # $debug_cmd # # # Extend the existing usage message. # usage_message=$usage_message' # -s, --silent don'\''t print informational messages # ' # # func_quote_for_eval ${1+"$@"} # my_options_prep_result=$func_quote_for_eval_result # } # func_add_hook func_options_prep my_options_prep # # # my_silent_option () # { # $debug_cmd # # # Note that for efficiency, we parse as many options as we can # # recognise in a loop before passing the remainder back to the # # caller on the first unrecognised argument we encounter. # while test $# -gt 0; do # opt=$1; shift # case $opt in # --silent|-s) opt_silent=: ;; # # Separate non-argument short options: # -s*) func_split_short_opt "$_G_opt" # set dummy "$func_split_short_opt_name" \ # "-$func_split_short_opt_arg" ${1+"$@"} # shift # ;; # *) set dummy "$_G_opt" "$*"; shift; break ;; # esac # done # # func_quote_for_eval ${1+"$@"} # my_silent_option_result=$func_quote_for_eval_result # } # func_add_hook func_parse_options my_silent_option # # # my_option_validation () # { # $debug_cmd # # $opt_silent && $opt_verbose && func_fatal_help "\ # '--silent' and '--verbose' options are mutually exclusive." # # func_quote_for_eval ${1+"$@"} # my_option_validation_result=$func_quote_for_eval_result # } # func_add_hook func_validate_options my_option_validation # # You'll alse need to manually amend $usage_message to reflect the extra # options you parse. It's preferable to append if you can, so that # multiple option parsing hooks can be added safely. # func_options [ARG]... # --------------------- # All the functions called inside func_options are hookable. See the # individual implementations for details. func_hookable func_options func_options () { $debug_cmd func_options_prep ${1+"$@"} eval func_parse_options \ ${func_options_prep_result+"$func_options_prep_result"} eval func_validate_options \ ${func_parse_options_result+"$func_parse_options_result"} eval func_run_hooks func_options \ ${func_validate_options_result+"$func_validate_options_result"} # save modified positional parameters for caller func_options_result=$func_run_hooks_result } # func_options_prep [ARG]... # -------------------------- # All initialisations required before starting the option parse loop. # Note that when calling hook functions, we pass through the list of # positional parameters. If a hook function modifies that list, and # needs to propogate that back to rest of this script, then the complete # modified list must be put in 'func_run_hooks_result' before # returning. func_hookable func_options_prep func_options_prep () { $debug_cmd # Option defaults: opt_verbose=false opt_warning_types= func_run_hooks func_options_prep ${1+"$@"} # save modified positional parameters for caller func_options_prep_result=$func_run_hooks_result } # func_parse_options [ARG]... # --------------------------- # The main option parsing loop. func_hookable func_parse_options func_parse_options () { $debug_cmd func_parse_options_result= # this just eases exit handling while test $# -gt 0; do # Defer to hook functions for initial option parsing, so they # get priority in the event of reusing an option name. func_run_hooks func_parse_options ${1+"$@"} # Adjust func_parse_options positional parameters to match eval set dummy "$func_run_hooks_result"; shift # Break out of the loop if we already parsed every option. test $# -gt 0 || break _G_opt=$1 shift case $_G_opt in --debug|-x) debug_cmd='set -x' func_echo "enabling shell trace mode" $debug_cmd ;; --no-warnings|--no-warning|--no-warn) set dummy --warnings none ${1+"$@"} shift ;; --warnings|--warning|-W) test $# = 0 && func_missing_arg $_G_opt && break case " $warning_categories $1" in *" $1 "*) # trailing space prevents matching last $1 above func_append_uniq opt_warning_types " $1" ;; *all) opt_warning_types=$warning_categories ;; *none) opt_warning_types=none warning_func=: ;; *error) opt_warning_types=$warning_categories warning_func=func_fatal_error ;; *) func_fatal_error \ "unsupported warning category: '$1'" ;; esac shift ;; --verbose|-v) opt_verbose=: ;; --version) func_version ;; -\?|-h) func_usage ;; --help) func_help ;; # Separate optargs to long options (plugins may need this): --*=*) func_split_equals "$_G_opt" set dummy "$func_split_equals_lhs" \ "$func_split_equals_rhs" ${1+"$@"} shift ;; # Separate optargs to short options: -W*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "$func_split_short_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-v*|-x*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) break ;; -*) func_fatal_help "unrecognised option: '$_G_opt'" ;; *) set dummy "$_G_opt" ${1+"$@"}; shift; break ;; esac done # save modified positional parameters for caller func_quote_for_eval ${1+"$@"} func_parse_options_result=$func_quote_for_eval_result } # func_validate_options [ARG]... # ------------------------------ # Perform any sanity checks on option settings and/or unconsumed # arguments. func_hookable func_validate_options func_validate_options () { $debug_cmd # Display all warnings if -W was not given. test -n "$opt_warning_types" || opt_warning_types=" $warning_categories" func_run_hooks func_validate_options ${1+"$@"} # Bail if the options were screwed! $exit_cmd $EXIT_FAILURE # save modified positional parameters for caller func_validate_options_result=$func_run_hooks_result } ## ----------------- ## ## Helper functions. ## ## ----------------- ## # This section contains the helper functions used by the rest of the # hookable option parser framework in ascii-betical order. # func_fatal_help ARG... # ---------------------- # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { $debug_cmd eval \$ECHO \""Usage: $usage"\" eval \$ECHO \""$fatal_help"\" func_error ${1+"$@"} exit $EXIT_FAILURE } # func_help # --------- # Echo long help message to standard output and exit. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message" exit 0 } # func_missing_arg ARGNAME # ------------------------ # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $debug_cmd func_error "Missing argument for '$1'." exit_cmd=exit } # func_split_equals STRING # ------------------------ # Set func_split_equals_lhs and func_split_equals_rhs shell variables after # splitting STRING at the '=' sign. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_equals () { $debug_cmd func_split_equals_lhs=${1%%=*} func_split_equals_rhs=${1#*=} test "x$func_split_equals_lhs" = "x$1" \ && func_split_equals_rhs= }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_equals () { $debug_cmd func_split_equals_lhs=`expr "x$1" : 'x\([^=]*\)'` func_split_equals_rhs= test "x$func_split_equals_lhs" = "x$1" \ || func_split_equals_rhs=`expr "x$1" : 'x[^=]*=\(.*\)$'` } fi #func_split_equals # func_split_short_opt SHORTOPT # ----------------------------- # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_short_opt () { $debug_cmd func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"} }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_short_opt () { $debug_cmd func_split_short_opt_name=`expr "x$1" : 'x-\(.\)'` func_split_short_opt_arg=`expr "x$1" : 'x-.\(.*\)$'` } fi #func_split_short_opt # func_usage # ---------- # Echo short help message to standard output and exit. func_usage () { $debug_cmd func_usage_message $ECHO "Run '$progname --help |${PAGER-more}' for full usage" exit 0 } # func_usage_message # ------------------ # Echo short help message to standard output. func_usage_message () { $debug_cmd eval \$ECHO \""Usage: $usage"\" echo $SED -n 's|^# || /^Written by/{ x;p;x } h /^Written by/q' < "$progpath" echo eval \$ECHO \""$usage_message"\" } # func_version # ------------ # Echo version message to standard output and exit. func_version () { $debug_cmd printf '%s\n' "$progname $scriptversion" $SED -n ' /(C)/!b go :more /\./!{ N s|\n# | | b more } :go /^# Written by /,/# warranty; / { s|^# || s|^# *$|| s|\((C)\)[ 0-9,-]*[ ,-]\([1-9][0-9]* \)|\1 \2| p } /^# Written by / { s|^# || p } /^warranty; /q' < "$progpath" exit $? } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: # Set a version string. scriptversion='(GNU libtool) 2.4.6' # func_echo ARG... # ---------------- # Libtool also displays the current mode in messages, so override # funclib.sh func_echo with this custom definition. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname${opt_mode+: $opt_mode}: $_G_line" done IFS=$func_echo_IFS } # func_warning ARG... # ------------------- # Libtool warnings are not categorized, so override funclib.sh # func_warning with this simpler definition. func_warning () { $debug_cmd $warning_func ${1+"$@"} } ## ---------------- ## ## Options parsing. ## ## ---------------- ## # Hook in the functions to make sure our own options are parsed during # the option parsing loop. usage='$progpath [OPTION]... [MODE-ARG]...' # Short help message in response to '-h'. usage_message="Options: --config show all configuration variables --debug enable verbose shell tracing -n, --dry-run display commands without modifying any files --features display basic configuration information and exit --mode=MODE use operation mode MODE --no-warnings equivalent to '-Wnone' --preserve-dup-deps don't remove duplicate dependency libraries --quiet, --silent don't print informational messages --tag=TAG use configuration variables from tag TAG -v, --verbose print more informational messages than default --version print version information -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -h, --help, --help-all print short, long, or detailed help message " # Additional text appended to 'usage_message' in response to '--help'. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message MODE must be one of the following: clean remove files from the build directory compile compile a source file into a libtool object execute automatically set library path, then run a program finish complete the installation of libtool libraries install install libraries or executables link create a library or an executable uninstall remove libraries from an installed directory MODE-ARGS vary depending on the MODE. When passed as first option, '--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that. Try '$progname --help --mode=MODE' for a more detailed description of MODE. When reporting a bug, please describe a test case to reproduce it and include the following information: host-triplet: $host shell: $SHELL compiler: $LTCC compiler flags: $LTCFLAGS linker: $LD (gnu? $with_gnu_ld) version: $progname (GNU libtool) 2.4.6 automake: `($AUTOMAKE --version) 2>/dev/null |$SED 1q` autoconf: `($AUTOCONF --version) 2>/dev/null |$SED 1q` Report bugs to <bug-libtool@gnu.org>. GNU libtool home page: <http://www.gnu.org/software/libtool/>. General help using GNU software: <http://www.gnu.org/gethelp/>." exit 0 } # func_lo2o OBJECT-NAME # --------------------- # Transform OBJECT-NAME from a '.lo' suffix to the platform specific # object suffix. lo2o=s/\\.lo\$/.$objext/ o2lo=s/\\.$objext\$/.lo/ if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_lo2o () { case $1 in *.lo) func_lo2o_result=${1%.lo}.$objext ;; * ) func_lo2o_result=$1 ;; esac }' # func_xform LIBOBJ-OR-SOURCE # --------------------------- # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise) # suffix to a '.lo' libtool-object suffix. eval 'func_xform () { func_xform_result=${1%.*}.lo }' else # ...otherwise fall back to using sed. func_lo2o () { func_lo2o_result=`$ECHO "$1" | $SED "$lo2o"` } func_xform () { func_xform_result=`$ECHO "$1" | $SED 's|\.[^.]*$|.lo|'` } fi # func_fatal_configuration ARG... # ------------------------------- # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func__fatal_error ${1+"$@"} \ "See the $PACKAGE documentation for more information." \ "Fatal configuration error." } # func_config # ----------- # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # ------------- # Display the features supported by this script. func_features () { echo "host: $host" if test yes = "$build_libtool_libs"; then echo "enable shared libraries" else echo "disable shared libraries" fi if test yes = "$build_old_libs"; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag TAGNAME # ----------------------- # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname=$1 re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf=/$re_begincf/,/$re_endcf/p # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # ------------------------ # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # libtool_options_prep [ARG]... # ----------------------------- # Preparation for options parsed by libtool. libtool_options_prep () { $debug_mode # Option defaults: opt_config=false opt_dlopen= opt_dry_run=false opt_help=false opt_mode= opt_preserve_dup_deps=false opt_quiet=false nonopt= preserve_args= # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Pass back the list of options. func_quote_for_eval ${1+"$@"} libtool_options_prep_result=$func_quote_for_eval_result } func_add_hook func_options_prep libtool_options_prep # libtool_parse_options [ARG]... # --------------------------------- # Provide handling for libtool specific options. libtool_parse_options () { $debug_cmd # Perform our own loop to consume as many options as possible in # each iteration. while test $# -gt 0; do _G_opt=$1 shift case $_G_opt in --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) func_config ;; --dlopen|-dlopen) opt_dlopen="${opt_dlopen+$opt_dlopen }$1" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) func_features ;; --finish) set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $_G_opt && break opt_mode=$1 case $1 in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $_G_opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_quiet=false func_append preserve_args " $_G_opt" ;; --no-warnings|--no-warning|--no-warn) opt_warning=false func_append preserve_args " $_G_opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $_G_opt" ;; --silent|--quiet) opt_quiet=: opt_verbose=false func_append preserve_args " $_G_opt" ;; --tag) test $# = 0 && func_missing_arg $_G_opt && break opt_tag=$1 func_append preserve_args " $_G_opt $1" func_enable_tag "$1" shift ;; --verbose|-v) opt_quiet=false opt_verbose=: func_append preserve_args " $_G_opt" ;; # An option not handled by this hook function: *) set dummy "$_G_opt" ${1+"$@"}; shift; break ;; esac done # save modified positional parameters for caller func_quote_for_eval ${1+"$@"} libtool_parse_options_result=$func_quote_for_eval_result } func_add_hook func_parse_options libtool_parse_options # libtool_validate_options [ARG]... # --------------------------------- # Perform any sanity checks on option settings and/or unconsumed # arguments. libtool_validate_options () { # save first non-option argument if test 0 -lt $#; then nonopt=$1 shift fi # preserve --debug test : = "$debug_cmd" || func_append preserve_args " --debug" case $host in # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452 # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788 *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match test yes != "$build_libtool_libs" \ && test yes != "$build_old_libs" \ && func_fatal_configuration "not configured to build any kind of library" # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test execute != "$opt_mode"; then func_error "unrecognized option '-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help=$help help="Try '$progname --help --mode=$opt_mode' for more information." } # Pass back the unparsed argument list func_quote_for_eval ${1+"$@"} libtool_validate_options_result=$func_quote_for_eval_result } func_add_hook func_validate_options libtool_validate_options # Process options as early as possible so that --help and --version # can return quickly. func_options ${1+"$@"} eval set dummy "$func_options_result"; shift ## ----------- ## ## Main. ## ## ----------- ## magic='%%%MAGIC variable%%%' magic_exe='%%%MAGIC EXE variable%%%' # Global variables. extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # func_generated_by_libtool # True iff stdin has been generated by Libtool. This function is only # a basic sanity check; it will hardly flush out determined imposters. func_generated_by_libtool_p () { $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null | func_generated_by_libtool_p } # func_lalib_unsafe_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if 'file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case $lalib_p_line in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test yes = "$lalib_p" } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { test -f "$1" && $lt_truncate_bin < "$1" 2>/dev/null | func_generated_by_libtool_p } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $debug_cmd save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # 'FILE.' does not work on cygwin managed mounts. func_source () { $debug_cmd case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case $lt_sysroot:$1 in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result='='$func_stripname_result ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $debug_cmd if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with '--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=$1 if test yes = "$build_libtool_libs"; then write_lobj=\'$2\' else write_lobj=none fi if test yes = "$build_old_libs"; then write_oldobj=\'$3\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T <<EOF # $write_libobj - a libtool object file # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # Name of the PIC object. pic_object=$write_lobj # Name of the non-PIC object non_pic_object=$write_oldobj EOF $MV "${write_libobj}T" "$write_libobj" } } ################################################## # FILE NAME AND PATH CONVERSION HELPER FUNCTIONS # ################################################## # func_convert_core_file_wine_to_w32 ARG # Helper function used by file name conversion functions when $build is *nix, # and $host is mingw, cygwin, or some other w32 environment. Relies on a # correctly configured wine environment available, with the winepath program # in $build's $PATH. # # ARG is the $build file name to be converted to w32 format. # Result is available in $func_convert_core_file_wine_to_w32_result, and will # be empty on error (or when ARG is empty) func_convert_core_file_wine_to_w32 () { $debug_cmd func_convert_core_file_wine_to_w32_result=$1 if test -n "$1"; then # Unfortunately, winepath does not exit with a non-zero error code, so we # are forced to check the contents of stdout. On the other hand, if the # command is not found, the shell will set an exit code of 127 and print # *an error message* to stdout. So we must check for both error code of # zero AND non-empty stdout, which explains the odd construction: func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null` if test "$?" -eq 0 && test -n "$func_convert_core_file_wine_to_w32_tmp"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $debug_cmd # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result= if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result"; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $debug_cmd if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $debug_cmd # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $debug_cmd if test -z "$2" && test -n "$1"; then func_error "Could not determine host file name corresponding to" func_error " '$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result=$1 fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $debug_cmd if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " '$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result=$3 fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $debug_cmd case $4 in $1 ) func_to_host_path_result=$3$func_to_host_path_result ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via '$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $debug_cmd $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $debug_cmd case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result=$1 } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result=$func_convert_core_msys_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result=$func_convert_core_file_wine_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via '$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $debug_cmd if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd=func_convert_path_$func_stripname_result fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $debug_cmd func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result=$1 } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_msys_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_path_wine_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_dll_def_p FILE # True iff FILE is a Windows DLL '.def' file. # Keep in sync with _LT_DLL_DEF_P in libtool.m4 func_dll_def_p () { $debug_cmd func_dll_def_p_tmp=`$SED -n \ -e 's/^[ ]*//' \ -e '/^\(;.*\)*$/d' \ -e 's/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p' \ -e q \ "$1"` test DEF = "$func_dll_def_p_tmp" } # func_mode_compile arg... func_mode_compile () { $debug_cmd # Get the compilation command and the source file. base_compile= srcfile=$nonopt # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg=$arg arg_mode=normal ;; target ) libobj=$arg arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify '-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs=$IFS; IFS=, for arg in $args; do IFS=$save_ifs func_append_quoted lastarg "$arg" done IFS=$save_ifs func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg=$srcfile srcfile=$arg ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with '-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj=$func_basename_result } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from '$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test yes = "$build_libtool_libs" \ || func_fatal_configuration "cannot build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name '$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname=$func_basename_result xdir=$func_dirname_result lobj=$xdir$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test yes = "$build_old_libs"; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test no = "$pic_mode" && test pass_all != "$deplibs_check_method"; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test no = "$compiler_c_o"; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.$objext lockfile=$output_obj.lock else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test yes = "$need_locks"; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test warn = "$need_locks"; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test yes = "$build_libtool_libs"; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test no != "$pic_mode"; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test yes = "$suppress_opt"; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test yes = "$build_old_libs"; then if test yes != "$pic_mode"; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test yes = "$compiler_c_o"; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test no != "$need_locks"; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test compile = "$opt_mode" && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a '.o' file suitable for static linking -static only build a '.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a 'standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix '.c' with the library object suffix, '.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to '-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the '--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the 'install' or 'cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE '-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE use a list of object files found in FILE to specify objects -os2dllname NAME force a short DLL name on OS/2 (no effect on other OSes) -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with '-') are ignored. Every other argument is treated as a filename. Files ending in '.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in '.la', then a libtool library is created, only library objects ('.lo' files) may be specified, and '-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created using 'ar' and 'ranlib', or on Windows using 'lib'. If OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode '$opt_mode'" ;; esac echo $ECHO "Try '$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test : = "$opt_help"; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | $SED -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | $SED '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $debug_cmd # The first argument is the command name. cmd=$nonopt test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "'$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "'$file' was not linked with '-export-dynamic'" continue fi func_dirname "$file" "" "." dir=$func_dirname_result if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find '$dlname' in '$dir' or '$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir=$func_dirname_result ;; *) func_warning "'-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir=$absdir # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic=$magic # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file=$progdir/$program elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file=$progdir/$program fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if $opt_dry_run; then # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS else if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd=\$cmd$args fi } test execute = "$opt_mode" && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $debug_cmd libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "'$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument '$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and '=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do $SED -e "$sysroot_cmd s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_quiet && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the '-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the '$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the '$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the '$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to '/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test finish = "$opt_mode" && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $debug_cmd # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$SHELL" = "$nonopt" || test /bin/sh = "$nonopt" || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" func_append install_prog "$func_quote_for_eval_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=false stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=: ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test X-m = "X$prev" && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" func_append install_prog " $func_quote_for_eval_result" if test -n "$arg2"; then func_quote_for_eval "$arg2" fi func_append install_shared_prog " $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the '$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_for_eval "$install_override_mode" func_append install_shared_prog " -m $func_quote_for_eval_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=: if $isdir; then destdir=$dest destname= else func_dirname_and_basename "$dest" "" "." destdir=$func_dirname_result destname=$func_basename_result # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "'$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "'$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir=$func_dirname_result func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install '$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking '$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink '\''$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname=$1 shift srcname=$realname test -n "$relink_command" && srcname=${realname}T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme=$stripme case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme= ;; esac ;; os2*) case $realname in *_dll.a) tstripme= ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try 'ln -sf' first, because the 'ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib=$destdir/$realname func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name=$func_basename_result instname=$dir/${name}i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest=$destfile destfile= ;; *) func_fatal_help "cannot copy a libtool object to '$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test yes = "$build_old_libs"; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext= case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=.exe fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script '$wrapper'" finalize=: for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile=$libdir/`$ECHO "$lib" | $SED 's%^.*/%%g'` if test -n "$libdir" && test ! -f "$libfile"; then func_warning "'$lib' has not been installed in '$libdir'" finalize=false fi done relink_command= func_source "$wrapper" outputname= if test no = "$fast_install" && test -n "$relink_command"; then $opt_dry_run || { if $finalize; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file=$func_basename_result outputname=$tmpdir/$file # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_quiet || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink '$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file=$outputname else func_warning "cannot relink '$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name=$func_basename_result # Set up the ranlib parameters. oldlib=$destdir/$name func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run '$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL "$progpath" $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test install = "$opt_mode" && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $debug_cmd my_outputname=$1 my_originator=$2 my_pic_p=${3-false} my_prefix=`$ECHO "$my_originator" | $SED 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms=${my_outputname}S.c else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist=$output_objdir/$my_outputname.nm func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* External symbol declarations for the compiler. */\ " if test yes = "$dlself"; then func_verbose "generating symbol list for '$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from '$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols=$output_objdir/$outputname.exp $opt_dry_run || { $RM $export_symbols eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "$SED -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from '$dlprefile'" func_basename "$dlprefile" name=$func_basename_result case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename= if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname"; then func_basename "$dlprefile_dlname" dlprefile_dlbasename=$func_basename_result else # no lafile. user explicitly requested -dlpreopen <import library>. $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename"; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 </dev/null >/dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi func_show_eval '$RM "${nlist}I"' if test -n "$global_symbol_to_import"; then eval "$global_symbol_to_import"' < "$nlist"S > "$nlist"I' fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[];\ " if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ static void lt_syminit(void) { LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols; for (; symbol->name; ++symbol) {" $SED 's/.*/ if (STREQ (symbol->name, \"&\")) symbol->address = (void *) \&&;/' < "$nlist"I >> "$output_objdir/$my_dlsyms" echo >> "$output_objdir/$my_dlsyms" "\ } }" fi echo >> "$output_objdir/$my_dlsyms" "\ LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = { {\"$my_originator\", (void *) 0}," if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ {\"@INIT@\", (void *) &lt_syminit}," fi case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) $my_pic_p && pic_flag_for_symtable=" $pic_flag" ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T" "${nlist}I"' # Transform the symbol file into the correct name. symfileobj=$output_objdir/${my_outputname}S.$objext case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for '$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $debug_cmd win32_libid_type=unknown win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then case $nm_interface in "MS dumpbin") if func_cygming_ms_implib_p "$1" || func_cygming_gnu_implib_p "$1" then win32_nmres=import else win32_nmres= fi ;; *) func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s|.*|import| p q } }'` ;; esac case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $debug_cmd sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $debug_cmd match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive that possess that section. Heuristic: eliminate # all those that have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $debug_cmd if func_cygming_gnu_implib_p "$1"; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1"; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result= fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $debug_cmd f_ex_an_ar_dir=$1; shift f_ex_an_ar_oldlib=$1 if test yes = "$lock_old_archive_extraction"; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test yes = "$lock_old_archive_extraction"; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $debug_cmd my_gentop=$1; shift my_oldlibs=${1+"$@"} my_oldobjs= my_xlib= my_xabs= my_xdir= for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs=$my_xlib ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib=$func_basename_result my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir=$my_gentop/$my_xlib_u func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` func_basename "$darwin_archive" darwin_base_archive=$func_basename_result darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches; do func_mkdir_p "unfat-$$/$darwin_base_archive-$darwin_arch" $LIPO -thin $darwin_arch -output "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" "$darwin_archive" cd "unfat-$$/$darwin_base_archive-$darwin_arch" func_extract_an_archive "`pwd`" "$darwin_base_archive" cd "$darwin_curdir" $RM "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$sed_basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result=$my_oldobjs } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory where it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=\"$qECHO\" fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ that is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options that match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"$outputname:$output:\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"$outputname:$output:\$LINENO: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test yes = "$fast_install"; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | $SED 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else \$ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: '\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat <<EOF /* $cwrappersource - temporary wrapper executable for $objdir/$outputname Generated by $PROGRAM (GNU $PACKAGE) $VERSION The $output program cannot be directly executed until all the libtool libraries that it depends on are installed. This wrapper executable should never be moved out of the build directory. If it is, it will not operate correctly. */ EOF cat <<"EOF" #ifdef _MSC_VER # define _CRT_SECURE_NO_DEPRECATE 1 #endif #include <stdio.h> #include <stdlib.h> #ifdef _MSC_VER # include <direct.h> # include <process.h> # include <io.h> #else # include <unistd.h> # include <stdint.h> # ifdef __CYGWIN__ # include <io.h> # endif #endif #include <malloc.h> #include <stdarg.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* declarations of non-ANSI functions */ #if defined __MINGW32__ # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined __CYGWIN__ # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined other_platform || defined ... */ #endif /* portability defines, excluding path handling macros */ #if defined _MSC_VER # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC #elif defined __MINGW32__ # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined __CYGWIN__ # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined other platforms ... */ #endif #if defined PATH_MAX # define LT_PATHMAX PATH_MAX #elif defined MAXPATHLEN # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \ defined __OS2__ # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free (stale); stale = 0; } \ } while (0) #if defined LT_DEBUGWRAPPER static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <<EOF #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5) # define externally_visible volatile #else # define externally_visible __attribute__((externally_visible)) volatile #endif externally_visible const char * MAGIC_EXE = "$magic_exe"; const char * LIB_PATH_VARNAME = "$shlibpath_var"; EOF if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then func_to_host_path "$temp_rpath" cat <<EOF const char * LIB_PATH_VALUE = "$func_to_host_path_result"; EOF else cat <<"EOF" const char * LIB_PATH_VALUE = ""; EOF fi if test -n "$dllsearchpath"; then func_to_host_path "$dllsearchpath:" cat <<EOF const char * EXE_PATH_VARNAME = "PATH"; const char * EXE_PATH_VALUE = "$func_to_host_path_result"; EOF else cat <<"EOF" const char * EXE_PATH_VARNAME = ""; const char * EXE_PATH_VALUE = ""; EOF fi if test yes = "$fast_install"; then cat <<EOF const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */ EOF else cat <<EOF const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */ EOF fi cat <<"EOF" #define LTWRAPPER_OPTION_PREFIX "--lt-" static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX; static const char *dumpscript_opt = LTWRAPPER_OPTION_PREFIX "dump-script"; static const char *debug_opt = LTWRAPPER_OPTION_PREFIX "debug"; int main (int argc, char *argv[]) { char **newargz; int newargc; char *tmp_pathspec; char *actual_cwrapper_path; char *actual_cwrapper_name; char *target_name; char *lt_argv_zero; int rval = 127; int i; program_name = (char *) xstrdup (base_name (argv[0])); newargz = XMALLOC (char *, (size_t) argc + 1); /* very simple arg parsing; don't want to rely on getopt * also, copy all non cwrapper options to newargz, except * argz[0], which is handled differently */ newargc=0; for (i = 1; i < argc; i++) { if (STREQ (argv[i], dumpscript_opt)) { EOF case $host in *mingw* | *cygwin* ) # make stdout use "unix" line endings echo " setmode(1,_O_BINARY);" ;; esac cat <<"EOF" lt_dump_script (stdout); return 0; } if (STREQ (argv[i], debug_opt)) { lt_debug = 1; continue; } if (STREQ (argv[i], ltwrapper_option_prefix)) { /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX namespace, but it is not one of the ones we know about and have already dealt with, above (inluding dump-script), then report an error. Otherwise, targets might begin to believe they are allowed to use options in the LTWRAPPER_OPTION_PREFIX namespace. The first time any user complains about this, we'll need to make LTWRAPPER_OPTION_PREFIX a configure-time option or a configure.ac-settable value. */ lt_fatal (__FILE__, __LINE__, "unrecognized %s option: '%s'", ltwrapper_option_prefix, argv[i]); } /* otherwise ... */ newargz[++newargc] = xstrdup (argv[i]); } newargz[++newargc] = NULL; EOF cat <<EOF /* The GNU banner must be the first non-error debug message */ lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE) $VERSION\n"); EOF cat <<"EOF" lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]); lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program_name); tmp_pathspec = find_executable (argv[0]); if (tmp_pathspec == NULL) lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]); lt_debugprintf (__FILE__, __LINE__, "(main) found exe (before symlink chase) at: %s\n", tmp_pathspec); actual_cwrapper_path = chase_symlinks (tmp_pathspec); lt_debugprintf (__FILE__, __LINE__, "(main) found exe (after symlink chase) at: %s\n", actual_cwrapper_path); XFREE (tmp_pathspec); actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path)); strendzap (actual_cwrapper_path, actual_cwrapper_name); /* wrapper name transforms */ strendzap (actual_cwrapper_name, ".exe"); tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1); XFREE (actual_cwrapper_name); actual_cwrapper_name = tmp_pathspec; tmp_pathspec = 0; /* target_name transforms -- use actual target program name; might have lt- prefix */ target_name = xstrdup (base_name (TARGET_PROGRAM_NAME)); strendzap (target_name, ".exe"); tmp_pathspec = lt_extend_str (target_name, ".exe", 1); XFREE (target_name); target_name = tmp_pathspec; tmp_pathspec = 0; lt_debugprintf (__FILE__, __LINE__, "(main) libtool target name: %s\n", target_name); EOF cat <<EOF newargz[0] = XMALLOC (char, (strlen (actual_cwrapper_path) + strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1)); strcpy (newargz[0], actual_cwrapper_path); strcat (newargz[0], "$objdir"); strcat (newargz[0], "/"); EOF cat <<"EOF" /* stop here, and copy so we don't have to do this twice */ tmp_pathspec = xstrdup (newargz[0]); /* do NOT want the lt- prefix here, so use actual_cwrapper_name */ strcat (newargz[0], actual_cwrapper_name); /* DO want the lt- prefix here if it exists, so use target_name */ lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1); XFREE (tmp_pathspec); tmp_pathspec = NULL; EOF case $host_os in mingw*) cat <<"EOF" { char* p; while ((p = strchr (newargz[0], '\\')) != NULL) { *p = '/'; } while ((p = strchr (lt_argv_zero, '\\')) != NULL) { *p = '/'; } } EOF ;; esac cat <<"EOF" XFREE (target_name); XFREE (actual_cwrapper_path); XFREE (actual_cwrapper_name); lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */ lt_setenv ("DUALCASE", "1"); /* for MSK sh */ /* Update the DLL searchpath. EXE_PATH_VALUE ($dllsearchpath) must be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath) because on Windows, both *_VARNAMEs are PATH but uninstalled libraries must come first. */ lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE); lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE); lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n", nonnull (lt_argv_zero)); for (i = 0; i < newargc; i++) { lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n", i, nonnull (newargz[i])); } EOF case $host_os in mingw*) cat <<"EOF" /* execv doesn't actually work on mingw as expected on unix */ newargz = prepare_spawn (newargz); rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz); if (rval == -1) { /* failed to start process */ lt_debugprintf (__FILE__, __LINE__, "(main) failed to launch target \"%s\": %s\n", lt_argv_zero, nonnull (strerror (errno))); return 127; } return rval; EOF ;; *) cat <<"EOF" execv (lt_argv_zero, newargz); return rval; /* =127, but avoids unused variable warning */ EOF ;; esac cat <<"EOF" } void * xmalloc (size_t num) { void *p = (void *) malloc (num); if (!p) lt_fatal (__FILE__, __LINE__, "memory exhausted"); return p; } char * xstrdup (const char *string) { return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL; } const char * base_name (const char *name) { const char *base; #if defined HAVE_DOS_BASED_FILE_SYSTEM /* Skip over the disk name in MSDOS pathnames. */ if (isalpha ((unsigned char) name[0]) && name[1] == ':') name += 2; #endif for (base = name; *name; name++) if (IS_DIR_SEPARATOR (*name)) base = name + 1; return base; } int check_executable (const char *path) { struct stat st; lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if ((stat (path, &st) >= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; size_t tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined HAVE_DOS_BASED_FILE_SYSTEM if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined HAVE_DOS_BASED_FILE_SYSTEM } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = (size_t) (q - p); p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (STREQ (str, pat)) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else size_t len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { size_t orig_value_len = strlen (orig_value); size_t add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ size_t len = strlen (new_value); while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[--len] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $debug_cmd case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_suncc_cstd_abi # !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!! # Several compiler flags select an ABI that is incompatible with the # Cstd library. Avoid specifying it if any are in CXXFLAGS. func_suncc_cstd_abi () { $debug_cmd case " $compile_command " in *" -compat=g "*|*\ -std=c++[0-9][0-9]\ *|*" -library=stdcxx4 "*|*" -library=stlport4 "*) suncc_use_cstd_abi=no ;; *) suncc_use_cstd_abi=yes ;; esac } # func_mode_link arg... func_mode_link () { $debug_cmd case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # what system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll that has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= os2dllname= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=false prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module=$wl-single_module func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test yes != "$build_libtool_libs" \ && func_fatal_configuration "cannot build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test yes = "$build_libtool_libs" && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg=$1 shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir=$arg prev= continue ;; dlfiles|dlprefiles) $preload || { # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=: } case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test no = "$dlself"; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test dlprefiles = "$prev"; then dlself=yes elif test dlfiles = "$prev" && test yes != "$dlopen_self"; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test dlfiles = "$prev"; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols=$arg test -f "$arg" \ || func_fatal_error "symbol file '$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex=$arg prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir=$arg prev= continue ;; mllvm) # Clang does not use LLVM to link, so we can simply discard any # '-mllvm $arg' options when doing the link step. prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result if test none != "$pic_object"; then # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object fi # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file '$arg' does not exist" fi arg=$save_arg prev= continue ;; os2dllname) os2dllname=$arg prev= continue ;; precious_regex) precious_files_regex=$arg prev= continue ;; release) release=-$arg prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test rpath = "$prev"; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds=$arg prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg=$arg case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "'-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test X-export-symbols = "X$arg"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between '-L' and '$1'" else func_fatal_error "need path for '-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of '$dir'" dir=$absdir ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test X-lc = "X$arg" || test X-lm = "X$arg"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test X-lc = "X$arg" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) # Do not include libc due to us having libc/libc_r. test X-lc = "X$arg" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test X-lc = "X$arg" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test X-lc = "X$arg" && continue ;; esac elif test X-lc_r = "X$arg"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -mllvm) prev=mllvm continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module=$wl-multi_module continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "'-no-install' is ignored for $host" func_warning "assuming '-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -os2dllname) prev=os2dllname continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_for_eval "$flag" func_append arg " $func_quote_for_eval_result" func_append compiler_flags " $func_quote_for_eval_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,--as-needed) deplibs="$deplibs $arg" continue ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_for_eval "$flag" func_append arg " $wl$func_quote_for_eval_result" func_append compiler_flags " $wl$func_quote_for_eval_result" func_append linker_flags " $func_quote_for_eval_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # -fstack-protector* stack protector flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization # -stdlib=* select c++ std lib with clang -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; -Z*) if test os2 = "`expr $host : '.*\(os2\)'`"; then # OS/2 uses -Zxxx to specify OS/2-specific options compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case $arg in -Zlinker | -Zstack) prev=xcompiler ;; esac continue else # Otherwise treat like 'Some other compiler flag' below func_quote_for_eval "$arg" arg=$func_quote_for_eval_result fi ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result test none = "$pic_object" || { # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object } # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test dlfiles = "$prev"; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test dlprefiles = "$prev"; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the '$prevarg' option requires an argument" if test yes = "$export_dynamic" && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname=$func_basename_result libobjs_save=$libobjs if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\$$shlibpath_var\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" # Definition is injected by LT_CONFIG during libtool generation. func_munge_path_list sys_lib_dlsearch_path "$LT_SYS_LIBRARY_PATH" func_dirname "$output" "/" "" output_objdir=$func_dirname_result$objdir func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test lib = "$linkmode"; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) as_needed_flag= passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can '-dlopen' only libtool libraries: $file" ;; esac done ;; prog) as_needed_flag= compile_deplibs= finalize_deplibs= alldeplibs=false newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test lib,link = "$linkmode,$pass"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs=$tmp_deplibs fi if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass"; then libs=$deplibs deplibs= fi if test prog = "$linkmode"; then case $pass in dlopen) libs=$dlfiles ;; dlpreopen) libs=$dlprefiles ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test lib,dlpreopen = "$linkmode,$pass"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs=$dlprefiles fi if test dlopen = "$pass"; then # Collect dlpreopened libraries save_deplibs=$deplibs deplibs= fi for deplib in $libs; do lib= found=false case $deplib in -Wl,--as-needed) if test prog,link = "$linkmode,$pass" || test lib,link = "$linkmode,$pass"; then as_needed_flag="$deplib " else deplibs="$deplib $deplibs" fi continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test lib != "$linkmode" && test prog != "$linkmode"; then func_warning "'-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test lib = "$linkmode"; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib=$searchdir/lib$name$search_ext if test -f "$lib"; then if test .la = "$search_ext"; then found=: else found=false fi break 2 fi done done if $found; then # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll=$l done if test "X$ll" = "X$old_library"; then # only static version available found=false func_dirname "$lib" "" "." ladir=$func_dirname_result lib=$ladir/$old_library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi else # deplib doesn't seem to be a libtool library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi ;; # -l *.ltframework) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test conv = "$pass" && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi if test scan = "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "'-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test link = "$pass"; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=false case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=: fi ;; pass_all) valid_a_lib=: ;; esac if $valid_a_lib; then echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" else echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." fi ;; esac continue ;; prog) if test link != "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test conv = "$pass"; then deplibs="$deplib $deplibs" elif test prog = "$linkmode"; then if test dlpreopen = "$pass" || test yes != "$dlopen_support" || test no = "$build_libtool_libs"; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=: continue ;; esac # case $deplib $found || test -f "$lib" \ || func_fatal_error "cannot find the library '$lib' or unhandled argument '$deplib'" # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "'$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir=$func_dirname_result dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass" || { test prog != "$linkmode" && test lib != "$linkmode"; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test conv = "$pass"; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for '$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" elif test prog != "$linkmode" && test lib != "$linkmode"; then func_fatal_error "'$lib' is not a convenience library" fi tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test yes = "$prefer_static_libs" || test built,no = "$prefer_static_libs,$installed"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib=$l done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for '$lib'" fi # This library was specified with -dlopen. if test dlopen = "$pass"; then test -z "$libdir" \ && func_fatal_error "cannot -dlopen a convenience library: '$lib'" if test -z "$dlname" || test yes != "$dlopen_support" || test no = "$build_libtool_libs" then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir=$ladir ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of '$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir=$ladir fi ;; esac func_basename "$lib" laname=$func_basename_result # Find the relevant object directory and library name. if test yes = "$installed"; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library '$lib' was moved." dir=$ladir absdir=$abs_ladir libdir=$abs_ladir else dir=$lt_sysroot$libdir absdir=$lt_sysroot$libdir fi test yes = "$hardcode_automatic" && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir=$ladir absdir=$abs_ladir # Remove this search path later func_append notinst_path " $abs_ladir" else dir=$ladir/$objdir absdir=$abs_ladir/$objdir # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test dlpreopen = "$pass"; then if test -z "$libdir" && test prog = "$linkmode"; then func_fatal_error "only libraries may -dlpreopen a convenience library: '$lib'" fi case $host in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test lib = "$linkmode"; then deplibs="$dir/$old_library $deplibs" elif test prog,link = "$linkmode,$pass"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test prog = "$linkmode" && test link != "$pass"; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=false if test no != "$link_all_deplibs" || test -z "$library_names" || test no = "$build_libtool_libs"; then linkalldeplibs=: fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if $linkalldeplibs; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test prog,link = "$linkmode,$pass"; then if test -n "$library_names" && { { test no = "$prefer_static_libs" || test built,yes = "$prefer_static_libs,$installed"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath"; then # Make sure the rpath contains only unique directories. case $temp_rpath: in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if $alldeplibs && { test pass_all = "$deplibs_check_method" || { test yes = "$build_libtool_libs" && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test built = "$use_static_libs" && test yes = "$installed"; then use_static_libs=no fi if test -n "$library_names" && { test no = "$use_static_libs" || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc* | *os2*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test no = "$installed"; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule= for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule=$dlpremoduletest break fi done if test -z "$dlopenmodule" && test yes = "$shouldnotlink" && test link = "$pass"; then echo if test prog = "$linkmode"; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test lib = "$linkmode" && test yes = "$hardcode_into_libs"; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname=$1 shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname=$dlname elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc* | *os2*) func_arith $current - $age major=$func_arith_result versuffix=-$major ;; esac eval soname=\"$soname_spec\" else soname=$realname fi # Make a new name for the extract_expsyms_cmds to use soroot=$soname func_basename "$soroot" soname=$func_basename_result func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from '$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for '$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test prog = "$linkmode" || test relink != "$opt_mode"; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test no = "$hardcode_direct"; then add=$dir/$linklib case $host in *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;; *-*-sysv4*uw2*) add_dir=-L$dir ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir=-L$dir ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we cannot # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library"; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add=$dir/$old_library fi elif test -n "$old_library"; then add=$dir/$old_library fi fi esac elif test no = "$hardcode_minus_L"; then case $host in *-*-sunos*) add_shlibpath=$dir ;; esac add_dir=-L$dir add=-l$name elif test no = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; relink) if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$dir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$absdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name elif test yes = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; *) lib_linked=no ;; esac if test yes != "$lib_linked"; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test prog = "$linkmode"; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test yes != "$hardcode_direct" && test yes != "$hardcode_minus_L" && test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test prog = "$linkmode" || test relink = "$opt_mode"; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$libdir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$libdir add=-l$name elif test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add=-l$name elif test yes = "$hardcode_automatic"; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib"; then add=$inst_prefix_dir$libdir/$linklib else add=$libdir/$linklib fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir=-L$libdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name fi if test prog = "$linkmode"; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test prog = "$linkmode"; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test unsupported != "$hardcode_direct"; then test -n "$old_library" && linklib=$old_library compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test yes = "$build_libtool_libs"; then # Not a shared library if test pass_all != "$deplibs_check_method"; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system cannot link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test yes = "$module"; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test lib = "$linkmode"; then if test -n "$dependency_libs" && { test yes != "$hardcode_into_libs" || test yes = "$build_old_libs" || test yes = "$link_static"; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs=$temp_deplibs fi func_append newlib_search_path " $absdir" # Link against this library test no = "$link_static" && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test no != "$link_all_deplibs"; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path=$deplib ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir=$dir ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of '$dir'" absdir=$dir fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`$SED -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names"; then for tmp in $deplibrary_names; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl"; then depdepl=$absdir/$objdir/$depdepl darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`$OTOOL64 -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " $wl-dylib_file $wl$darwin_install_name:$depdepl" func_append linker_flags " -dylib_file $darwin_install_name:$depdepl" path= fi fi ;; *) path=-L$absdir/$objdir ;; esac else eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "'$deplib' seems to be moved" path=-L$absdir fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test link = "$pass"; then if test prog = "$linkmode"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs=$newdependency_libs if test dlpreopen = "$pass"; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test dlopen != "$pass"; then test conv = "$pass" || { # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= } if test prog,link = "$linkmode,$pass"; then vars="compile_deplibs finalize_deplibs" else vars=deplibs fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Add Sun CC postdeps if required: test CXX = "$tagname" && { case $host_os in linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; solaris*) func_cc_basename "$CC" case $func_cc_basename_result in CC* | sunCC*) func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; esac } # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i= ;; esac if test -n "$i"; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test prog = "$linkmode"; then dlfiles=$newdlfiles fi if test prog = "$linkmode" || test lib = "$linkmode"; then dlprefiles=$newdlprefiles fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "'-R' is ignored for archives" test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "'-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "'-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs=$output func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form 'libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test no = "$module" \ && func_fatal_help "libtool library '$output' must begin with 'lib'" if test no != "$need_lib_prefix"; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test pass_all != "$deplibs_check_method"; then func_fatal_error "cannot build libtool library '$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test no = "$dlself" \ || func_warning "'-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test 1 -lt "$#" \ && func_warning "ignoring multiple '-rpath's for a libtool library" install_libdir=$1 oldlibs= if test -z "$rpath"; then if test yes = "$build_libtool_libs"; then # Building a libtool convenience library. # Some compilers have problems with a '.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "'-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs=$IFS; IFS=: set dummy $vinfo 0 0 0 shift IFS=$save_ifs test -n "$7" && \ func_fatal_help "too many parameters to '-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major=$1 number_minor=$2 number_revision=$3 # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # that has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|freebsd-elf|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_revision ;; freebsd-aout|qnx|sunos) current=$number_major revision=$number_minor age=0 ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_minor lt_irix_increment=no ;; esac ;; no) current=$1 revision=$2 age=$3 ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT '$current' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION '$revision' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE '$age' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE '$age' is greater than the current interface number '$current'" func_fatal_error "'$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" # On Darwin other compilers case $CC in nagfor*) verstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" ;; *) verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; esac ;; freebsd-aout) major=.$current versuffix=.$current.$revision ;; freebsd-elf) func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; irix | nonstopux) if test no = "$lt_irix_increment"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring=$verstring_prefix$major.$revision # Add in all the interfaces that we are compatible with. loop=$revision while test 0 -ne "$loop"; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring_prefix$major.$iface:$verstring done # Before this point, $major must not contain '.'. major=.$major versuffix=$major.$revision ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=.$current.$age.$revision verstring=$current.$age.$revision # Add in all the interfaces that we are compatible with. loop=$age while test 0 -ne "$loop"; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring:$iface.0 done # Make executables depend on our current version. func_append verstring ":$current.0" ;; qnx) major=.$current versuffix=.$current ;; sco) major=.$current versuffix=.$current ;; sunos) major=.$current versuffix=.$current.$revision ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 file systems. func_arith $current - $age major=$func_arith_result versuffix=-$major ;; *) func_fatal_configuration "unknown library version type '$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring=0.0 ;; esac if test no = "$need_version"; then versuffix= else versuffix=.0.0 fi fi # Remove version info from name if versioning should be avoided if test yes,no = "$avoid_version,$need_version"; then major= versuffix= verstring= fi # Check to see if the archive will have undefined symbols. if test yes = "$allow_undefined"; then if test unsupported = "$allow_undefined_flag"; then if test yes = "$build_old_libs"; then func_warning "undefined symbols not allowed in $host shared libraries; building static only" build_libtool_libs=no else func_fatal_error "can't build $host shared library unless -no-undefined is specified" fi fi else # Don't allow undefined symbols. allow_undefined_flag=$no_undefined_flag fi fi func_generate_dlsyms "$libname" "$libname" : func_append libobjs " $symfileobj" test " " = "$libobjs" && libobjs= if test relink != "$opt_mode"; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*) if test -n "$precious_files_regex"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test yes = "$build_old_libs" && test convenience != "$build_libtool_libs"; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test yes != "$hardcode_into_libs" || test yes = "$build_old_libs"; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles=$dlfiles dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles=$dlprefiles dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test yes = "$build_libtool_libs"; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test yes = "$build_libtool_need_lc"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release= versuffix= major= newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c <<EOF int main() { return 0; } EOF $opt_dry_run || $RM conftest if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then ldd_output=`ldd conftest` for i in $deplibs; do case $i in -l*) func_stripname -l '' "$i" name=$func_stripname_result if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $i "*) func_append newdeplibs " $i" i= ;; esac fi if test -n "$i"; then libname=`eval "\\$ECHO \"$libname_spec\""` deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` set dummy $deplib_matches; shift deplib_match=$1 if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0; then func_append newdeplibs " $i" else droppeddeps=yes echo $ECHO "*** Warning: dynamic linker does not accept needed library $i." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which I believe you do not have" echo "*** because a test_compile did reveal that the linker did not use it for" echo "*** its dynamic dependency list that programs get resolved with at runtime." fi fi ;; *) func_append newdeplibs " $i" ;; esac done else # Error occurred in the first compile. Let's try to salvage # the situation: Compile a separate program for each library. for i in $deplibs; do case $i in -l*) func_stripname -l '' "$i" name=$func_stripname_result $opt_dry_run || $RM conftest if $LTCC $LTCFLAGS -o conftest conftest.c $i; then ldd_output=`ldd conftest` if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $i "*) func_append newdeplibs " $i" i= ;; esac fi if test -n "$i"; then libname=`eval "\\$ECHO \"$libname_spec\""` deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` set dummy $deplib_matches; shift deplib_match=$1 if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0; then func_append newdeplibs " $i" else droppeddeps=yes echo $ECHO "*** Warning: dynamic linker does not accept needed library $i." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because a test_compile did reveal that the linker did not use this one" echo "*** as a dynamic dependency that programs can get resolved with at runtime." fi fi else droppeddeps=yes echo $ECHO "*** Warning! Library $i is needed by this library but I was not able to" echo "*** make it link in! You will probably need to install it or some" echo "*** library that it depends on before this library will be fully" echo "*** functional. Installing it before continuing would be even better." fi ;; *) func_append newdeplibs " $i" ;; esac done fi ;; file_magic*) set dummy $deplibs_check_method; shift file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib= ;; esac fi if test -n "$a_deplib"; then libname=`eval "\\$ECHO \"$libname_spec\""` if test -n "$file_magic_glob"; then libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob` else libnameglob=$libname fi test yes = "$want_nocaseglob" && nocaseglob=`shopt -p nocaseglob` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do if test yes = "$want_nocaseglob"; then shopt -s nocaseglob potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib=$potent_lib while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | $SED 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib=$potliblink;; *) potlib=`$ECHO "$potlib" | $SED 's|[^/]*$||'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib= ;; esac fi if test -n "$a_deplib"; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib=$potent_lib # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs= tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test yes = "$allow_libtool_libs_with_static_runtimes"; then for i in $predeps $postdeps; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s|$i||"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test none = "$deplibs_check_method"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test yes = "$droppeddeps"; then if test yes = "$module"; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test no = "$allow_undefined"; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs=$new_libs # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test yes = "$build_libtool_libs"; then # Remove $wl instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test yes = "$hardcode_into_libs"; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath=$finalize_rpath test relink = "$opt_mode" || rpath=$compile_rpath$rpath for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath=$finalize_shlibpath test relink = "$opt_mode" || shlibpath=$compile_shlibpath$shlibpath if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname=$1 shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname=$realname fi if test -z "$dlname"; then dlname=$soname fi lib=$output_objdir/$realname linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols=$output_objdir/$libname.uexp func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile func_dll_def_p "$export_symbols" || { # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols=$export_symbols export_symbols= always_export_symbols=yes } fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test yes = "$always_export_symbols" || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs=$IFS; IFS='~' for cmd1 in $cmds; do IFS=$save_ifs # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test yes = "$try_normal_branch" \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=$output_objdir/$output_la.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS=$save_ifs if test -n "$export_symbols_regex" && test : != "$skipped_export"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test : != "$skipped_export" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs=$tmp_deplibs if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test yes = "$compiler_needs_object" && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test yes = "$thread_safe" && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test : != "$skipped_export" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then output=$output_objdir/$output_la.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then output=$output_objdir/$output_la.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test yes = "$compiler_needs_object"; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-$k.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test -z "$objlist" || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test 1 -eq "$k"; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-$k.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-$k.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi ${skipped_export-false} && { func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi } test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs=$IFS; IFS='~' for cmd in $concat_cmds; do IFS=$save_ifs $opt_quiet || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi ${skipped_export-false} && { if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi } libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi # A bit hacky. I had wanted to add \$as_needed_flag to archive_cmds instead, but that # comes from libtool.m4 which is part of the project being built. This should put it # in the right place though. if test lib,link = "$linkmode,$pass" && test -n "$as_needed_flag"; then libobjs=$as_needed_flag$libobjs fi save_ifs=$IFS; IFS='~' for cmd in $cmds; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs $opt_quiet || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs # Restore the uninstalled library and exit if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test yes = "$module" || test yes = "$export_dynamic"; then # On all known operating systems, these are identical. dlname=$soname fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "'-R' is ignored for objects" test -n "$vinfo" && \ func_warning "'-version-info' is ignored for objects" test -n "$release" && \ func_warning "'-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object '$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj=$output ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # if reload_cmds runs $LD directly, get rid of -Wl from # whole_archive_flag_spec and hope we can get by with turning comma # into space. case $reload_cmds in *\$LD[\ \$]*) wl= ;; esac if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" test -n "$wl" || tmp_whole_archive_flags=`$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` reload_conv_objs=$reload_objs\ $tmp_whole_archive_flags else gentop=$output_objdir/${obj}x func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test yes = "$build_libtool_libs" || libobjs=$non_pic_objects # Create the old-style object. reload_objs=$objs$old_deplibs' '`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; /\.lib$/d; $lo2o" | $NL2SP`' '$reload_conv_objs output=$obj func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi test yes = "$build_libtool_libs" || { if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS } if test -n "$pic_flag" || test default != "$pic_mode"; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output=$libobj func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "'-version-info' is ignored for programs" test -n "$release" && \ func_warning "'-release' is ignored for programs" $preload \ && test unknown,unknown,unknown = "$dlopen_support,$dlopen_self,$dlopen_self_static" \ && func_warning "'LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test CXX = "$tagname"; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " $wl-bind_at_load" func_append finalize_command " $wl-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs=$new_libs func_append compile_command " $as_needed_flag $compile_deplibs" func_append finalize_command " $as_needed_flag $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath=$rpath rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath=$rpath if test -n "$libobjs" && test yes = "$build_old_libs"; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" false # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=: case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=false ;; *cygwin* | *mingw* ) test yes = "$build_libtool_libs" || wrappers_required=false ;; *) if test no = "$need_relink" || test yes != "$build_libtool_libs"; then wrappers_required=false fi ;; esac $wrappers_required || { # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command=$compile_command$compile_rpath # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.$objext"; then func_show_eval '$RM "$output_objdir/${outputname}S.$objext"' fi exit $exit_status } if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test yes = "$no_install"; then # We don't need to create a wrapper script. link_command=$compile_var$compile_command$compile_rpath # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi case $hardcode_action,$fast_install in relink,*) # Fast installation is not supported link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath func_warning "this platform does not like uninstalled shared libraries" func_warning "'$output' will be relinked during installation" ;; *,yes) link_command=$finalize_var$compile_command$finalize_rpath relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` ;; *,no) link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath ;; *,needless) link_command=$finalize_var$compile_command$finalize_rpath relink_command= ;; esac # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource=$output_path/$objdir/lt-$output_name.c cwrapper=$output_path/$output_name.exe $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host"; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do case $build_libtool_libs in convenience) oldobjs="$libobjs_save $symfileobj" addlibs=$convenience build_libtool_libs=no ;; module) oldobjs=$libobjs_save addlibs=$old_convenience build_libtool_libs=no ;; *) oldobjs="$old_deplibs $non_pic_objects" $preload && test -f "$symfileobj" \ && func_append oldobjs " $symfileobj" addlibs=$old_convenience ;; esac if test -n "$addlibs"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test yes = "$build_libtool_libs"; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase=$func_basename_result case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj"; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test -z "$oldobjs"; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test yes = "$build_old_libs" && old_library=$libname.$libext func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL \"$progpath\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` if test yes = "$hardcode_automatic"; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test yes = "$installed"; then if test -z "$install_libdir"; then break fi output=$output_objdir/${outputname}i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name=$func_basename_result func_resolve_sysroot "$deplib" eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs=$newdependency_libs newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles=$newdlprefiles else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles=$newdlprefiles fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test -n "$bindir"; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result/$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that cannot go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test no,yes = "$installed,$need_relink"; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } if test link = "$opt_mode" || test relink = "$opt_mode"; then func_mode_link ${1+"$@"} fi # func_mode_uninstall arg... func_mode_uninstall () { $debug_cmd RM=$nonopt files= rmforce=false exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic for arg do case $arg in -f) func_append RM " $arg"; rmforce=: ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir=$func_dirname_result if test . = "$dir"; then odir=$objdir else odir=$dir/$objdir fi func_basename "$file" name=$func_basename_result test uninstall = "$opt_mode" && odir=$dir # Remember odir for removal later, being careful to avoid duplicates if test clean = "$opt_mode"; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif $rmforce; then continue fi rmfiles=$file case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case $opt_mode in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" '$rmforce || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" '$rmforce || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test none != "$pic_object"; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test none != "$non_pic_object"; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test clean = "$opt_mode"; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.$objext" if test yes = "$fast_install" && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name"; then func_append rmfiles " $odir/lt-$noexename.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the $objdir's in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } if test uninstall = "$opt_mode" || test clean = "$opt_mode"; then func_mode_uninstall ${1+"$@"} fi test -z "$opt_mode" && { help=$generic_help func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode '$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # where we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End:
Shell
3D
mcellteam/mcell
libs/gperftools/autogen.sh
.sh
25
4
#!/bin/sh autoreconf -i
Shell
3D
mcellteam/mcell
libs/gperftools/packages/deb.sh
.sh
2,560
75
#!/bin/bash -e # This takes one commandline argument, the name of the package. If no # name is given, then we'll end up just using the name associated with # an arbitrary .tar.gz file in the rootdir. That's fine: there's probably # only one. # # Run this from the 'packages' directory, just under rootdir ## Set LIB to lib if exporting a library, empty-string else LIB= #LIB=lib PACKAGE="$1" VERSION="$2" # We can only build Debian packages, if the Debian build tools are installed if [ \! -x /usr/bin/debuild ]; then echo "Cannot find /usr/bin/debuild. Not building Debian packages." 1>&2 exit 0 fi # Double-check we're in the packages directory, just under rootdir if [ \! -r ../Makefile -a \! -r ../INSTALL ]; then echo "Must run $0 in the 'packages' directory, under the root directory." 1>&2 echo "Also, you must run \"make dist\" before running this script." 1>&2 exit 0 fi # Find the top directory for this package topdir="${PWD%/*}" # Find the tar archive built by "make dist" archive="${PACKAGE}-${VERSION}" archive_with_underscore="${PACKAGE}_${VERSION}" if [ -z "${archive}" ]; then echo "Cannot find ../$PACKAGE*.tar.gz. Run \"make dist\" first." 1>&2 exit 0 fi # Create a pristine directory for building the Debian package files trap 'rm -rf '`pwd`/tmp'; exit $?' EXIT SIGHUP SIGINT SIGTERM rm -rf tmp mkdir -p tmp cd tmp # Debian has very specific requirements about the naming of build # directories, and tar archives. It also wants to write all generated # packages to the parent of the source directory. We accommodate these # requirements by building directly from the tar file. ln -s "${topdir}/${archive}.tar.gz" "${LIB}${archive}.orig.tar.gz" # Some version of debuilder want foo.orig.tar.gz with _ between versions. ln -s "${topdir}/${archive}.tar.gz" "${LIB}${archive_with_underscore}.orig.tar.gz" tar zfx "${LIB}${archive}.orig.tar.gz" [ -n "${LIB}" ] && mv "${archive}" "${LIB}${archive}" cd "${LIB}${archive}" # This is one of those 'specific requirements': where the deb control files live cp -a "packages/deb" "debian" # Now, we can call Debian's standard build tool debuild -uc -us cd ../.. # get back to the original top-level dir # We'll put the result in a subdirectory that's named after the OS version # we've made this .deb file for. destdir="debian-$(cat /etc/debian_version 2>/dev/null || echo UNKNOWN)" rm -rf "$destdir" mkdir -p "$destdir" mv $(find tmp -mindepth 1 -maxdepth 1 -type f) "$destdir" echo echo "The Debian package files are located in $PWD/$destdir"
Shell
3D
mcellteam/mcell
libs/gperftools/packages/rpm.sh
.sh
2,661
87
#!/bin/sh -e # Run this from the 'packages' directory, just under rootdir # We can only build rpm packages, if the rpm build tools are installed if [ \! -x /usr/bin/rpmbuild ] then echo "Cannot find /usr/bin/rpmbuild. Not building an rpm." 1>&2 exit 0 fi # Check the commandline flags PACKAGE="$1" VERSION="$2" fullname="${PACKAGE}-${VERSION}" archive=../$fullname.tar.gz if [ -z "$1" -o -z "$2" ] then echo "Usage: $0 <package name> <package version>" 1>&2 exit 0 fi # Double-check we're in the packages directory, just under rootdir if [ \! -r ../Makefile -a \! -r ../INSTALL ] then echo "Must run $0 in the 'packages' directory, under the root directory." 1>&2 echo "Also, you must run \"make dist\" before running this script." 1>&2 exit 0 fi if [ \! -r "$archive" ] then echo "Cannot find $archive. Run \"make dist\" first." 1>&2 exit 0 fi # Create the directory where the input lives, and where the output should live RPM_SOURCE_DIR="/tmp/rpmsource-$fullname" RPM_BUILD_DIR="/tmp/rpmbuild-$fullname" trap 'rm -rf $RPM_SOURCE_DIR $RPM_BUILD_DIR; exit $?' EXIT SIGHUP SIGINT SIGTERM rm -rf "$RPM_SOURCE_DIR" "$RPM_BUILD_DIR" mkdir "$RPM_SOURCE_DIR" mkdir "$RPM_BUILD_DIR" cp "$archive" "$RPM_SOURCE_DIR" # rpmbuild -- as far as I can tell -- asks the OS what CPU it has. # This may differ from what kind of binaries gcc produces. dpkg # does a better job of this, so if we can run 'dpkg --print-architecture' # to get the build CPU, we use that in preference of the rpmbuild # default. target=`dpkg --print-architecture 2>/dev/null || echo ""` if [ -n "$target" ] then target=" --target $target" fi rpmbuild -bb rpm/rpm.spec $target \ --define "NAME $PACKAGE" \ --define "VERSION $VERSION" \ --define "_sourcedir $RPM_SOURCE_DIR" \ --define "_builddir $RPM_BUILD_DIR" \ --define "_rpmdir $RPM_SOURCE_DIR" # We put the output in a directory based on what system we've built for destdir=rpm-unknown if [ -r /etc/issue ] then grep "Red Hat.*release 7" /etc/issue >/dev/null 2>&1 && destdir=rh7 grep "Red Hat.*release 8" /etc/issue >/dev/null 2>&1 && destdir=rh8 grep "Red Hat.*release 9" /etc/issue >/dev/null 2>&1 && destdir=rh9 grep "Fedora Core.*release 1" /etc/issue >/dev/null 2>&1 && destdir=fc1 grep "Fedora Core.*release 2" /etc/issue >/dev/null 2>&1 && destdir=fc2 grep "Fedora Core.*release 3" /etc/issue >/dev/null 2>&1 && destdir=fc3 fi rm -rf "$destdir" mkdir -p "$destdir" # We want to get not only the main package but devel etc, hence the middle * mv "$RPM_SOURCE_DIR"/*/"${PACKAGE}"-*"${VERSION}"*.rpm "$destdir" echo echo "The rpm package file(s) are located in $PWD/$destdir"
Shell
3D
mcellteam/mcell
libs/gperftools/benchmark/binary_trees.cc
.cc
2,832
109
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // // Copied from // http://benchmarksgame.alioth.debian.org/u64q/program.php?test=binarytrees&lang=gpp&id=2 // and slightly modified (particularly by adding multi-threaded // operation to hit malloc harder). // // This version of binary trees is mostly new/delete benchmark // // NOTE: copyright of this code is unclear, but we only distribute // source. /* The Computer Language Benchmarks Game * http://benchmarksgame.alioth.debian.org/ * * Contributed by Jon Harrop * Modified by Alex Mizrahi * Adapted for gperftools and added threads by Aliaksei Kandratsenka */ #include <algorithm> #include <errno.h> #include <iostream> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <vector> struct Node { Node *l, *r; int i; Node(int i2) : l(0), r(0), i(i2) {} Node(Node *l2, int i2, Node *r2) : l(l2), r(r2), i(i2) {} ~Node() { delete l; delete r; } int check() const { if (l) { return l->check() + i - r->check(); } else { return i; } } }; Node *make(int i, int d) { if (d == 0) return new Node(i); return new Node(make(2*i-1, d-1), i, make(2*i, d-1)); } void run(int given_depth) { int min_depth = 4, max_depth = std::max(min_depth+2, given_depth), stretch_depth = max_depth+1; { Node *c = make(0, stretch_depth); std::cout << "stretch tree of depth " << stretch_depth << "\t " << "check: " << c->check() << std::endl; delete c; } Node *long_lived_tree=make(0, max_depth); for (int d=min_depth; d<=max_depth; d+=2) { int iterations = 1 << (max_depth - d + min_depth), c=0; for (int i=1; i<=iterations; ++i) { Node *a = make(i, d), *b = make(-i, d); c += a->check() + b->check(); delete a; delete b; } std::cout << (2*iterations) << "\t trees of depth " << d << "\t " << "check: " << c << std::endl; } std::cout << "long lived tree of depth " << max_depth << "\t " << "check: " << (long_lived_tree->check()) << "\n"; delete long_lived_tree; } static void *run_tramp(void *_a) { intptr_t a = reinterpret_cast<intptr_t>(_a); run(a); return 0; } int main(int argc, char *argv[]) { int given_depth = argc >= 2 ? atoi(argv[1]) : 20; int thread_count = std::max(1, argc >= 3 ? atoi(argv[2]) : 1) - 1; std::vector<pthread_t> threads(thread_count); for (int i = 0; i < thread_count; i++) { int rv = pthread_create(&threads[i], NULL, run_tramp, reinterpret_cast<void *>(given_depth)); if (rv) { errno = rv; perror("pthread_create"); } } run_tramp(reinterpret_cast<void *>(given_depth)); for (int i = 0; i < thread_count; i++) { pthread_join(threads[i], NULL); } return 0; }
Unknown
3D
mcellteam/mcell
libs/gperftools/benchmark/malloc_bench.cc
.cc
8,769
294
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <algorithm> #include "run_benchmark.h" static void bench_fastpath_throughput(long iterations, uintptr_t param) { size_t sz = 32; for (; iterations>0; iterations--) { void *p = malloc(sz); if (!p) { abort(); } free(p); // this makes next iteration use different free list. So // subsequent iterations may actually overlap in time. sz = ((sz * 8191) & 511) + 16; } } static void bench_fastpath_dependent(long iterations, uintptr_t param) { size_t sz = 32; for (; iterations>0; iterations--) { void *p = malloc(sz); if (!p) { abort(); } free(p); // this makes next iteration depend on current iteration. But this // iteration's free may still overlap with next iteration's malloc sz = ((sz | reinterpret_cast<size_t>(p)) & 511) + 16; } } static void bench_fastpath_simple(long iterations, uintptr_t param) { size_t sz = static_cast<size_t>(param); for (; iterations>0; iterations--) { void *p = malloc(sz); if (!p) { abort(); } free(p); // next iteration will use same free list as this iteration. So it // should be prevent next iterations malloc to go too far before // free done. But using same size will make free "too fast" since // we'll hit size class cache. } } #ifdef __GNUC__ #define HAVE_SIZED_FREE_OPTION extern "C" void tc_free_sized(void *ptr, size_t size) __attribute__((weak)); extern "C" void *tc_memalign(size_t align, size_t size) __attribute__((weak)); static bool is_sized_free_available(void) { return tc_free_sized != NULL; } static bool is_memalign_available(void) { return tc_memalign != NULL; } static void bench_fastpath_simple_sized(long iterations, uintptr_t param) { size_t sz = static_cast<size_t>(param); for (; iterations>0; iterations--) { void *p = malloc(sz); if (!p) { abort(); } tc_free_sized(p, sz); // next iteration will use same free list as this iteration. So it // should be prevent next iterations malloc to go too far before // free done. But using same size will make free "too fast" since // we'll hit size class cache. } } static void bench_fastpath_memalign(long iterations, uintptr_t param) { size_t sz = static_cast<size_t>(param); for (; iterations>0; iterations--) { void *p = tc_memalign(32, sz); if (!p) { abort(); } free(p); // next iteration will use same free list as this iteration. So it // should be prevent next iterations malloc to go too far before // free done. But using same size will make free "too fast" since // we'll hit size class cache. } } #endif // __GNUC__ #define STACKSZ (1 << 16) static void bench_fastpath_stack(long iterations, uintptr_t _param) { void *stack[STACKSZ]; size_t sz = 64; long param = static_cast<long>(_param); param &= STACKSZ - 1; param = param ? param : 1; for (; iterations>0; iterations -= param) { for (long k = param-1; k >= 0; k--) { void *p = malloc(sz); if (!p) { abort(); } stack[k] = p; // this makes next iteration depend on result of this iteration sz = ((sz | reinterpret_cast<size_t>(p)) & 511) + 16; } for (long k = 0; k < param; k++) { free(stack[k]); } } } static void bench_fastpath_stack_simple(long iterations, uintptr_t _param) { void *stack[STACKSZ]; size_t sz = 128; long param = static_cast<long>(_param); param &= STACKSZ - 1; param = param ? param : 1; for (; iterations>0; iterations -= param) { for (long k = param-1; k >= 0; k--) { void *p = malloc(sz); if (!p) { abort(); } stack[k] = p; } for (long k = 0; k < param; k++) { free(stack[k]); } } } static void bench_fastpath_rnd_dependent(long iterations, uintptr_t _param) { static const uintptr_t rnd_c = 1013904223; static const uintptr_t rnd_a = 1664525; void *ptrs[STACKSZ]; size_t sz = 128; if ((_param & (_param - 1))) { abort(); } if (_param > STACKSZ) { abort(); } int param = static_cast<int>(_param); for (; iterations>0; iterations -= param) { for (int k = param-1; k >= 0; k--) { void *p = malloc(sz); if (!p) { abort(); } ptrs[k] = p; sz = ((sz | reinterpret_cast<size_t>(p)) & 511) + 16; } // this will iterate through all objects in order that is // unpredictable to processor's prefetchers uint32_t rnd = 0; uint32_t free_idx = 0; do { free(ptrs[free_idx]); rnd = rnd * rnd_a + rnd_c; free_idx = rnd & (param - 1); } while (free_idx != 0); } } static void *randomize_buffer[13<<20]; void randomize_one_size_class(size_t size) { int count = (100<<20) / size; if (count * sizeof(randomize_buffer[0]) > sizeof(randomize_buffer)) { abort(); } for (int i = 0; i < count; i++) { randomize_buffer[i] = malloc(size); } std::random_shuffle(randomize_buffer, randomize_buffer + count); for (int i = 0; i < count; i++) { free(randomize_buffer[i]); } } void randomize_size_classes() { randomize_one_size_class(8); int i; for (i = 16; i < 256; i += 16) { randomize_one_size_class(i); } for (; i < 512; i += 32) { randomize_one_size_class(i); } for (; i < 1024; i += 64) { randomize_one_size_class(i); } for (; i < (4 << 10); i += 128) { randomize_one_size_class(i); } for (; i < (32 << 10); i += 1024) { randomize_one_size_class(i); } } int main(void) { randomize_size_classes(); report_benchmark("bench_fastpath_throughput", bench_fastpath_throughput, 0); report_benchmark("bench_fastpath_dependent", bench_fastpath_dependent, 0); report_benchmark("bench_fastpath_simple", bench_fastpath_simple, 64); report_benchmark("bench_fastpath_simple", bench_fastpath_simple, 2048); report_benchmark("bench_fastpath_simple", bench_fastpath_simple, 16384); #ifdef HAVE_SIZED_FREE_OPTION if (is_sized_free_available()) { report_benchmark("bench_fastpath_simple_sized", bench_fastpath_simple_sized, 64); report_benchmark("bench_fastpath_simple_sized", bench_fastpath_simple_sized, 2048); } if (is_memalign_available()) { report_benchmark("bench_fastpath_memalign", bench_fastpath_memalign, 64); report_benchmark("bench_fastpath_memalign", bench_fastpath_memalign, 2048); } #endif for (int i = 8; i <= 512; i <<= 1) { report_benchmark("bench_fastpath_stack", bench_fastpath_stack, i); } report_benchmark("bench_fastpath_stack_simple", bench_fastpath_stack_simple, 32); report_benchmark("bench_fastpath_stack_simple", bench_fastpath_stack_simple, 8192); report_benchmark("bench_fastpath_rnd_dependent", bench_fastpath_rnd_dependent, 32); report_benchmark("bench_fastpath_rnd_dependent", bench_fastpath_rnd_dependent, 8192); return 0; }
Unknown
3D
mcellteam/mcell
libs/gperftools/benchmark/run_benchmark.h
.h
1,882
44
// -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*- // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _RUN_BENCHMARK_H_ #define _RUN_BENCHMARK_H_ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef void (*bench_body)(long iterations, uintptr_t param); void report_benchmark(const char *name, bench_body body, uintptr_t param); #ifdef __cplusplus } // extern "C" #endif #endif // _RUN_BENCHMARK_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/benchmark/run_benchmark.c
.c
3,351
113
// -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*- // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "run_benchmark.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> struct internal_bench { bench_body body; uintptr_t param; }; static void run_body(struct internal_bench *b, long iterations) { b->body(iterations, b->param); } static double measure_once(struct internal_bench *b, long iterations) { struct timeval tv_before, tv_after; int rv; double time; rv = gettimeofday(&tv_before, NULL); if (rv) { perror("gettimeofday"); abort(); } run_body(b, iterations); rv = gettimeofday(&tv_after, NULL); if (rv) { perror("gettimeofday"); abort(); } tv_after.tv_sec -= tv_before.tv_sec; time = tv_after.tv_sec * 1E6 + tv_after.tv_usec; time -= tv_before.tv_usec; time *= 1000; return time; } #define TRIAL_NSEC 0.3E9 #define TARGET_NSEC 3E9 static double run_benchmark(struct internal_bench *b) { long iterations = 128; double nsec; while (1) { nsec = measure_once(b, iterations); if (nsec > TRIAL_NSEC) { break; } iterations <<= 1; } while (nsec < TARGET_NSEC) { iterations = (long)(iterations * TARGET_NSEC * 1.1 / nsec); nsec = measure_once(b, iterations); } return nsec / iterations; } void report_benchmark(const char *name, bench_body body, uintptr_t param) { int i; struct internal_bench b = {.body = body, .param = param}; for (i = 0; i < 3; i++) { double nsec = run_benchmark(&b); int slen; int padding_size; slen = printf("Benchmark: %s", name); if (param && name[strlen(name)-1] != ')') { slen += printf("(%lld)", (long long)param); } padding_size = 60 - slen; if (padding_size < 1) { padding_size = 1; } printf("%*c%f nsec\n", padding_size, ' ', nsec); fflush(stdout); } }
C
3D
mcellteam/mcell
libs/gperftools/src/emergency_malloc.h
.h
2,649
61
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2014, gperftools Contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EMERGENCY_MALLOC_H #define EMERGENCY_MALLOC_H #include "config.h" #include <stddef.h> #include "base/basictypes.h" #include "common.h" namespace tcmalloc { static const uintptr_t kEmergencyArenaShift = 20+4; // 16 megs static const uintptr_t kEmergencyArenaSize = 1 << kEmergencyArenaShift; extern __attribute__ ((visibility("internal"))) char *emergency_arena_start; extern __attribute__ ((visibility("internal"))) uintptr_t emergency_arena_start_shifted;; PERFTOOLS_DLL_DECL void *EmergencyMalloc(size_t size); PERFTOOLS_DLL_DECL void EmergencyFree(void *p); PERFTOOLS_DLL_DECL void *EmergencyCalloc(size_t n, size_t elem_size); PERFTOOLS_DLL_DECL void *EmergencyRealloc(void *old_ptr, size_t new_size); static inline bool IsEmergencyPtr(const void *_ptr) { uintptr_t ptr = reinterpret_cast<uintptr_t>(_ptr); return PREDICT_FALSE((ptr >> kEmergencyArenaShift) == emergency_arena_start_shifted) && emergency_arena_start_shifted; } } // namespace tcmalloc #endif
Unknown
3D
mcellteam/mcell
libs/gperftools/src/profiler.cc
.cc
14,833
429
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // Chris Demetriou (refactoring) // // Profile current program by sampling stack-trace every so often #include "config.h" #include "getpc.h" // should be first to get the _GNU_SOURCE dfn #include <signal.h> #include <assert.h> #include <stdio.h> #include <errno.h> #include <string.h> #ifdef HAVE_UNISTD_H #include <unistd.h> // for getpid() #endif #if defined(HAVE_SYS_UCONTEXT_H) #include <sys/ucontext.h> #elif defined(HAVE_UCONTEXT_H) #include <ucontext.h> #elif defined(HAVE_CYGWIN_SIGNAL_H) #include <cygwin/signal.h> typedef ucontext ucontext_t; #else typedef int ucontext_t; // just to quiet the compiler, mostly #endif #include <sys/time.h> #include <string> #include <gperftools/profiler.h> #include <gperftools/stacktrace.h> #include "base/commandlineflags.h" #include "base/logging.h" #include "base/googleinit.h" #include "base/spinlock.h" #include "base/sysinfo.h" /* for GetUniquePathFromEnv, etc */ #include "profiledata.h" #include "profile-handler.h" #ifdef HAVE_CONFLICT_SIGNAL_H #include "conflict-signal.h" /* used on msvc machines */ #endif using std::string; DEFINE_bool(cpu_profiler_unittest, EnvToBool("PERFTOOLS_UNITTEST", true), "Determines whether or not we are running under the \ control of a unit test. This allows us to include or \ exclude certain behaviours."); // Collects up all profile data. This is a singleton, which is // initialized by a constructor at startup. If no cpu profiler // signal is specified then the profiler lifecycle is either // manaully controlled via the API or attached to the scope of // the singleton (program scope). Otherwise the cpu toggle is // used to allow for user selectable control via signal generation. // This is very useful for profiling a daemon process without // having to start and stop the daemon or having to modify the // source code to use the cpu profiler API. class CpuProfiler { public: CpuProfiler(); ~CpuProfiler(); // Start profiler to write profile info into fname bool Start(const char* fname, const ProfilerOptions* options); // Stop profiling and write the data to disk. void Stop(); // Write the data to disk (and continue profiling). void FlushTable(); bool Enabled(); void GetCurrentState(ProfilerState* state); static CpuProfiler instance_; private: // This lock implements the locking requirements described in the ProfileData // documentation, specifically: // // lock_ is held all over all collector_ method calls except for the 'Add' // call made from the signal handler, to protect against concurrent use of // collector_'s control routines. Code other than signal handler must // unregister the signal handler before calling any collector_ method. // 'Add' method in the collector is protected by a guarantee from // ProfileHandle that only one instance of prof_handler can run at a time. SpinLock lock_; ProfileData collector_; // Filter function and its argument, if any. (NULL means include all // samples). Set at start, read-only while running. Written while holding // lock_, read and executed in the context of SIGPROF interrupt. int (*filter_)(void*); void* filter_arg_; // Opaque token returned by the profile handler. To be used when calling // ProfileHandlerUnregisterCallback. ProfileHandlerToken* prof_handler_token_; // Sets up a callback to receive SIGPROF interrupt. void EnableHandler(); // Disables receiving SIGPROF interrupt. void DisableHandler(); // Signal handler that records the interrupted pc in the profile data. static void prof_handler(int sig, siginfo_t*, void* signal_ucontext, void* cpu_profiler); }; // Signal handler that is registered when a user selectable signal // number is defined in the environment variable CPUPROFILESIGNAL. static void CpuProfilerSwitch(int signal_number) { static unsigned profile_count; static char base_profile_name[PATH_MAX]; static bool started = false; if (base_profile_name[0] == '\0') { if (!GetUniquePathFromEnv("CPUPROFILE", base_profile_name)) { RAW_LOG(FATAL,"Cpu profiler switch is registered but no CPUPROFILE is defined"); return; } } if (!started) { char full_profile_name[PATH_MAX + 16]; snprintf(full_profile_name, sizeof(full_profile_name), "%s.%u", base_profile_name, profile_count++); if(!ProfilerStart(full_profile_name)) { RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n", full_profile_name, strerror(errno)); } } else { ProfilerStop(); } started = !started; } // Profile data structure singleton: Constructor will check to see if // profiling should be enabled. Destructor will write profile data // out to disk. CpuProfiler CpuProfiler::instance_; // Initialize profiling: activated if getenv("CPUPROFILE") exists. CpuProfiler::CpuProfiler() : prof_handler_token_(NULL) { // TODO(cgd) Move this code *out* of the CpuProfile constructor into a // separate object responsible for initialization. With ProfileHandler there // is no need to limit the number of profilers. if (getenv("CPUPROFILE") == NULL) { if (!FLAGS_cpu_profiler_unittest) { RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n"); } return; } // We don't enable profiling if setuid -- it's a security risk #ifdef HAVE_GETEUID if (getuid() != geteuid()) { if (!FLAGS_cpu_profiler_unittest) { RAW_LOG(WARNING, "Cannot perform CPU profiling when running with setuid\n"); } return; } #endif char *signal_number_str = getenv("CPUPROFILESIGNAL"); if (signal_number_str != NULL) { long int signal_number = strtol(signal_number_str, NULL, 10); if (signal_number >= 1 && signal_number <= 64) { intptr_t old_signal_handler = reinterpret_cast<intptr_t>(signal(signal_number, CpuProfilerSwitch)); if (old_signal_handler == 0) { RAW_LOG(INFO,"Using signal %d as cpu profiling switch", signal_number); } else { RAW_LOG(FATAL, "Signal %d already in use\n", signal_number); } } else { RAW_LOG(FATAL, "Signal number %s is invalid\n", signal_number_str); } } else { char fname[PATH_MAX]; if (!GetUniquePathFromEnv("CPUPROFILE", fname)) { if (!FLAGS_cpu_profiler_unittest) { RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n"); } return; } if (!Start(fname, NULL)) { RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n", fname, strerror(errno)); } } } bool CpuProfiler::Start(const char* fname, const ProfilerOptions* options) { SpinLockHolder cl(&lock_); if (collector_.enabled()) { return false; } ProfileHandlerState prof_handler_state; ProfileHandlerGetState(&prof_handler_state); ProfileData::Options collector_options; collector_options.set_frequency(prof_handler_state.frequency); if (!collector_.Start(fname, collector_options)) { return false; } filter_ = NULL; if (options != NULL && options->filter_in_thread != NULL) { filter_ = options->filter_in_thread; filter_arg_ = options->filter_in_thread_arg; } // Setup handler for SIGPROF interrupts EnableHandler(); return true; } CpuProfiler::~CpuProfiler() { Stop(); } // Stop profiling and write out any collected profile data void CpuProfiler::Stop() { SpinLockHolder cl(&lock_); if (!collector_.enabled()) { return; } // Unregister prof_handler to stop receiving SIGPROF interrupts before // stopping the collector. DisableHandler(); // DisableHandler waits for the currently running callback to complete and // guarantees no future invocations. It is safe to stop the collector. collector_.Stop(); } void CpuProfiler::FlushTable() { SpinLockHolder cl(&lock_); if (!collector_.enabled()) { return; } // Unregister prof_handler to stop receiving SIGPROF interrupts before // flushing the profile data. DisableHandler(); // DisableHandler waits for the currently running callback to complete and // guarantees no future invocations. It is safe to flush the profile data. collector_.FlushTable(); EnableHandler(); } bool CpuProfiler::Enabled() { SpinLockHolder cl(&lock_); return collector_.enabled(); } void CpuProfiler::GetCurrentState(ProfilerState* state) { ProfileData::State collector_state; { SpinLockHolder cl(&lock_); collector_.GetCurrentState(&collector_state); } state->enabled = collector_state.enabled; state->start_time = static_cast<time_t>(collector_state.start_time); state->samples_gathered = collector_state.samples_gathered; int buf_size = sizeof(state->profile_name); strncpy(state->profile_name, collector_state.profile_name, buf_size); state->profile_name[buf_size-1] = '\0'; } void CpuProfiler::EnableHandler() { RAW_CHECK(prof_handler_token_ == NULL, "SIGPROF handler already registered"); prof_handler_token_ = ProfileHandlerRegisterCallback(prof_handler, this); RAW_CHECK(prof_handler_token_ != NULL, "Failed to set up SIGPROF handler"); } void CpuProfiler::DisableHandler() { RAW_CHECK(prof_handler_token_ != NULL, "SIGPROF handler is not registered"); ProfileHandlerUnregisterCallback(prof_handler_token_); prof_handler_token_ = NULL; } // Signal handler that records the pc in the profile-data structure. We do no // synchronization here. profile-handler.cc guarantees that at most one // instance of prof_handler() will run at a time. All other routines that // access the data touched by prof_handler() disable this signal handler before // accessing the data and therefore cannot execute concurrently with // prof_handler(). void CpuProfiler::prof_handler(int sig, siginfo_t*, void* signal_ucontext, void* cpu_profiler) { CpuProfiler* instance = static_cast<CpuProfiler*>(cpu_profiler); if (instance->filter_ == NULL || (*instance->filter_)(instance->filter_arg_)) { void* stack[ProfileData::kMaxStackDepth]; // Under frame-pointer-based unwinding at least on x86, the // top-most active routine doesn't show up as a normal frame, but // as the "pc" value in the signal handler context. stack[0] = GetPC(*reinterpret_cast<ucontext_t*>(signal_ucontext)); // We skip the top three stack trace entries (this function, // SignalHandler::SignalHandler and one signal handler frame) // since they are artifacts of profiling and should not be // measured. Other profiling related frames may be removed by // "pprof" at analysis time. Instead of skipping the top frames, // we could skip nothing, but that would increase the profile size // unnecessarily. int depth = GetStackTraceWithContext(stack + 1, arraysize(stack) - 1, 3, signal_ucontext); void **used_stack; if (depth > 0 && stack[1] == stack[0]) { // in case of non-frame-pointer-based unwinding we will get // duplicate of PC in stack[1], which we don't want used_stack = stack + 1; } else { used_stack = stack; depth++; // To account for pc value in stack[0]; } instance->collector_.Add(depth, used_stack); } } #if !(defined(__CYGWIN__) || defined(__CYGWIN32__)) extern "C" PERFTOOLS_DLL_DECL void ProfilerRegisterThread() { ProfileHandlerRegisterThread(); } extern "C" PERFTOOLS_DLL_DECL void ProfilerFlush() { CpuProfiler::instance_.FlushTable(); } extern "C" PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads() { return CpuProfiler::instance_.Enabled(); } extern "C" PERFTOOLS_DLL_DECL int ProfilerStart(const char* fname) { return CpuProfiler::instance_.Start(fname, NULL); } extern "C" PERFTOOLS_DLL_DECL int ProfilerStartWithOptions( const char *fname, const ProfilerOptions *options) { return CpuProfiler::instance_.Start(fname, options); } extern "C" PERFTOOLS_DLL_DECL void ProfilerStop() { CpuProfiler::instance_.Stop(); } extern "C" PERFTOOLS_DLL_DECL void ProfilerGetCurrentState( ProfilerState* state) { CpuProfiler::instance_.GetCurrentState(state); } #else // OS_CYGWIN // ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't // work as well for profiling, and also interferes with alarm(). Because of // these issues, unless a specific need is identified, profiler support is // disabled under Cygwin. extern "C" void ProfilerRegisterThread() { } extern "C" void ProfilerFlush() { } extern "C" int ProfilingIsEnabledForAllThreads() { return 0; } extern "C" int ProfilerStart(const char* fname) { return 0; } extern "C" int ProfilerStartWithOptions(const char *fname, const ProfilerOptions *options) { return 0; } extern "C" void ProfilerStop() { } extern "C" void ProfilerGetCurrentState(ProfilerState* state) { memset(state, 0, sizeof(*state)); } #endif // OS_CYGWIN // DEPRECATED routines extern "C" PERFTOOLS_DLL_DECL void ProfilerEnable() { } extern "C" PERFTOOLS_DLL_DECL void ProfilerDisable() { }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/malloc_hook.cc
.cc
26,372
712
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #include <config.h> // Disable the glibc prototype of mremap(), as older versions of the // system headers define this function with only four arguments, // whereas newer versions allow an optional fifth argument: #ifdef HAVE_MMAP # define mremap glibc_mremap # include <sys/mman.h> # undef mremap #endif #include <stddef.h> #ifdef HAVE_STDINT_H #include <stdint.h> #endif #include <algorithm> #include "base/logging.h" #include "base/spinlock.h" #include "maybe_emergency_malloc.h" #include "maybe_threads.h" #include "malloc_hook-inl.h" #include <gperftools/malloc_hook.h> // This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if // you're porting to a system where you really can't get a stacktrace. #ifdef NO_TCMALLOC_SAMPLES // We use #define so code compiles even if you #include stacktrace.h somehow. # define GetStackTrace(stack, depth, skip) (0) #else # include <gperftools/stacktrace.h> #endif // __THROW is defined in glibc systems. It means, counter-intuitively, // "This function will never throw an exception." It's an optional // optimization tool, but we may need to use it to match glibc prototypes. #ifndef __THROW // I guess we're not on a glibc system # define __THROW // __THROW is just an optimization, so ok to make it "" #endif using std::copy; // Declaration of default weak initialization function, that can be overridden // by linking-in a strong definition (as heap-checker.cc does). This is // extern "C" so that it doesn't trigger gold's --detect-odr-violations warning, // which only looks at C++ symbols. // // This function is declared here as weak, and defined later, rather than a more // straightforward simple weak definition, as a workround for an icc compiler // issue ((Intel reference 290819). This issue causes icc to resolve weak // symbols too early, at compile rather than link time. By declaring it (weak) // here, then defining it below after its use, we can avoid the problem. extern "C" { ATTRIBUTE_WEAK void MallocHook_InitAtFirstAllocation_HeapLeakChecker(); } namespace { void RemoveInitialHooksAndCallInitializers(); // below. pthread_once_t once = PTHREAD_ONCE_INIT; // These hooks are installed in MallocHook as the only initial hooks. The first // hook that is called will run RemoveInitialHooksAndCallInitializers (see the // definition below) and then redispatch to any malloc hooks installed by // RemoveInitialHooksAndCallInitializers. // // Note(llib): there is a possibility of a race in the event that there are // multiple threads running before the first allocation. This is pretty // difficult to achieve, but if it is then multiple threads may concurrently do // allocations. The first caller will call // RemoveInitialHooksAndCallInitializers via one of the initial hooks. A // concurrent allocation may, depending on timing either: // * still have its initial malloc hook installed, run that and block on waiting // for the first caller to finish its call to // RemoveInitialHooksAndCallInitializers, and proceed normally. // * occur some time during the RemoveInitialHooksAndCallInitializers call, at // which point there could be no initial hooks and the subsequent hooks that // are about to be set up by RemoveInitialHooksAndCallInitializers haven't // been installed yet. I think the worst we can get is that some allocations // will not get reported to some hooks set by the initializers called from // RemoveInitialHooksAndCallInitializers. void InitialNewHook(const void* ptr, size_t size) { perftools_pthread_once(&once, &RemoveInitialHooksAndCallInitializers); MallocHook::InvokeNewHook(ptr, size); } void InitialPreMMapHook(const void* start, size_t size, int protection, int flags, int fd, off_t offset) { perftools_pthread_once(&once, &RemoveInitialHooksAndCallInitializers); MallocHook::InvokePreMmapHook(start, size, protection, flags, fd, offset); } void InitialPreSbrkHook(ptrdiff_t increment) { perftools_pthread_once(&once, &RemoveInitialHooksAndCallInitializers); MallocHook::InvokePreSbrkHook(increment); } // This function is called at most once by one of the above initial malloc // hooks. It removes all initial hooks and initializes all other clients that // want to get control at the very first memory allocation. The initializers // may assume that the initial malloc hooks have been removed. The initializers // may set up malloc hooks and allocate memory. void RemoveInitialHooksAndCallInitializers() { RAW_CHECK(MallocHook::RemoveNewHook(&InitialNewHook), ""); RAW_CHECK(MallocHook::RemovePreMmapHook(&InitialPreMMapHook), ""); RAW_CHECK(MallocHook::RemovePreSbrkHook(&InitialPreSbrkHook), ""); // HeapLeakChecker is currently the only module that needs to get control on // the first memory allocation, but one can add other modules by following the // same weak/strong function pattern. MallocHook_InitAtFirstAllocation_HeapLeakChecker(); } } // namespace // Weak default initialization function that must go after its use. extern "C" void MallocHook_InitAtFirstAllocation_HeapLeakChecker() { // Do nothing. } namespace base { namespace internal { // This lock is shared between all implementations of HookList::Add & Remove. // The potential for contention is very small. This needs to be a SpinLock and // not a Mutex since it's possible for Mutex locking to allocate memory (e.g., // per-thread allocation in debug builds), which could cause infinite recursion. static SpinLock hooklist_spinlock(base::LINKER_INITIALIZED); template <typename T> bool HookList<T>::Add(T value_as_t) { AtomicWord value = bit_cast<AtomicWord>(value_as_t); if (value == 0) { return false; } SpinLockHolder l(&hooklist_spinlock); // Find the first slot in data that is 0. int index = 0; while ((index < kHookListMaxValues) && (base::subtle::NoBarrier_Load(&priv_data[index]) != 0)) { ++index; } if (index == kHookListMaxValues) { return false; } AtomicWord prev_num_hooks = base::subtle::Acquire_Load(&priv_end); base::subtle::NoBarrier_Store(&priv_data[index], value); if (prev_num_hooks <= index) { base::subtle::NoBarrier_Store(&priv_end, index + 1); } return true; } template <typename T> void HookList<T>::FixupPrivEndLocked() { AtomicWord hooks_end = base::subtle::NoBarrier_Load(&priv_end); while ((hooks_end > 0) && (base::subtle::NoBarrier_Load(&priv_data[hooks_end - 1]) == 0)) { --hooks_end; } base::subtle::NoBarrier_Store(&priv_end, hooks_end); } template <typename T> bool HookList<T>::Remove(T value_as_t) { if (value_as_t == 0) { return false; } SpinLockHolder l(&hooklist_spinlock); AtomicWord hooks_end = base::subtle::NoBarrier_Load(&priv_end); int index = 0; while (index < hooks_end && value_as_t != bit_cast<T>( base::subtle::NoBarrier_Load(&priv_data[index]))) { ++index; } if (index == hooks_end) { return false; } base::subtle::NoBarrier_Store(&priv_data[index], 0); FixupPrivEndLocked(); return true; } template <typename T> int HookList<T>::Traverse(T* output_array, int n) const { AtomicWord hooks_end = base::subtle::Acquire_Load(&priv_end); int actual_hooks_end = 0; for (int i = 0; i < hooks_end && n > 0; ++i) { AtomicWord data = base::subtle::Acquire_Load(&priv_data[i]); if (data != 0) { *output_array++ = bit_cast<T>(data); ++actual_hooks_end; --n; } } return actual_hooks_end; } template <typename T> T HookList<T>::ExchangeSingular(T value_as_t) { AtomicWord value = bit_cast<AtomicWord>(value_as_t); AtomicWord old_value; SpinLockHolder l(&hooklist_spinlock); old_value = base::subtle::NoBarrier_Load(&priv_data[kHookListSingularIdx]); base::subtle::NoBarrier_Store(&priv_data[kHookListSingularIdx], value); if (value != 0) { base::subtle::NoBarrier_Store(&priv_end, kHookListSingularIdx + 1); } else { FixupPrivEndLocked(); } return bit_cast<T>(old_value); } // Initialize a HookList (optionally with the given initial_value in index 0). #define INIT_HOOK_LIST { 0 } #define INIT_HOOK_LIST_WITH_VALUE(initial_value) \ { 1, { reinterpret_cast<AtomicWord>(initial_value) } } // Explicit instantiation for malloc_hook_test.cc. This ensures all the methods // are instantiated. template struct HookList<MallocHook::NewHook>; HookList<MallocHook::NewHook> new_hooks_ = INIT_HOOK_LIST_WITH_VALUE(&InitialNewHook); HookList<MallocHook::DeleteHook> delete_hooks_ = INIT_HOOK_LIST; HookList<MallocHook::PreMmapHook> premmap_hooks_ = INIT_HOOK_LIST_WITH_VALUE(&InitialPreMMapHook); HookList<MallocHook::MmapHook> mmap_hooks_ = INIT_HOOK_LIST; HookList<MallocHook::MunmapHook> munmap_hooks_ = INIT_HOOK_LIST; HookList<MallocHook::MremapHook> mremap_hooks_ = INIT_HOOK_LIST; HookList<MallocHook::PreSbrkHook> presbrk_hooks_ = INIT_HOOK_LIST_WITH_VALUE(InitialPreSbrkHook); HookList<MallocHook::SbrkHook> sbrk_hooks_ = INIT_HOOK_LIST; // These lists contain either 0 or 1 hooks. HookList<MallocHook::MmapReplacement> mmap_replacement_ = { 0 }; HookList<MallocHook::MunmapReplacement> munmap_replacement_ = { 0 }; #undef INIT_HOOK_LIST_WITH_VALUE #undef INIT_HOOK_LIST } } // namespace base::internal using base::internal::kHookListMaxValues; using base::internal::new_hooks_; using base::internal::delete_hooks_; using base::internal::premmap_hooks_; using base::internal::mmap_hooks_; using base::internal::mmap_replacement_; using base::internal::munmap_hooks_; using base::internal::munmap_replacement_; using base::internal::mremap_hooks_; using base::internal::presbrk_hooks_; using base::internal::sbrk_hooks_; // These are available as C bindings as well as C++, hence their // definition outside the MallocHook class. extern "C" int MallocHook_AddNewHook(MallocHook_NewHook hook) { RAW_VLOG(10, "AddNewHook(%p)", hook); return new_hooks_.Add(hook); } extern "C" int MallocHook_RemoveNewHook(MallocHook_NewHook hook) { RAW_VLOG(10, "RemoveNewHook(%p)", hook); return new_hooks_.Remove(hook); } extern "C" int MallocHook_AddDeleteHook(MallocHook_DeleteHook hook) { RAW_VLOG(10, "AddDeleteHook(%p)", hook); return delete_hooks_.Add(hook); } extern "C" int MallocHook_RemoveDeleteHook(MallocHook_DeleteHook hook) { RAW_VLOG(10, "RemoveDeleteHook(%p)", hook); return delete_hooks_.Remove(hook); } extern "C" int MallocHook_AddPreMmapHook(MallocHook_PreMmapHook hook) { RAW_VLOG(10, "AddPreMmapHook(%p)", hook); return premmap_hooks_.Add(hook); } extern "C" int MallocHook_RemovePreMmapHook(MallocHook_PreMmapHook hook) { RAW_VLOG(10, "RemovePreMmapHook(%p)", hook); return premmap_hooks_.Remove(hook); } extern "C" int MallocHook_SetMmapReplacement(MallocHook_MmapReplacement hook) { RAW_VLOG(10, "SetMmapReplacement(%p)", hook); // NOTE this is a best effort CHECK. Concurrent sets could succeed since // this test is outside of the Add spin lock. RAW_CHECK(mmap_replacement_.empty(), "Only one MMapReplacement is allowed."); return mmap_replacement_.Add(hook); } extern "C" int MallocHook_RemoveMmapReplacement(MallocHook_MmapReplacement hook) { RAW_VLOG(10, "RemoveMmapReplacement(%p)", hook); return mmap_replacement_.Remove(hook); } extern "C" int MallocHook_AddMmapHook(MallocHook_MmapHook hook) { RAW_VLOG(10, "AddMmapHook(%p)", hook); return mmap_hooks_.Add(hook); } extern "C" int MallocHook_RemoveMmapHook(MallocHook_MmapHook hook) { RAW_VLOG(10, "RemoveMmapHook(%p)", hook); return mmap_hooks_.Remove(hook); } extern "C" int MallocHook_AddMunmapHook(MallocHook_MunmapHook hook) { RAW_VLOG(10, "AddMunmapHook(%p)", hook); return munmap_hooks_.Add(hook); } extern "C" int MallocHook_RemoveMunmapHook(MallocHook_MunmapHook hook) { RAW_VLOG(10, "RemoveMunmapHook(%p)", hook); return munmap_hooks_.Remove(hook); } extern "C" int MallocHook_SetMunmapReplacement(MallocHook_MunmapReplacement hook) { RAW_VLOG(10, "SetMunmapReplacement(%p)", hook); // NOTE this is a best effort CHECK. Concurrent sets could succeed since // this test is outside of the Add spin lock. RAW_CHECK(munmap_replacement_.empty(), "Only one MunmapReplacement is allowed."); return munmap_replacement_.Add(hook); } extern "C" int MallocHook_RemoveMunmapReplacement(MallocHook_MunmapReplacement hook) { RAW_VLOG(10, "RemoveMunmapReplacement(%p)", hook); return munmap_replacement_.Remove(hook); } extern "C" int MallocHook_AddMremapHook(MallocHook_MremapHook hook) { RAW_VLOG(10, "AddMremapHook(%p)", hook); return mremap_hooks_.Add(hook); } extern "C" int MallocHook_RemoveMremapHook(MallocHook_MremapHook hook) { RAW_VLOG(10, "RemoveMremapHook(%p)", hook); return mremap_hooks_.Remove(hook); } extern "C" int MallocHook_AddPreSbrkHook(MallocHook_PreSbrkHook hook) { RAW_VLOG(10, "AddPreSbrkHook(%p)", hook); return presbrk_hooks_.Add(hook); } extern "C" int MallocHook_RemovePreSbrkHook(MallocHook_PreSbrkHook hook) { RAW_VLOG(10, "RemovePreSbrkHook(%p)", hook); return presbrk_hooks_.Remove(hook); } extern "C" int MallocHook_AddSbrkHook(MallocHook_SbrkHook hook) { RAW_VLOG(10, "AddSbrkHook(%p)", hook); return sbrk_hooks_.Add(hook); } extern "C" int MallocHook_RemoveSbrkHook(MallocHook_SbrkHook hook) { RAW_VLOG(10, "RemoveSbrkHook(%p)", hook); return sbrk_hooks_.Remove(hook); } // The code below is DEPRECATED. extern "C" MallocHook_NewHook MallocHook_SetNewHook(MallocHook_NewHook hook) { RAW_VLOG(10, "SetNewHook(%p)", hook); return new_hooks_.ExchangeSingular(hook); } extern "C" MallocHook_DeleteHook MallocHook_SetDeleteHook(MallocHook_DeleteHook hook) { RAW_VLOG(10, "SetDeleteHook(%p)", hook); return delete_hooks_.ExchangeSingular(hook); } extern "C" MallocHook_PreMmapHook MallocHook_SetPreMmapHook(MallocHook_PreMmapHook hook) { RAW_VLOG(10, "SetPreMmapHook(%p)", hook); return premmap_hooks_.ExchangeSingular(hook); } extern "C" MallocHook_MmapHook MallocHook_SetMmapHook(MallocHook_MmapHook hook) { RAW_VLOG(10, "SetMmapHook(%p)", hook); return mmap_hooks_.ExchangeSingular(hook); } extern "C" MallocHook_MunmapHook MallocHook_SetMunmapHook(MallocHook_MunmapHook hook) { RAW_VLOG(10, "SetMunmapHook(%p)", hook); return munmap_hooks_.ExchangeSingular(hook); } extern "C" MallocHook_MremapHook MallocHook_SetMremapHook(MallocHook_MremapHook hook) { RAW_VLOG(10, "SetMremapHook(%p)", hook); return mremap_hooks_.ExchangeSingular(hook); } extern "C" MallocHook_PreSbrkHook MallocHook_SetPreSbrkHook(MallocHook_PreSbrkHook hook) { RAW_VLOG(10, "SetPreSbrkHook(%p)", hook); return presbrk_hooks_.ExchangeSingular(hook); } extern "C" MallocHook_SbrkHook MallocHook_SetSbrkHook(MallocHook_SbrkHook hook) { RAW_VLOG(10, "SetSbrkHook(%p)", hook); return sbrk_hooks_.ExchangeSingular(hook); } // End of DEPRECATED code section. // Note: embedding the function calls inside the traversal of HookList would be // very confusing, as it is legal for a hook to remove itself and add other // hooks. Doing traversal first, and then calling the hooks ensures we only // call the hooks registered at the start. #define INVOKE_HOOKS(HookType, hook_list, args) do { \ HookType hooks[kHookListMaxValues]; \ int num_hooks = hook_list.Traverse(hooks, kHookListMaxValues); \ for (int i = 0; i < num_hooks; ++i) { \ (*hooks[i])args; \ } \ } while (0) // There should only be one replacement. Return the result of the first // one, or false if there is none. #define INVOKE_REPLACEMENT(HookType, hook_list, args) do { \ HookType hooks[kHookListMaxValues]; \ int num_hooks = hook_list.Traverse(hooks, kHookListMaxValues); \ return (num_hooks > 0 && (*hooks[0])args); \ } while (0) void MallocHook::InvokeNewHookSlow(const void* p, size_t s) { if (tcmalloc::IsEmergencyPtr(p)) { return; } INVOKE_HOOKS(NewHook, new_hooks_, (p, s)); } void MallocHook::InvokeDeleteHookSlow(const void* p) { if (tcmalloc::IsEmergencyPtr(p)) { return; } INVOKE_HOOKS(DeleteHook, delete_hooks_, (p)); } void MallocHook::InvokePreMmapHookSlow(const void* start, size_t size, int protection, int flags, int fd, off_t offset) { INVOKE_HOOKS(PreMmapHook, premmap_hooks_, (start, size, protection, flags, fd, offset)); } void MallocHook::InvokeMmapHookSlow(const void* result, const void* start, size_t size, int protection, int flags, int fd, off_t offset) { INVOKE_HOOKS(MmapHook, mmap_hooks_, (result, start, size, protection, flags, fd, offset)); } bool MallocHook::InvokeMmapReplacementSlow(const void* start, size_t size, int protection, int flags, int fd, off_t offset, void** result) { INVOKE_REPLACEMENT(MmapReplacement, mmap_replacement_, (start, size, protection, flags, fd, offset, result)); } void MallocHook::InvokeMunmapHookSlow(const void* p, size_t s) { INVOKE_HOOKS(MunmapHook, munmap_hooks_, (p, s)); } bool MallocHook::InvokeMunmapReplacementSlow(const void* p, size_t s, int* result) { INVOKE_REPLACEMENT(MunmapReplacement, munmap_replacement_, (p, s, result)); } void MallocHook::InvokeMremapHookSlow(const void* result, const void* old_addr, size_t old_size, size_t new_size, int flags, const void* new_addr) { INVOKE_HOOKS(MremapHook, mremap_hooks_, (result, old_addr, old_size, new_size, flags, new_addr)); } void MallocHook::InvokePreSbrkHookSlow(ptrdiff_t increment) { INVOKE_HOOKS(PreSbrkHook, presbrk_hooks_, (increment)); } void MallocHook::InvokeSbrkHookSlow(const void* result, ptrdiff_t increment) { INVOKE_HOOKS(SbrkHook, sbrk_hooks_, (result, increment)); } #undef INVOKE_HOOKS #ifndef NO_TCMALLOC_SAMPLES DEFINE_ATTRIBUTE_SECTION_VARS(google_malloc); DECLARE_ATTRIBUTE_SECTION_VARS(google_malloc); // actual functions are in debugallocation.cc or tcmalloc.cc DEFINE_ATTRIBUTE_SECTION_VARS(malloc_hook); DECLARE_ATTRIBUTE_SECTION_VARS(malloc_hook); // actual functions are in this file, malloc_hook.cc, and low_level_alloc.cc #define ADDR_IN_ATTRIBUTE_SECTION(addr, name) \ (reinterpret_cast<uintptr_t>(ATTRIBUTE_SECTION_START(name)) <= \ reinterpret_cast<uintptr_t>(addr) && \ reinterpret_cast<uintptr_t>(addr) < \ reinterpret_cast<uintptr_t>(ATTRIBUTE_SECTION_STOP(name))) // Return true iff 'caller' is a return address within a function // that calls one of our hooks via MallocHook:Invoke*. // A helper for GetCallerStackTrace. static inline bool InHookCaller(const void* caller) { return ADDR_IN_ATTRIBUTE_SECTION(caller, google_malloc) || ADDR_IN_ATTRIBUTE_SECTION(caller, malloc_hook); // We can use one section for everything except tcmalloc_or_debug // due to its special linkage mode, which prevents merging of the sections. } #undef ADDR_IN_ATTRIBUTE_SECTION static bool checked_sections = false; static inline void CheckInHookCaller() { if (!checked_sections) { INIT_ATTRIBUTE_SECTION_VARS(google_malloc); if (ATTRIBUTE_SECTION_START(google_malloc) == ATTRIBUTE_SECTION_STOP(google_malloc)) { RAW_LOG(ERROR, "google_malloc section is missing, " "thus InHookCaller is broken!"); } INIT_ATTRIBUTE_SECTION_VARS(malloc_hook); if (ATTRIBUTE_SECTION_START(malloc_hook) == ATTRIBUTE_SECTION_STOP(malloc_hook)) { RAW_LOG(ERROR, "malloc_hook section is missing, " "thus InHookCaller is broken!"); } checked_sections = true; } } #endif // !NO_TCMALLOC_SAMPLES // We can improve behavior/compactness of this function // if we pass a generic test function (with a generic arg) // into the implementations for GetStackTrace instead of the skip_count. extern "C" int MallocHook_GetCallerStackTrace(void** result, int max_depth, int skip_count) { #if defined(NO_TCMALLOC_SAMPLES) return 0; #elif !defined(HAVE_ATTRIBUTE_SECTION_START) // Fall back to GetStackTrace and good old but fragile frame skip counts. // Note: this path is inaccurate when a hook is not called directly by an // allocation function but is daisy-chained through another hook, // search for MallocHook::(Get|Set|Invoke)* to find such cases. return GetStackTrace(result, max_depth, skip_count + int(DEBUG_MODE)); // due to -foptimize-sibling-calls in opt mode // there's no need for extra frame skip here then #else CheckInHookCaller(); // MallocHook caller determination via InHookCaller works, use it: static const int kMaxSkip = 32 + 6 + 3; // Constant tuned to do just one GetStackTrace call below in practice // and not get many frames that we don't actually need: // currently max passsed max_depth is 32, // max passed/needed skip_count is 6 // and 3 is to account for some hook daisy chaining. static const int kStackSize = kMaxSkip + 1; void* stack[kStackSize]; int depth = GetStackTrace(stack, kStackSize, 1); // skip this function frame if (depth == 0) // silenty propagate cases when GetStackTrace does not work return 0; for (int i = 0; i < depth; ++i) { // stack[0] is our immediate caller if (InHookCaller(stack[i])) { // fast-path to slow-path calls may be implemented by compiler // as non-tail calls. Causing two functions on stack trace to be // inside google_malloc. In such case we're skipping to // outermost such frame since this is where malloc stack frames // really start. while (i + 1 < depth && InHookCaller(stack[i+1])) { i++; } RAW_VLOG(10, "Found hooked allocator at %d: %p <- %p", i, stack[i], stack[i+1]); i += 1; // skip hook caller frame depth -= i; // correct depth if (depth > max_depth) depth = max_depth; copy(stack + i, stack + i + depth, result); if (depth < max_depth && depth + i == kStackSize) { // get frames for the missing depth depth += GetStackTrace(result + depth, max_depth - depth, 1 + kStackSize); } return depth; } } RAW_LOG(WARNING, "Hooked allocator frame not found, returning empty trace"); // If this happens try increasing kMaxSkip // or else something must be wrong with InHookCaller, // e.g. for every section used in InHookCaller // all functions in that section must be inside the same library. return 0; #endif } // On systems where we know how, we override mmap/munmap/mremap/sbrk // to provide support for calling the related hooks (in addition, // of course, to doing what these functions normally do). #if defined(__linux) # include "malloc_hook_mmap_linux.h" #elif defined(__FreeBSD__) # include "malloc_hook_mmap_freebsd.h" #else /*static*/void* MallocHook::UnhookedMMap(void *start, size_t length, int prot, int flags, int fd, off_t offset) { void* result; if (!MallocHook::InvokeMmapReplacement( start, length, prot, flags, fd, offset, &result)) { result = mmap(start, length, prot, flags, fd, offset); } return result; } /*static*/int MallocHook::UnhookedMUnmap(void *start, size_t length) { int result; if (!MallocHook::InvokeMunmapReplacement(start, length, &result)) { result = munmap(start, length); } return result; } #endif
Unknown
3D
mcellteam/mcell
libs/gperftools/src/tcmalloc_guard.h
.h
2,195
50
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein // // We expose the TCMallocGuard class -- which initializes the tcmalloc // allocator -- so classes that need to be sure tcmalloc is loaded // before they do stuff -- notably heap-profiler -- can. To use this // create a static TCMallocGuard instance at the top of a file where // you need tcmalloc to be initialized before global constructors run. #ifndef TCMALLOC_TCMALLOC_GUARD_H_ #define TCMALLOC_TCMALLOC_GUARD_H_ class TCMallocGuard { public: TCMallocGuard(); ~TCMallocGuard(); }; #endif // TCMALLOC_TCMALLOC_GUARD_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/central_freelist.cc
.cc
12,647
388
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #include "config.h" #include <algorithm> #include "central_freelist.h" #include "internal_logging.h" // for ASSERT, MESSAGE #include "linked_list.h" // for SLL_Next, SLL_Push, etc #include "page_heap.h" // for PageHeap #include "static_vars.h" // for Static using std::min; using std::max; namespace tcmalloc { void CentralFreeList::Init(size_t cl) { size_class_ = cl; tcmalloc::DLL_Init(&empty_); tcmalloc::DLL_Init(&nonempty_); num_spans_ = 0; counter_ = 0; max_cache_size_ = kMaxNumTransferEntries; #ifdef TCMALLOC_SMALL_BUT_SLOW // Disable the transfer cache for the small footprint case. cache_size_ = 0; #else cache_size_ = 16; #endif if (cl > 0) { // Limit the maximum size of the cache based on the size class. If this // is not done, large size class objects will consume a lot of memory if // they just sit in the transfer cache. int32_t bytes = Static::sizemap()->ByteSizeForClass(cl); int32_t objs_to_move = Static::sizemap()->num_objects_to_move(cl); ASSERT(objs_to_move > 0 && bytes > 0); // Limit each size class cache to at most 1MB of objects or one entry, // whichever is greater. Total transfer cache memory used across all // size classes then can't be greater than approximately // 1MB * kMaxNumTransferEntries. // min and max are in parens to avoid macro-expansion on windows. max_cache_size_ = (min)(max_cache_size_, (max)(1, (1024 * 1024) / (bytes * objs_to_move))); cache_size_ = (min)(cache_size_, max_cache_size_); } used_slots_ = 0; ASSERT(cache_size_ <= max_cache_size_); } void CentralFreeList::ReleaseListToSpans(void* start) { while (start) { void *next = SLL_Next(start); ReleaseToSpans(start); start = next; } } // MapObjectToSpan should logically be part of ReleaseToSpans. But // this triggers an optimization bug in gcc 4.5.0. Moving to a // separate function, and making sure that function isn't inlined, // seems to fix the problem. It also should be fixed for gcc 4.5.1. static #if __GNUC__ == 4 && __GNUC_MINOR__ == 5 && __GNUC_PATCHLEVEL__ == 0 __attribute__ ((noinline)) #endif Span* MapObjectToSpan(void* object) { const PageID p = reinterpret_cast<uintptr_t>(object) >> kPageShift; Span* span = Static::pageheap()->GetDescriptor(p); return span; } void CentralFreeList::ReleaseToSpans(void* object) { Span* span = MapObjectToSpan(object); ASSERT(span != NULL); ASSERT(span->refcount > 0); // If span is empty, move it to non-empty list if (span->objects == NULL) { tcmalloc::DLL_Remove(span); tcmalloc::DLL_Prepend(&nonempty_, span); Event(span, 'N', 0); } // The following check is expensive, so it is disabled by default if (false) { // Check that object does not occur in list int got = 0; for (void* p = span->objects; p != NULL; p = *((void**) p)) { ASSERT(p != object); got++; } ASSERT(got + span->refcount == (span->length<<kPageShift) / Static::sizemap()->ByteSizeForClass(span->sizeclass)); } counter_++; span->refcount--; if (span->refcount == 0) { Event(span, '#', 0); counter_ -= ((span->length<<kPageShift) / Static::sizemap()->ByteSizeForClass(span->sizeclass)); tcmalloc::DLL_Remove(span); --num_spans_; // Release central list lock while operating on pageheap lock_.Unlock(); { SpinLockHolder h(Static::pageheap_lock()); Static::pageheap()->Delete(span); } lock_.Lock(); } else { *(reinterpret_cast<void**>(object)) = span->objects; span->objects = object; } } bool CentralFreeList::EvictRandomSizeClass( int locked_size_class, bool force) { static int race_counter = 0; int t = race_counter++; // Updated without a lock, but who cares. if (t >= Static::num_size_classes()) { while (t >= Static::num_size_classes()) { t -= Static::num_size_classes(); } race_counter = t; } ASSERT(t >= 0); ASSERT(t < Static::num_size_classes()); if (t == locked_size_class) return false; return Static::central_cache()[t].ShrinkCache(locked_size_class, force); } bool CentralFreeList::MakeCacheSpace() { // Is there room in the cache? if (used_slots_ < cache_size_) return true; // Check if we can expand this cache? if (cache_size_ == max_cache_size_) return false; // Ok, we'll try to grab an entry from some other size class. if (EvictRandomSizeClass(size_class_, false) || EvictRandomSizeClass(size_class_, true)) { // Succeeded in evicting, we're going to make our cache larger. // However, we may have dropped and re-acquired the lock in // EvictRandomSizeClass (via ShrinkCache and the LockInverter), so the // cache_size may have changed. Therefore, check and verify that it is // still OK to increase the cache_size. if (cache_size_ < max_cache_size_) { cache_size_++; return true; } } return false; } namespace { class LockInverter { private: SpinLock *held_, *temp_; public: inline explicit LockInverter(SpinLock* held, SpinLock *temp) : held_(held), temp_(temp) { held_->Unlock(); temp_->Lock(); } inline ~LockInverter() { temp_->Unlock(); held_->Lock(); } }; } // This function is marked as NO_THREAD_SAFETY_ANALYSIS because it uses // LockInverter to release one lock and acquire another in scoped-lock // style, which our current annotation/analysis does not support. bool CentralFreeList::ShrinkCache(int locked_size_class, bool force) NO_THREAD_SAFETY_ANALYSIS { // Start with a quick check without taking a lock. if (cache_size_ == 0) return false; // We don't evict from a full cache unless we are 'forcing'. if (force == false && used_slots_ == cache_size_) return false; // Grab lock, but first release the other lock held by this thread. We use // the lock inverter to ensure that we never hold two size class locks // concurrently. That can create a deadlock because there is no well // defined nesting order. LockInverter li(&Static::central_cache()[locked_size_class].lock_, &lock_); ASSERT(used_slots_ <= cache_size_); ASSERT(0 <= cache_size_); if (cache_size_ == 0) return false; if (used_slots_ == cache_size_) { if (force == false) return false; // ReleaseListToSpans releases the lock, so we have to make all the // updates to the central list before calling it. cache_size_--; used_slots_--; ReleaseListToSpans(tc_slots_[used_slots_].head); return true; } cache_size_--; return true; } void CentralFreeList::InsertRange(void *start, void *end, int N) { SpinLockHolder h(&lock_); if (N == Static::sizemap()->num_objects_to_move(size_class_) && MakeCacheSpace()) { int slot = used_slots_++; ASSERT(slot >=0); ASSERT(slot < max_cache_size_); TCEntry *entry = &tc_slots_[slot]; entry->head = start; entry->tail = end; return; } ReleaseListToSpans(start); } int CentralFreeList::RemoveRange(void **start, void **end, int N) { ASSERT(N > 0); lock_.Lock(); if (N == Static::sizemap()->num_objects_to_move(size_class_) && used_slots_ > 0) { int slot = --used_slots_; ASSERT(slot >= 0); TCEntry *entry = &tc_slots_[slot]; *start = entry->head; *end = entry->tail; lock_.Unlock(); return N; } int result = 0; *start = NULL; *end = NULL; // TODO: Prefetch multiple TCEntries? result = FetchFromOneSpansSafe(N, start, end); if (result != 0) { while (result < N) { int n; void* head = NULL; void* tail = NULL; n = FetchFromOneSpans(N - result, &head, &tail); if (!n) break; result += n; SLL_PushRange(start, head, tail); } } lock_.Unlock(); return result; } int CentralFreeList::FetchFromOneSpansSafe(int N, void **start, void **end) { int result = FetchFromOneSpans(N, start, end); if (!result) { Populate(); result = FetchFromOneSpans(N, start, end); } return result; } int CentralFreeList::FetchFromOneSpans(int N, void **start, void **end) { if (tcmalloc::DLL_IsEmpty(&nonempty_)) return 0; Span* span = nonempty_.next; ASSERT(span->objects != NULL); int result = 0; void *prev, *curr; curr = span->objects; do { prev = curr; curr = *(reinterpret_cast<void**>(curr)); } while (++result < N && curr != NULL); if (curr == NULL) { // Move to empty list tcmalloc::DLL_Remove(span); tcmalloc::DLL_Prepend(&empty_, span); Event(span, 'E', 0); } *start = span->objects; *end = prev; span->objects = curr; SLL_SetNext(*end, NULL); span->refcount += result; counter_ -= result; return result; } // Fetch memory from the system and add to the central cache freelist. void CentralFreeList::Populate() { // Release central list lock while operating on pageheap lock_.Unlock(); const size_t npages = Static::sizemap()->class_to_pages(size_class_); Span* span; { SpinLockHolder h(Static::pageheap_lock()); span = Static::pageheap()->New(npages); if (span) Static::pageheap()->RegisterSizeClass(span, size_class_); } if (span == NULL) { Log(kLog, __FILE__, __LINE__, "tcmalloc: allocation failed", npages << kPageShift); lock_.Lock(); return; } ASSERT(span->length == npages); // Cache sizeclass info eagerly. Locking is not necessary. // (Instead of being eager, we could just replace any stale info // about this span, but that seems to be no better in practice.) for (int i = 0; i < npages; i++) { Static::pageheap()->SetCachedSizeClass(span->start + i, size_class_); } // Split the block into pieces and add to the free-list // TODO: coloring of objects to avoid cache conflicts? void** tail = &span->objects; char* ptr = reinterpret_cast<char*>(span->start << kPageShift); char* limit = ptr + (npages << kPageShift); const size_t size = Static::sizemap()->ByteSizeForClass(size_class_); int num = 0; while (ptr + size <= limit) { *tail = ptr; tail = reinterpret_cast<void**>(ptr); ptr += size; num++; } ASSERT(ptr <= limit); *tail = NULL; span->refcount = 0; // No sub-object in use yet // Add span to list of non-empty spans lock_.Lock(); tcmalloc::DLL_Prepend(&nonempty_, span); ++num_spans_; counter_ += num; } int CentralFreeList::tc_length() { SpinLockHolder h(&lock_); return used_slots_ * Static::sizemap()->num_objects_to_move(size_class_); } size_t CentralFreeList::OverheadBytes() { SpinLockHolder h(&lock_); if (size_class_ == 0) { // 0 holds the 0-sized allocations return 0; } const size_t pages_per_span = Static::sizemap()->class_to_pages(size_class_); const size_t object_size = Static::sizemap()->class_to_size(size_class_); ASSERT(object_size > 0); const size_t overhead_per_span = (pages_per_span * kPageSize) % object_size; return num_spans_ * overhead_per_span; } } // namespace tcmalloc
Unknown
3D
mcellteam/mcell
libs/gperftools/src/heap-checker.cc
.cc
100,182
2,389
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Maxim Lifantsev // #include "config.h" #include <fcntl.h> // for O_RDONLY (we use syscall to do actual reads) #include <string.h> #include <errno.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_MMAP #include <sys/mman.h> #endif #ifdef HAVE_PTHREAD #include <pthread.h> #endif #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <assert.h> #if defined(HAVE_LINUX_PTRACE_H) #include <linux/ptrace.h> #endif #ifdef HAVE_SYS_SYSCALL_H #include <sys/syscall.h> #endif #if defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW32__) #include <wtypes.h> #include <winbase.h> #undef ERROR // windows defines these as macros, which can cause trouble #undef max #undef min #endif #include <string> #include <vector> #include <map> #include <set> #include <algorithm> #include <functional> #include <gperftools/heap-checker.h> #include "base/basictypes.h" #include "base/googleinit.h" #include "base/logging.h" #include <gperftools/stacktrace.h> #include "base/commandlineflags.h" #include "base/elfcore.h" // for i386_regs #include "base/thread_lister.h" #include "heap-profile-table.h" #include "base/low_level_alloc.h" #include "malloc_hook-inl.h" #include <gperftools/malloc_hook.h> #include <gperftools/malloc_extension.h> #include "maybe_threads.h" #include "memory_region_map.h" #include "base/spinlock.h" #include "base/sysinfo.h" #include "base/stl_allocator.h" using std::string; using std::basic_string; using std::pair; using std::map; using std::set; using std::vector; using std::swap; using std::make_pair; using std::min; using std::max; using std::less; using std::char_traits; // If current process is being ptrace()d, 'TracerPid' in /proc/self/status // will be non-zero. static bool IsDebuggerAttached(void) { // only works under linux, probably char buf[256]; // TracerPid comes relatively earlier in status output int fd = open("/proc/self/status", O_RDONLY); if (fd == -1) { return false; // Can't tell for sure. } const int len = read(fd, buf, sizeof(buf)); bool rc = false; if (len > 0) { const char *const kTracerPid = "TracerPid:\t"; buf[len - 1] = '\0'; const char *p = strstr(buf, kTracerPid); if (p != NULL) { rc = (strncmp(p + strlen(kTracerPid), "0\n", 2) != 0); } } close(fd); return rc; } // This is the default if you don't link in -lprofiler extern "C" { ATTRIBUTE_WEAK PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads(); int ProfilingIsEnabledForAllThreads() { return false; } } //---------------------------------------------------------------------- // Flags that control heap-checking //---------------------------------------------------------------------- DEFINE_string(heap_check, EnvToString("HEAPCHECK", ""), "The heap leak checking to be done over the whole executable: " "\"minimal\", \"normal\", \"strict\", " "\"draconian\", \"as-is\", and \"local\" " " or the empty string are the supported choices. " "(See HeapLeakChecker_InternalInitStart for details.)"); DEFINE_bool(heap_check_report, true, "Obsolete"); DEFINE_bool(heap_check_before_constructors, true, "deprecated; pretty much always true now"); DEFINE_bool(heap_check_after_destructors, EnvToBool("HEAP_CHECK_AFTER_DESTRUCTORS", false), "If overall heap check is to end after global destructors " "or right after all REGISTER_HEAPCHECK_CLEANUP's"); DEFINE_bool(heap_check_strict_check, true, "Obsolete"); DEFINE_bool(heap_check_ignore_global_live, EnvToBool("HEAP_CHECK_IGNORE_GLOBAL_LIVE", true), "If overall heap check is to ignore heap objects reachable " "from the global data"); DEFINE_bool(heap_check_identify_leaks, EnvToBool("HEAP_CHECK_IDENTIFY_LEAKS", false), "If heap check should generate the addresses of the leaked " "objects in the memory leak profiles. This may be useful " "in tracking down leaks where only a small fraction of " "objects allocated at the same stack trace are leaked."); DEFINE_bool(heap_check_ignore_thread_live, EnvToBool("HEAP_CHECK_IGNORE_THREAD_LIVE", true), "If set to true, objects reachable from thread stacks " "and registers are not reported as leaks"); DEFINE_bool(heap_check_test_pointer_alignment, EnvToBool("HEAP_CHECK_TEST_POINTER_ALIGNMENT", false), "Set to true to check if the found leak can be due to " "use of unaligned pointers"); // Alignment at which all pointers in memory are supposed to be located; // use 1 if any alignment is ok. // heap_check_test_pointer_alignment flag guides if we try the value of 1. // The larger it can be, the lesser is the chance of missing real leaks. static const size_t kPointerSourceAlignment = sizeof(void*); DEFINE_int32(heap_check_pointer_source_alignment, EnvToInt("HEAP_CHECK_POINTER_SOURCE_ALIGNMENT", kPointerSourceAlignment), "Alignment at which all pointers in memory are supposed to be " "located. Use 1 if any alignment is ok."); // A reasonable default to handle pointers inside of typical class objects: // Too low and we won't be able to traverse pointers to normally-used // nested objects and base parts of multiple-inherited objects. // Too high and it will both slow down leak checking (FindInsideAlloc // in HaveOnHeapLocked will get slower when there are large on-heap objects) // and make it probabilistically more likely to miss leaks // of large-sized objects. static const int64 kHeapCheckMaxPointerOffset = 1024; DEFINE_int64(heap_check_max_pointer_offset, EnvToInt("HEAP_CHECK_MAX_POINTER_OFFSET", kHeapCheckMaxPointerOffset), "Largest pointer offset for which we traverse " "pointers going inside of heap allocated objects. " "Set to -1 to use the actual largest heap object size."); DEFINE_bool(heap_check_run_under_gdb, EnvToBool("HEAP_CHECK_RUN_UNDER_GDB", false), "If false, turns off heap-checking library when running under gdb " "(normally, set to 'true' only when debugging the heap-checker)"); DEFINE_int32(heap_check_delay_seconds, 0, "Number of seconds to delay on-exit heap checking." " If you set this flag," " you may also want to set exit_timeout_seconds in order to" " avoid exit timeouts.\n" "NOTE: This flag is to be used only to help diagnose issues" " where it is suspected that the heap checker is reporting" " false leaks that will disappear if the heap checker delays" " its checks. Report any such issues to the heap-checker" " maintainer(s)."); //---------------------------------------------------------------------- DEFINE_string(heap_profile_pprof, EnvToString("PPROF_PATH", "pprof"), "OBSOLETE; not used"); DEFINE_string(heap_check_dump_directory, EnvToString("HEAP_CHECK_DUMP_DIRECTORY", "/tmp"), "Directory to put heap-checker leak dump information"); //---------------------------------------------------------------------- // HeapLeakChecker global data //---------------------------------------------------------------------- // Global lock for all the global data of this module. static SpinLock heap_checker_lock(SpinLock::LINKER_INITIALIZED); //---------------------------------------------------------------------- // Heap profile prefix for leak checking profiles. // Gets assigned once when leak checking is turned on, then never modified. static const string* profile_name_prefix = NULL; // Whole-program heap leak checker. // Gets assigned once when leak checking is turned on, // then main_heap_checker is never deleted. static HeapLeakChecker* main_heap_checker = NULL; // Whether we will use main_heap_checker to do a check at program exit // automatically. In any case user can ask for more checks on main_heap_checker // via GlobalChecker(). static bool do_main_heap_check = false; // The heap profile we use to collect info about the heap. // This is created in HeapLeakChecker::BeforeConstructorsLocked // together with setting heap_checker_on (below) to true // and registering our new/delete malloc hooks; // similarly all are unset in HeapLeakChecker::TurnItselfOffLocked. static HeapProfileTable* heap_profile = NULL; // If we are doing (or going to do) any kind of heap-checking. static bool heap_checker_on = false; // pid of the process that does whole-program heap leak checking static pid_t heap_checker_pid = 0; // If we did heap profiling during global constructors execution static bool constructor_heap_profiling = false; // RAW_VLOG level we dump key INFO messages at. If you want to turn // off these messages, set the environment variable PERFTOOLS_VERBOSE=-1. static const int heap_checker_info_level = 0; //---------------------------------------------------------------------- // HeapLeakChecker's own memory allocator that is // independent of the normal program allocator. //---------------------------------------------------------------------- // Wrapper of LowLevelAlloc for STL_Allocator and direct use. // We always access this class under held heap_checker_lock, // this allows us to in particular protect the period when threads are stopped // at random spots with TCMalloc_ListAllProcessThreads by heap_checker_lock, // w/o worrying about the lock in LowLevelAlloc::Arena. // We rely on the fact that we use an own arena with an own lock here. class HeapLeakChecker::Allocator { public: static void Init() { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); RAW_DCHECK(arena_ == NULL, ""); arena_ = LowLevelAlloc::NewArena(0, LowLevelAlloc::DefaultArena()); } static void Shutdown() { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); if (!LowLevelAlloc::DeleteArena(arena_) || alloc_count_ != 0) { RAW_LOG(FATAL, "Internal heap checker leak of %d objects", alloc_count_); } } static int alloc_count() { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); return alloc_count_; } static void* Allocate(size_t n) { RAW_DCHECK(arena_ && heap_checker_lock.IsHeld(), ""); void* p = LowLevelAlloc::AllocWithArena(n, arena_); if (p) alloc_count_ += 1; return p; } static void Free(void* p) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); if (p) alloc_count_ -= 1; LowLevelAlloc::Free(p); } static void Free(void* p, size_t /* n */) { Free(p); } // destruct, free, and make *p to be NULL template<typename T> static void DeleteAndNull(T** p) { (*p)->~T(); Free(*p); *p = NULL; } template<typename T> static void DeleteAndNullIfNot(T** p) { if (*p != NULL) DeleteAndNull(p); } private: static LowLevelAlloc::Arena* arena_; static int alloc_count_; }; LowLevelAlloc::Arena* HeapLeakChecker::Allocator::arena_ = NULL; int HeapLeakChecker::Allocator::alloc_count_ = 0; //---------------------------------------------------------------------- // HeapLeakChecker live object tracking components //---------------------------------------------------------------------- // Cases of live object placement we distinguish enum ObjectPlacement { MUST_BE_ON_HEAP, // Must point to a live object of the matching size in the // heap_profile map of the heap when we get to it IGNORED_ON_HEAP, // Is a live (ignored) object on heap MAYBE_LIVE, // Is a piece of writable memory from /proc/self/maps IN_GLOBAL_DATA, // Is part of global data region of the executable THREAD_DATA, // Part of a thread stack and a thread descriptor with TLS THREAD_REGISTERS, // Values in registers of some thread }; // Information about an allocated object struct AllocObject { const void* ptr; // the object uintptr_t size; // its size ObjectPlacement place; // where ptr points to AllocObject(const void* p, size_t s, ObjectPlacement l) : ptr(p), size(s), place(l) { } }; // All objects (memory ranges) ignored via HeapLeakChecker::IgnoreObject // Key is the object's address; value is its size. typedef map<uintptr_t, size_t, less<uintptr_t>, STL_Allocator<pair<const uintptr_t, size_t>, HeapLeakChecker::Allocator> > IgnoredObjectsMap; static IgnoredObjectsMap* ignored_objects = NULL; // All objects (memory ranges) that we consider to be the sources of pointers // to live (not leaked) objects. // At different times this holds (what can be reached from) global data regions // and the objects we've been told to ignore. // For any AllocObject::ptr "live_objects" is supposed to contain at most one // record at any time. We maintain this by checking with the heap_profile map // of the heap and removing the live heap objects we've handled from it. // This vector is maintained as a stack and the frontier of reachable // live heap objects in our flood traversal of them. typedef vector<AllocObject, STL_Allocator<AllocObject, HeapLeakChecker::Allocator> > LiveObjectsStack; static LiveObjectsStack* live_objects = NULL; // A special string type that uses my allocator typedef basic_string<char, char_traits<char>, STL_Allocator<char, HeapLeakChecker::Allocator> > HCL_string; // A placeholder to fill-in the starting values for live_objects // for each library so we can keep the library-name association for logging. typedef map<HCL_string, LiveObjectsStack, less<HCL_string>, STL_Allocator<pair<const HCL_string, LiveObjectsStack>, HeapLeakChecker::Allocator> > LibraryLiveObjectsStacks; static LibraryLiveObjectsStacks* library_live_objects = NULL; // Value stored in the map of disabled address ranges; // its key is the end of the address range. // We'll ignore allocations with a return address in a disabled range // if the address occurs at 'max_depth' or less in the stack trace. struct HeapLeakChecker::RangeValue { uintptr_t start_address; // the start of the range int max_depth; // the maximal stack depth to disable at }; typedef map<uintptr_t, HeapLeakChecker::RangeValue, less<uintptr_t>, STL_Allocator<pair<const uintptr_t, HeapLeakChecker::RangeValue>, HeapLeakChecker::Allocator> > DisabledRangeMap; // The disabled program counter address ranges for profile dumping // that are registered with HeapLeakChecker::DisableChecksFromToLocked. static DisabledRangeMap* disabled_ranges = NULL; // Set of stack tops. // These are used to consider live only appropriate chunks of the memory areas // that are used for stacks (and maybe thread-specific data as well) // so that we do not treat pointers from outdated stack frames as live. typedef set<uintptr_t, less<uintptr_t>, STL_Allocator<uintptr_t, HeapLeakChecker::Allocator> > StackTopSet; static StackTopSet* stack_tops = NULL; // A map of ranges of code addresses for the system libraries // that can mmap/mremap/sbrk-allocate memory regions for stacks // and thread-local storage that we want to consider as live global data. // Maps from the end address to the start address. typedef map<uintptr_t, uintptr_t, less<uintptr_t>, STL_Allocator<pair<const uintptr_t, uintptr_t>, HeapLeakChecker::Allocator> > GlobalRegionCallerRangeMap; static GlobalRegionCallerRangeMap* global_region_caller_ranges = NULL; // TODO(maxim): make our big data structs into own modules // Disabler is implemented by keeping track of a per-thread count // of active Disabler objects. Any objects allocated while the // count > 0 are not reported. #ifdef HAVE_TLS static __thread int thread_disable_counter // The "inital exec" model is faster than the default TLS model, at // the cost you can't dlopen this library. But dlopen on heap-checker // doesn't work anyway -- it must run before main -- so this is a good // trade-off. # ifdef HAVE___ATTRIBUTE__ __attribute__ ((tls_model ("initial-exec"))) # endif ; inline int get_thread_disable_counter() { return thread_disable_counter; } inline void set_thread_disable_counter(int value) { thread_disable_counter = value; } #else // #ifdef HAVE_TLS static pthread_key_t thread_disable_counter_key; static int main_thread_counter; // storage for use before main() static bool use_main_thread_counter = true; // TODO(csilvers): this is called from NewHook, in the middle of malloc(). // If perftools_pthread_getspecific calls malloc, that will lead to an // infinite loop. I don't know how to fix that, so I hope it never happens! inline int get_thread_disable_counter() { if (use_main_thread_counter) // means we're running really early return main_thread_counter; void* p = perftools_pthread_getspecific(thread_disable_counter_key); return (intptr_t)p; // kinda evil: store the counter directly in the void* } inline void set_thread_disable_counter(int value) { if (use_main_thread_counter) { // means we're running really early main_thread_counter = value; return; } intptr_t pointer_sized_value = value; // kinda evil: store the counter directly in the void* void* p = (void*)pointer_sized_value; // NOTE: this may call malloc, which will call NewHook which will call // get_thread_disable_counter() which will call pthread_getspecific(). I // don't know if anything bad can happen if we call getspecific() in the // middle of a setspecific() call. It seems to work ok in practice... perftools_pthread_setspecific(thread_disable_counter_key, p); } // The idea here is that this initializer will run pretty late: after // pthreads have been totally set up. At this point we can call // pthreads routines, so we set those up. class InitThreadDisableCounter { public: InitThreadDisableCounter() { perftools_pthread_key_create(&thread_disable_counter_key, NULL); // Set up the main thread's value, which we have a special variable for. void* p = (void*)(intptr_t)main_thread_counter; // store the counter directly perftools_pthread_setspecific(thread_disable_counter_key, p); use_main_thread_counter = false; } }; InitThreadDisableCounter init_thread_disable_counter; #endif // #ifdef HAVE_TLS HeapLeakChecker::Disabler::Disabler() { // It is faster to unconditionally increment the thread-local // counter than to check whether or not heap-checking is on // in a thread-safe manner. int counter = get_thread_disable_counter(); set_thread_disable_counter(counter + 1); RAW_VLOG(10, "Increasing thread disable counter to %d", counter + 1); } HeapLeakChecker::Disabler::~Disabler() { int counter = get_thread_disable_counter(); RAW_DCHECK(counter > 0, ""); if (counter > 0) { set_thread_disable_counter(counter - 1); RAW_VLOG(10, "Decreasing thread disable counter to %d", counter); } else { RAW_VLOG(0, "Thread disable counter underflow : %d", counter); } } //---------------------------------------------------------------------- // The size of the largest heap object allocated so far. static size_t max_heap_object_size = 0; // The possible range of addresses that can point // into one of the elements of heap_objects. static uintptr_t min_heap_address = uintptr_t(-1LL); static uintptr_t max_heap_address = 0; //---------------------------------------------------------------------- // Simple casting helpers for uintptr_t and void*: template<typename T> inline static const void* AsPtr(T addr) { return reinterpret_cast<void*>(addr); } inline static uintptr_t AsInt(const void* ptr) { return reinterpret_cast<uintptr_t>(ptr); } //---------------------------------------------------------------------- // We've seen reports that strstr causes heap-checker crashes in some // libc's (?): // http://code.google.com/p/gperftools/issues/detail?id=263 // It's simple enough to use our own. This is not in time-critical code. static const char* hc_strstr(const char* s1, const char* s2) { const size_t len = strlen(s2); RAW_CHECK(len > 0, "Unexpected empty string passed to strstr()"); for (const char* p = strchr(s1, *s2); p != NULL; p = strchr(p+1, *s2)) { if (strncmp(p, s2, len) == 0) { return p; } } return NULL; } //---------------------------------------------------------------------- // Our hooks for MallocHook static void NewHook(const void* ptr, size_t size) { if (ptr != NULL) { const int counter = get_thread_disable_counter(); const bool ignore = (counter > 0); RAW_VLOG(16, "Recording Alloc: %p of %" PRIuS "; %d", ptr, size, int(counter)); // Fetch the caller's stack trace before acquiring heap_checker_lock. void* stack[HeapProfileTable::kMaxStackDepth]; int depth = HeapProfileTable::GetCallerStackTrace(0, stack); { SpinLockHolder l(&heap_checker_lock); if (size > max_heap_object_size) max_heap_object_size = size; uintptr_t addr = AsInt(ptr); if (addr < min_heap_address) min_heap_address = addr; addr += size; if (addr > max_heap_address) max_heap_address = addr; if (heap_checker_on) { heap_profile->RecordAlloc(ptr, size, depth, stack); if (ignore) { heap_profile->MarkAsIgnored(ptr); } } } RAW_VLOG(17, "Alloc Recorded: %p of %" PRIuS "", ptr, size); } } static void DeleteHook(const void* ptr) { if (ptr != NULL) { RAW_VLOG(16, "Recording Free %p", ptr); { SpinLockHolder l(&heap_checker_lock); if (heap_checker_on) heap_profile->RecordFree(ptr); } RAW_VLOG(17, "Free Recorded: %p", ptr); } } //---------------------------------------------------------------------- enum StackDirection { GROWS_TOWARDS_HIGH_ADDRESSES, GROWS_TOWARDS_LOW_ADDRESSES, UNKNOWN_DIRECTION }; // Determine which way the stack grows: static StackDirection ATTRIBUTE_NOINLINE GetStackDirection( const uintptr_t *const ptr) { uintptr_t x; if (&x < ptr) return GROWS_TOWARDS_LOW_ADDRESSES; if (ptr < &x) return GROWS_TOWARDS_HIGH_ADDRESSES; RAW_CHECK(0, ""); // Couldn't determine the stack direction. return UNKNOWN_DIRECTION; } // Direction of stack growth (will initialize via GetStackDirection()) static StackDirection stack_direction = UNKNOWN_DIRECTION; // This routine is called for every thread stack we know about to register it. static void RegisterStackLocked(const void* top_ptr) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); RAW_DCHECK(MemoryRegionMap::LockIsHeld(), ""); RAW_VLOG(10, "Thread stack at %p", top_ptr); uintptr_t top = AsInt(top_ptr); stack_tops->insert(top); // add for later use // make sure stack_direction is initialized if (stack_direction == UNKNOWN_DIRECTION) { stack_direction = GetStackDirection(&top); } // Find memory region with this stack MemoryRegionMap::Region region; if (MemoryRegionMap::FindAndMarkStackRegion(top, &region)) { // Make the proper portion of the stack live: if (stack_direction == GROWS_TOWARDS_LOW_ADDRESSES) { RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes", top_ptr, region.end_addr - top); live_objects->push_back(AllocObject(top_ptr, region.end_addr - top, THREAD_DATA)); } else { // GROWS_TOWARDS_HIGH_ADDRESSES RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes", AsPtr(region.start_addr), top - region.start_addr); live_objects->push_back(AllocObject(AsPtr(region.start_addr), top - region.start_addr, THREAD_DATA)); } // not in MemoryRegionMap, look in library_live_objects: } else if (FLAGS_heap_check_ignore_global_live) { for (LibraryLiveObjectsStacks::iterator lib = library_live_objects->begin(); lib != library_live_objects->end(); ++lib) { for (LiveObjectsStack::iterator span = lib->second.begin(); span != lib->second.end(); ++span) { uintptr_t start = AsInt(span->ptr); uintptr_t end = start + span->size; if (start <= top && top < end) { RAW_VLOG(11, "Stack at %p is inside /proc/self/maps chunk %p..%p", top_ptr, AsPtr(start), AsPtr(end)); // Shrink start..end region by chopping away the memory regions in // MemoryRegionMap that land in it to undo merging of regions // in /proc/self/maps, so that we correctly identify what portion // of start..end is actually the stack region. uintptr_t stack_start = start; uintptr_t stack_end = end; // can optimize-away this loop, but it does not run often RAW_DCHECK(MemoryRegionMap::LockIsHeld(), ""); for (MemoryRegionMap::RegionIterator r = MemoryRegionMap::BeginRegionLocked(); r != MemoryRegionMap::EndRegionLocked(); ++r) { if (top < r->start_addr && r->start_addr < stack_end) { stack_end = r->start_addr; } if (stack_start < r->end_addr && r->end_addr <= top) { stack_start = r->end_addr; } } if (stack_start != start || stack_end != end) { RAW_VLOG(11, "Stack at %p is actually inside memory chunk %p..%p", top_ptr, AsPtr(stack_start), AsPtr(stack_end)); } // Make the proper portion of the stack live: if (stack_direction == GROWS_TOWARDS_LOW_ADDRESSES) { RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes", top_ptr, stack_end - top); live_objects->push_back( AllocObject(top_ptr, stack_end - top, THREAD_DATA)); } else { // GROWS_TOWARDS_HIGH_ADDRESSES RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes", AsPtr(stack_start), top - stack_start); live_objects->push_back( AllocObject(AsPtr(stack_start), top - stack_start, THREAD_DATA)); } lib->second.erase(span); // kill the rest of the region // Put the non-stack part(s) of the region back: if (stack_start != start) { lib->second.push_back(AllocObject(AsPtr(start), stack_start - start, MAYBE_LIVE)); } if (stack_end != end) { lib->second.push_back(AllocObject(AsPtr(stack_end), end - stack_end, MAYBE_LIVE)); } return; } } } RAW_LOG(ERROR, "Memory region for stack at %p not found. " "Will likely report false leak positives.", top_ptr); } } // Iterator for heap allocation map data to make ignored objects "live" // (i.e., treated as roots for the mark-and-sweep phase) static void MakeIgnoredObjectsLiveCallbackLocked( const void* ptr, const HeapProfileTable::AllocInfo& info) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); if (info.ignored) { live_objects->push_back(AllocObject(ptr, info.object_size, MUST_BE_ON_HEAP)); } } // Iterator for heap allocation map data to make objects allocated from // disabled regions of code to be live. static void MakeDisabledLiveCallbackLocked( const void* ptr, const HeapProfileTable::AllocInfo& info) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); bool stack_disable = false; bool range_disable = false; for (int depth = 0; depth < info.stack_depth; depth++) { uintptr_t addr = AsInt(info.call_stack[depth]); if (disabled_ranges) { DisabledRangeMap::const_iterator iter = disabled_ranges->upper_bound(addr); if (iter != disabled_ranges->end()) { RAW_DCHECK(iter->first > addr, ""); if (iter->second.start_address < addr && iter->second.max_depth > depth) { range_disable = true; // in range; dropping break; } } } } if (stack_disable || range_disable) { uintptr_t start_address = AsInt(ptr); uintptr_t end_address = start_address + info.object_size; StackTopSet::const_iterator iter = stack_tops->lower_bound(start_address); if (iter != stack_tops->end()) { RAW_DCHECK(*iter >= start_address, ""); if (*iter < end_address) { // We do not disable (treat as live) whole allocated regions // if they are used to hold thread call stacks // (i.e. when we find a stack inside). // The reason is that we'll treat as live the currently used // stack portions anyway (see RegisterStackLocked), // and the rest of the region where the stack lives can well // contain outdated stack variables which are not live anymore, // hence should not be treated as such. RAW_VLOG(11, "Not %s-disabling %" PRIuS " bytes at %p" ": have stack inside: %p", (stack_disable ? "stack" : "range"), info.object_size, ptr, AsPtr(*iter)); return; } } RAW_VLOG(11, "%s-disabling %" PRIuS " bytes at %p", (stack_disable ? "Stack" : "Range"), info.object_size, ptr); live_objects->push_back(AllocObject(ptr, info.object_size, MUST_BE_ON_HEAP)); } } static const char kUnnamedProcSelfMapEntry[] = "UNNAMED"; // This function takes some fields from a /proc/self/maps line: // // start_address start address of a memory region. // end_address end address of a memory region // permissions rwx + private/shared bit // filename filename of the mapped file // // If the region is not writeable, then it cannot have any heap // pointers in it, otherwise we record it as a candidate live region // to get filtered later. static void RecordGlobalDataLocked(uintptr_t start_address, uintptr_t end_address, const char* permissions, const char* filename) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); // Ignore non-writeable regions. if (strchr(permissions, 'w') == NULL) return; if (filename == NULL || *filename == '\0') { filename = kUnnamedProcSelfMapEntry; } RAW_VLOG(11, "Looking into %s: 0x%" PRIxPTR "..0x%" PRIxPTR, filename, start_address, end_address); (*library_live_objects)[filename]. push_back(AllocObject(AsPtr(start_address), end_address - start_address, MAYBE_LIVE)); } // See if 'library' from /proc/self/maps has base name 'library_base' // i.e. contains it and has '.' or '-' after it. static bool IsLibraryNamed(const char* library, const char* library_base) { const char* p = hc_strstr(library, library_base); size_t sz = strlen(library_base); return p != NULL && (p[sz] == '.' || p[sz] == '-'); } // static void HeapLeakChecker::DisableLibraryAllocsLocked(const char* library, uintptr_t start_address, uintptr_t end_address) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); int depth = 0; // TODO(maxim): maybe this should be extended to also use objdump // and pick the text portion of the library more precisely. if (IsLibraryNamed(library, "/libpthread") || // libpthread has a lot of small "system" leaks we don't care about. // In particular it allocates memory to store data supplied via // pthread_setspecific (which can be the only pointer to a heap object). IsLibraryNamed(library, "/libdl") || // library loaders leak some "system" heap that we don't care about IsLibraryNamed(library, "/libcrypto") || // Sometimes libcrypto of OpenSSH is compiled with -fomit-frame-pointer // (any library can be, of course, but this one often is because speed // is so important for making crypto usable). We ignore all its // allocations because we can't see the call stacks. We'd prefer // to ignore allocations done in files/symbols that match // "default_malloc_ex|default_realloc_ex" // but that doesn't work when the end-result binary is stripped. IsLibraryNamed(library, "/libjvm") || // JVM has a lot of leaks we don't care about. IsLibraryNamed(library, "/libzip") // The JVM leaks java.util.zip.Inflater after loading classes. ) { depth = 1; // only disable allocation calls directly from the library code } else if (IsLibraryNamed(library, "/ld") // library loader leaks some "system" heap // (e.g. thread-local storage) that we don't care about ) { depth = 2; // disable allocation calls directly from the library code // and at depth 2 from it. // We need depth 2 here solely because of a libc bug that // forces us to jump through __memalign_hook and MemalignOverride hoops // in tcmalloc.cc. // Those buggy __libc_memalign() calls are in ld-linux.so and happen for // thread-local storage allocations that we want to ignore here. // We go with the depth-2 hack as a workaround for this libc bug: // otherwise we'd need to extend MallocHook interface // so that correct stack depth adjustment can be propagated from // the exceptional case of MemalignOverride. // Using depth 2 here should not mask real leaks because ld-linux.so // does not call user code. } if (depth) { RAW_VLOG(10, "Disabling allocations from %s at depth %d:", library, depth); DisableChecksFromToLocked(AsPtr(start_address), AsPtr(end_address), depth); if (IsLibraryNamed(library, "/libpthread") || IsLibraryNamed(library, "/libdl") || IsLibraryNamed(library, "/ld")) { RAW_VLOG(10, "Global memory regions made by %s will be live data", library); if (global_region_caller_ranges == NULL) { global_region_caller_ranges = new(Allocator::Allocate(sizeof(GlobalRegionCallerRangeMap))) GlobalRegionCallerRangeMap; } global_region_caller_ranges ->insert(make_pair(end_address, start_address)); } } } // static HeapLeakChecker::ProcMapsResult HeapLeakChecker::UseProcMapsLocked( ProcMapsTask proc_maps_task) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); // Need to provide own scratch memory to ProcMapsIterator: ProcMapsIterator::Buffer buffer; ProcMapsIterator it(0, &buffer); if (!it.Valid()) { int errsv = errno; RAW_LOG(ERROR, "Could not open /proc/self/maps: errno=%d. " "Libraries will not be handled correctly.", errsv); return CANT_OPEN_PROC_MAPS; } uint64 start_address, end_address, file_offset; int64 inode; char *permissions, *filename; bool saw_shared_lib = false; bool saw_nonzero_inode = false; bool saw_shared_lib_with_nonzero_inode = false; while (it.Next(&start_address, &end_address, &permissions, &file_offset, &inode, &filename)) { if (start_address >= end_address) { // Warn if a line we can be interested in is ill-formed: if (inode != 0) { RAW_LOG(ERROR, "Errors reading /proc/self/maps. " "Some global memory regions will not " "be handled correctly."); } // Silently skip other ill-formed lines: some are possible // probably due to the interplay of how /proc/self/maps is updated // while we read it in chunks in ProcMapsIterator and // do things in this loop. continue; } // Determine if any shared libraries are present (this is the same // list of extensions as is found in pprof). We want to ignore // 'fake' libraries with inode 0 when determining. However, some // systems don't share inodes via /proc, so we turn off this check // if we don't see any evidence that we're getting inode info. if (inode != 0) { saw_nonzero_inode = true; } if ((hc_strstr(filename, "lib") && hc_strstr(filename, ".so")) || hc_strstr(filename, ".dll") || // not all .dylib filenames start with lib. .dylib is big enough // that we are unlikely to get false matches just checking that. hc_strstr(filename, ".dylib") || hc_strstr(filename, ".bundle")) { saw_shared_lib = true; if (inode != 0) { saw_shared_lib_with_nonzero_inode = true; } } switch (proc_maps_task) { case DISABLE_LIBRARY_ALLOCS: // All lines starting like // "401dc000-4030f000 r??p 00132000 03:01 13991972 lib/bin" // identify a data and code sections of a shared library or our binary if (inode != 0 && strncmp(permissions, "r-xp", 4) == 0) { DisableLibraryAllocsLocked(filename, start_address, end_address); } break; case RECORD_GLOBAL_DATA: RecordGlobalDataLocked(start_address, end_address, permissions, filename); break; default: RAW_CHECK(0, ""); } } // If /proc/self/maps is reporting inodes properly (we saw a // non-zero inode), then we only say we saw a shared lib if we saw a // 'real' one, with a non-zero inode. if (saw_nonzero_inode) { saw_shared_lib = saw_shared_lib_with_nonzero_inode; } if (!saw_shared_lib) { RAW_LOG(ERROR, "No shared libs detected. Will likely report false leak " "positives for statically linked executables."); return NO_SHARED_LIBS_IN_PROC_MAPS; } return PROC_MAPS_USED; } // Total number and size of live objects dropped from the profile; // (re)initialized in IgnoreAllLiveObjectsLocked. static int64 live_objects_total; static int64 live_bytes_total; // pid of the thread that is doing the current leak check // (protected by our lock; IgnoreAllLiveObjectsLocked sets it) static pid_t self_thread_pid = 0; // Status of our thread listing callback execution // (protected by our lock; used from within IgnoreAllLiveObjectsLocked) static enum { CALLBACK_NOT_STARTED, CALLBACK_STARTED, CALLBACK_COMPLETED, } thread_listing_status = CALLBACK_NOT_STARTED; // Ideally to avoid deadlocks this function should not result in any libc // or other function calls that might need to lock a mutex: // It is called when all threads of a process are stopped // at arbitrary points thus potentially holding those locks. // // In practice we are calling some simple i/o and sprintf-type library functions // for logging messages, but use only our own LowLevelAlloc::Arena allocator. // // This is known to be buggy: the library i/o function calls are able to cause // deadlocks when they request a lock that a stopped thread happens to hold. // This issue as far as we know have so far not resulted in any deadlocks // in practice, so for now we are taking our chance that the deadlocks // have insignificant frequency. // // If such deadlocks become a problem we should make the i/o calls // into appropriately direct system calls (or eliminate them), // in particular write() is not safe and vsnprintf() is potentially dangerous // due to reliance on locale functions (these are called through RAW_LOG // and in other ways). // #if defined(HAVE_LINUX_PTRACE_H) && defined(HAVE_SYS_SYSCALL_H) && defined(DUMPER) # if (defined(__i386__) || defined(__x86_64)) # define THREAD_REGS i386_regs # elif defined(__PPC__) # define THREAD_REGS ppc_regs # endif #endif /*static*/ int HeapLeakChecker::IgnoreLiveThreadsLocked(void* parameter, int num_threads, pid_t* thread_pids, va_list /*ap*/) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); thread_listing_status = CALLBACK_STARTED; RAW_VLOG(11, "Found %d threads (from pid %d)", num_threads, getpid()); if (FLAGS_heap_check_ignore_global_live) { UseProcMapsLocked(RECORD_GLOBAL_DATA); } // We put the registers from other threads here // to make pointers stored in them live. vector<void*, STL_Allocator<void*, Allocator> > thread_registers; int failures = 0; for (int i = 0; i < num_threads; ++i) { // the leak checking thread itself is handled // specially via self_thread_stack, not here: if (thread_pids[i] == self_thread_pid) continue; RAW_VLOG(11, "Handling thread with pid %d", thread_pids[i]); #ifdef THREAD_REGS THREAD_REGS thread_regs; #define sys_ptrace(r, p, a, d) syscall(SYS_ptrace, (r), (p), (a), (d)) // We use sys_ptrace to avoid thread locking // because this is called from TCMalloc_ListAllProcessThreads // when all but this thread are suspended. if (sys_ptrace(PTRACE_GETREGS, thread_pids[i], NULL, &thread_regs) == 0) { // Need to use SP to get all the data from the very last stack frame: COMPILE_ASSERT(sizeof(thread_regs.SP) == sizeof(void*), SP_register_does_not_look_like_a_pointer); RegisterStackLocked(reinterpret_cast<void*>(thread_regs.SP)); // Make registers live (just in case PTRACE_ATTACH resulted in some // register pointers still being in the registers and not on the stack): for (void** p = reinterpret_cast<void**>(&thread_regs); p < reinterpret_cast<void**>(&thread_regs + 1); ++p) { RAW_VLOG(12, "Thread register %p", *p); thread_registers.push_back(*p); } } else { failures += 1; } #else failures += 1; #endif } // Use all the collected thread (stack) liveness sources: IgnoreLiveObjectsLocked("threads stack data", ""); if (thread_registers.size()) { // Make thread registers be live heap data sources. // we rely here on the fact that vector is in one memory chunk: RAW_VLOG(11, "Live registers at %p of %" PRIuS " bytes", &thread_registers[0], thread_registers.size() * sizeof(void*)); live_objects->push_back(AllocObject(&thread_registers[0], thread_registers.size() * sizeof(void*), THREAD_REGISTERS)); IgnoreLiveObjectsLocked("threads register data", ""); } // Do all other liveness walking while all threads are stopped: IgnoreNonThreadLiveObjectsLocked(); // Can now resume the threads: TCMalloc_ResumeAllProcessThreads(num_threads, thread_pids); thread_listing_status = CALLBACK_COMPLETED; return failures; } // Stack top of the thread that is doing the current leak check // (protected by our lock; IgnoreAllLiveObjectsLocked sets it) static const void* self_thread_stack_top; // static void HeapLeakChecker::IgnoreNonThreadLiveObjectsLocked() { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); RAW_DCHECK(MemoryRegionMap::LockIsHeld(), ""); RAW_VLOG(11, "Handling self thread with pid %d", self_thread_pid); // Register our own stack: // Important that all stack ranges (including the one here) // are known before we start looking at them // in MakeDisabledLiveCallbackLocked: RegisterStackLocked(self_thread_stack_top); IgnoreLiveObjectsLocked("stack data", ""); // Make objects we were told to ignore live: if (ignored_objects) { for (IgnoredObjectsMap::const_iterator object = ignored_objects->begin(); object != ignored_objects->end(); ++object) { const void* ptr = AsPtr(object->first); RAW_VLOG(11, "Ignored live object at %p of %" PRIuS " bytes", ptr, object->second); live_objects-> push_back(AllocObject(ptr, object->second, MUST_BE_ON_HEAP)); // we do this liveness check for ignored_objects before doing any // live heap walking to make sure it does not fail needlessly: size_t object_size; if (!(heap_profile->FindAlloc(ptr, &object_size) && object->second == object_size)) { RAW_LOG(FATAL, "Object at %p of %" PRIuS " bytes from an" " IgnoreObject() has disappeared", ptr, object->second); } } IgnoreLiveObjectsLocked("ignored objects", ""); } // Treat objects that were allocated when a Disabler was live as // roots. I.e., if X was allocated while a Disabler was active, // and Y is reachable from X, arrange that neither X nor Y are // treated as leaks. heap_profile->IterateAllocs(MakeIgnoredObjectsLiveCallbackLocked); IgnoreLiveObjectsLocked("disabled objects", ""); // Make code-address-disabled objects live and ignored: // This in particular makes all thread-specific data live // because the basic data structure to hold pointers to thread-specific data // is allocated from libpthreads and we have range-disabled that // library code with UseProcMapsLocked(DISABLE_LIBRARY_ALLOCS); // so now we declare all thread-specific data reachable from there as live. heap_profile->IterateAllocs(MakeDisabledLiveCallbackLocked); IgnoreLiveObjectsLocked("disabled code", ""); // Actually make global data live: if (FLAGS_heap_check_ignore_global_live) { bool have_null_region_callers = false; for (LibraryLiveObjectsStacks::iterator l = library_live_objects->begin(); l != library_live_objects->end(); ++l) { RAW_CHECK(live_objects->empty(), ""); // Process library_live_objects in l->second // filtering them by MemoryRegionMap: // It's safe to iterate over MemoryRegionMap // w/o locks here as we are inside MemoryRegionMap::Lock(): RAW_DCHECK(MemoryRegionMap::LockIsHeld(), ""); // The only change to MemoryRegionMap possible in this loop // is region addition as a result of allocating more memory // for live_objects. This won't invalidate the RegionIterator // or the intent of the loop. // --see the comment by MemoryRegionMap::BeginRegionLocked(). for (MemoryRegionMap::RegionIterator region = MemoryRegionMap::BeginRegionLocked(); region != MemoryRegionMap::EndRegionLocked(); ++region) { // "region" from MemoryRegionMap is to be subtracted from // (tentatively live) regions in l->second // if it has a stack inside or it was allocated by // a non-special caller (not one covered by a range // in global_region_caller_ranges). // This will in particular exclude all memory chunks used // by the heap itself as well as what's been allocated with // any allocator on top of mmap. bool subtract = true; if (!region->is_stack && global_region_caller_ranges) { if (region->caller() == static_cast<uintptr_t>(NULL)) { have_null_region_callers = true; } else { GlobalRegionCallerRangeMap::const_iterator iter = global_region_caller_ranges->upper_bound(region->caller()); if (iter != global_region_caller_ranges->end()) { RAW_DCHECK(iter->first > region->caller(), ""); if (iter->second < region->caller()) { // in special region subtract = false; } } } } if (subtract) { // The loop puts the result of filtering l->second into live_objects: for (LiveObjectsStack::const_iterator i = l->second.begin(); i != l->second.end(); ++i) { // subtract *region from *i uintptr_t start = AsInt(i->ptr); uintptr_t end = start + i->size; if (region->start_addr <= start && end <= region->end_addr) { // full deletion due to subsumption } else if (start < region->start_addr && region->end_addr < end) { // cutting-out split live_objects->push_back(AllocObject(i->ptr, region->start_addr - start, IN_GLOBAL_DATA)); live_objects->push_back(AllocObject(AsPtr(region->end_addr), end - region->end_addr, IN_GLOBAL_DATA)); } else if (region->end_addr > start && region->start_addr <= start) { // cut from start live_objects->push_back(AllocObject(AsPtr(region->end_addr), end - region->end_addr, IN_GLOBAL_DATA)); } else if (region->start_addr > start && region->start_addr < end) { // cut from end live_objects->push_back(AllocObject(i->ptr, region->start_addr - start, IN_GLOBAL_DATA)); } else { // pass: no intersection live_objects->push_back(AllocObject(i->ptr, i->size, IN_GLOBAL_DATA)); } } // Move live_objects back into l->second // for filtering by the next region. live_objects->swap(l->second); live_objects->clear(); } } // Now get and use live_objects from the final version of l->second: if (VLOG_IS_ON(11)) { for (LiveObjectsStack::const_iterator i = l->second.begin(); i != l->second.end(); ++i) { RAW_VLOG(11, "Library live region at %p of %" PRIuPTR " bytes", i->ptr, i->size); } } live_objects->swap(l->second); IgnoreLiveObjectsLocked("in globals of\n ", l->first.c_str()); } if (have_null_region_callers) { RAW_LOG(ERROR, "Have memory regions w/o callers: " "might report false leaks"); } Allocator::DeleteAndNull(&library_live_objects); } } // Callback for TCMalloc_ListAllProcessThreads in IgnoreAllLiveObjectsLocked below // to test/verify that we have just the one main thread, in which case // we can do everything in that main thread, // so that CPU profiler can collect all its samples. // Returns the number of threads in the process. static int IsOneThread(void* parameter, int num_threads, pid_t* thread_pids, va_list ap) { if (num_threads != 1) { RAW_LOG(WARNING, "Have threads: Won't CPU-profile the bulk of leak " "checking work happening in IgnoreLiveThreadsLocked!"); } TCMalloc_ResumeAllProcessThreads(num_threads, thread_pids); return num_threads; } // Dummy for IgnoreAllLiveObjectsLocked below. // Making it global helps with compiler warnings. static va_list dummy_ap; // static void HeapLeakChecker::IgnoreAllLiveObjectsLocked(const void* self_stack_top) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); RAW_CHECK(live_objects == NULL, ""); live_objects = new(Allocator::Allocate(sizeof(LiveObjectsStack))) LiveObjectsStack; stack_tops = new(Allocator::Allocate(sizeof(StackTopSet))) StackTopSet; // reset the counts live_objects_total = 0; live_bytes_total = 0; // Reduce max_heap_object_size to FLAGS_heap_check_max_pointer_offset // for the time of leak check. // FLAGS_heap_check_max_pointer_offset caps max_heap_object_size // to manage reasonably low chances of random bytes // appearing to be pointing into large actually leaked heap objects. const size_t old_max_heap_object_size = max_heap_object_size; max_heap_object_size = ( FLAGS_heap_check_max_pointer_offset != -1 ? min(size_t(FLAGS_heap_check_max_pointer_offset), max_heap_object_size) : max_heap_object_size); // Record global data as live: if (FLAGS_heap_check_ignore_global_live) { library_live_objects = new(Allocator::Allocate(sizeof(LibraryLiveObjectsStacks))) LibraryLiveObjectsStacks; } // Ignore all thread stacks: thread_listing_status = CALLBACK_NOT_STARTED; bool need_to_ignore_non_thread_objects = true; self_thread_pid = getpid(); self_thread_stack_top = self_stack_top; if (FLAGS_heap_check_ignore_thread_live) { // In case we are doing CPU profiling we'd like to do all the work // in the main thread, not in the special thread created by // TCMalloc_ListAllProcessThreads, so that CPU profiler can // collect all its samples. The machinery of // TCMalloc_ListAllProcessThreads conflicts with the CPU profiler // by also relying on signals and ::sigaction. We can do this // (run everything in the main thread) safely only if there's just // the main thread itself in our process. This variable reflects // these two conditions: bool want_and_can_run_in_main_thread = ProfilingIsEnabledForAllThreads() && TCMalloc_ListAllProcessThreads(NULL, IsOneThread) == 1; // When the normal path of TCMalloc_ListAllProcessThreads below is taken, // we fully suspend the threads right here before any liveness checking // and keep them suspended for the whole time of liveness checking // inside of the IgnoreLiveThreadsLocked callback. // (The threads can't (de)allocate due to lock on the delete hook but // if not suspended they could still mess with the pointer // graph while we walk it). int r = want_and_can_run_in_main_thread ? IgnoreLiveThreadsLocked(NULL, 1, &self_thread_pid, dummy_ap) : TCMalloc_ListAllProcessThreads(NULL, IgnoreLiveThreadsLocked); need_to_ignore_non_thread_objects = r < 0; if (r < 0) { RAW_LOG(WARNING, "Thread finding failed with %d errno=%d", r, errno); if (thread_listing_status == CALLBACK_COMPLETED) { RAW_LOG(INFO, "Thread finding callback " "finished ok; hopefully everything is fine"); need_to_ignore_non_thread_objects = false; } else if (thread_listing_status == CALLBACK_STARTED) { RAW_LOG(FATAL, "Thread finding callback was " "interrupted or crashed; can't fix this"); } else { // CALLBACK_NOT_STARTED RAW_LOG(ERROR, "Could not find thread stacks. " "Will likely report false leak positives."); } } else if (r != 0) { RAW_LOG(ERROR, "Thread stacks not found for %d threads. " "Will likely report false leak positives.", r); } else { RAW_VLOG(11, "Thread stacks appear to be found for all threads"); } } else { RAW_LOG(WARNING, "Not looking for thread stacks; " "objects reachable only from there " "will be reported as leaks"); } // Do all other live data ignoring here if we did not do it // within thread listing callback with all threads stopped. if (need_to_ignore_non_thread_objects) { if (FLAGS_heap_check_ignore_global_live) { UseProcMapsLocked(RECORD_GLOBAL_DATA); } IgnoreNonThreadLiveObjectsLocked(); } if (live_objects_total) { RAW_VLOG(10, "Ignoring %" PRId64 " reachable objects of %" PRId64 " bytes", live_objects_total, live_bytes_total); } // Free these: we made them here and heap_profile never saw them Allocator::DeleteAndNull(&live_objects); Allocator::DeleteAndNull(&stack_tops); max_heap_object_size = old_max_heap_object_size; // reset this var } // Alignment at which we should consider pointer positions // in IgnoreLiveObjectsLocked. Will normally use the value of // FLAGS_heap_check_pointer_source_alignment. static size_t pointer_source_alignment = kPointerSourceAlignment; // Global lock for HeapLeakChecker::DoNoLeaks // to protect pointer_source_alignment. static SpinLock alignment_checker_lock(SpinLock::LINKER_INITIALIZED); // This function changes the live bits in the heap_profile-table's state: // we only record the live objects to be skipped. // // When checking if a byte sequence points to a heap object we use // HeapProfileTable::FindInsideAlloc to handle both pointers to // the start and inside of heap-allocated objects. // The "inside" case needs to be checked to support // at least the following relatively common cases: // - C++ arrays allocated with new FooClass[size] for classes // with destructors have their size recorded in a sizeof(int) field // before the place normal pointers point to. // - basic_string<>-s for e.g. the C++ library of gcc 3.4 // have the meta-info in basic_string<...>::_Rep recorded // before the place normal pointers point to. // - Multiple-inherited objects have their pointers when cast to // different base classes pointing inside of the actually // allocated object. // - Sometimes reachability pointers point to member objects of heap objects, // and then those member objects point to the full heap object. // - Third party UnicodeString: it stores a 32-bit refcount // (in both 32-bit and 64-bit binaries) as the first uint32 // in the allocated memory and a normal pointer points at // the second uint32 behind the refcount. // By finding these additional objects here // we slightly increase the chance to mistake random memory bytes // for a pointer and miss a leak in a particular run of a binary. // /*static*/ void HeapLeakChecker::IgnoreLiveObjectsLocked(const char* name, const char* name2) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); int64 live_object_count = 0; int64 live_byte_count = 0; while (!live_objects->empty()) { const char* object = reinterpret_cast<const char*>(live_objects->back().ptr); size_t size = live_objects->back().size; const ObjectPlacement place = live_objects->back().place; live_objects->pop_back(); if (place == MUST_BE_ON_HEAP && heap_profile->MarkAsLive(object)) { live_object_count += 1; live_byte_count += size; } RAW_VLOG(13, "Looking for heap pointers in %p of %" PRIuS " bytes", object, size); const char* const whole_object = object; size_t const whole_size = size; // Try interpretting any byte sequence in object,size as a heap pointer: const size_t remainder = AsInt(object) % pointer_source_alignment; if (remainder) { object += pointer_source_alignment - remainder; if (size >= pointer_source_alignment - remainder) { size -= pointer_source_alignment - remainder; } else { size = 0; } } if (size < sizeof(void*)) continue; #ifdef NO_FRAME_POINTER // Frame pointer omission requires us to use libunwind, which uses direct // mmap and munmap system calls, and that needs special handling. if (name2 == kUnnamedProcSelfMapEntry) { static const uintptr_t page_mask = ~(getpagesize() - 1); const uintptr_t addr = reinterpret_cast<uintptr_t>(object); if ((addr & page_mask) == 0 && (size & page_mask) == 0) { // This is an object we slurped from /proc/self/maps. // It may or may not be readable at this point. // // In case all the above conditions made a mistake, and the object is // not related to libunwind, we also verify that it's not readable // before ignoring it. if (msync(const_cast<char*>(object), size, MS_ASYNC) != 0) { // Skip unreadable object, so we don't crash trying to sweep it. RAW_VLOG(0, "Ignoring inaccessible object [%p, %p) " "(msync error %d (%s))", object, object + size, errno, strerror(errno)); continue; } } } #endif const char* const max_object = object + size - sizeof(void*); while (object <= max_object) { // potentially unaligned load: const uintptr_t addr = *reinterpret_cast<const uintptr_t*>(object); // Do fast check before the more expensive HaveOnHeapLocked lookup: // this code runs for all memory words that are potentially pointers: const bool can_be_on_heap = // Order tests by the likelyhood of the test failing in 64/32 bit modes. // Yes, this matters: we either lose 5..6% speed in 32 bit mode // (which is already slower) or by a factor of 1.5..1.91 in 64 bit mode. // After the alignment test got dropped the above performance figures // must have changed; might need to revisit this. #if defined(__x86_64__) addr <= max_heap_address && // <= is for 0-sized object with max addr min_heap_address <= addr; #else min_heap_address <= addr && addr <= max_heap_address; // <= is for 0-sized object with max addr #endif if (can_be_on_heap) { const void* ptr = reinterpret_cast<const void*>(addr); // Too expensive (inner loop): manually uncomment when debugging: // RAW_VLOG(17, "Trying pointer to %p at %p", ptr, object); size_t object_size; if (HaveOnHeapLocked(&ptr, &object_size) && heap_profile->MarkAsLive(ptr)) { // We take the (hopefully low) risk here of encountering by accident // a byte sequence in memory that matches an address of // a heap object which is in fact leaked. // I.e. in very rare and probably not repeatable/lasting cases // we might miss some real heap memory leaks. RAW_VLOG(14, "Found pointer to %p of %" PRIuS " bytes at %p " "inside %p of size %" PRIuS "", ptr, object_size, object, whole_object, whole_size); if (VLOG_IS_ON(15)) { // log call stacks to help debug how come something is not a leak HeapProfileTable::AllocInfo alloc; if (!heap_profile->FindAllocDetails(ptr, &alloc)) { RAW_LOG(FATAL, "FindAllocDetails failed on ptr %p", ptr); } RAW_LOG(INFO, "New live %p object's alloc stack:", ptr); for (int i = 0; i < alloc.stack_depth; ++i) { RAW_LOG(INFO, " @ %p", alloc.call_stack[i]); } } live_object_count += 1; live_byte_count += object_size; live_objects->push_back(AllocObject(ptr, object_size, IGNORED_ON_HEAP)); } } object += pointer_source_alignment; } } live_objects_total += live_object_count; live_bytes_total += live_byte_count; if (live_object_count) { RAW_VLOG(10, "Removed %" PRId64 " live heap objects of %" PRId64 " bytes: %s%s", live_object_count, live_byte_count, name, name2); } } //---------------------------------------------------------------------- // HeapLeakChecker leak check disabling components //---------------------------------------------------------------------- // static void HeapLeakChecker::DisableChecksIn(const char* pattern) { RAW_LOG(WARNING, "DisableChecksIn(%s) is ignored", pattern); } // static void HeapLeakChecker::DoIgnoreObject(const void* ptr) { SpinLockHolder l(&heap_checker_lock); if (!heap_checker_on) return; size_t object_size; if (!HaveOnHeapLocked(&ptr, &object_size)) { RAW_LOG(ERROR, "No live heap object at %p to ignore", ptr); } else { RAW_VLOG(10, "Going to ignore live object at %p of %" PRIuS " bytes", ptr, object_size); if (ignored_objects == NULL) { ignored_objects = new(Allocator::Allocate(sizeof(IgnoredObjectsMap))) IgnoredObjectsMap; } if (!ignored_objects->insert(make_pair(AsInt(ptr), object_size)).second) { RAW_LOG(WARNING, "Object at %p is already being ignored", ptr); } } } // static void HeapLeakChecker::UnIgnoreObject(const void* ptr) { SpinLockHolder l(&heap_checker_lock); if (!heap_checker_on) return; size_t object_size; if (!HaveOnHeapLocked(&ptr, &object_size)) { RAW_LOG(FATAL, "No live heap object at %p to un-ignore", ptr); } else { bool found = false; if (ignored_objects) { IgnoredObjectsMap::iterator object = ignored_objects->find(AsInt(ptr)); if (object != ignored_objects->end() && object_size == object->second) { ignored_objects->erase(object); found = true; RAW_VLOG(10, "Now not going to ignore live object " "at %p of %" PRIuS " bytes", ptr, object_size); } } if (!found) RAW_LOG(FATAL, "Object at %p has not been ignored", ptr); } } //---------------------------------------------------------------------- // HeapLeakChecker non-static functions //---------------------------------------------------------------------- char* HeapLeakChecker::MakeProfileNameLocked() { RAW_DCHECK(lock_->IsHeld(), ""); RAW_DCHECK(heap_checker_lock.IsHeld(), ""); const int len = profile_name_prefix->size() + strlen(name_) + 5 + strlen(HeapProfileTable::kFileExt) + 1; char* file_name = reinterpret_cast<char*>(Allocator::Allocate(len)); snprintf(file_name, len, "%s.%s-end%s", profile_name_prefix->c_str(), name_, HeapProfileTable::kFileExt); return file_name; } void HeapLeakChecker::Create(const char *name, bool make_start_snapshot) { SpinLockHolder l(lock_); name_ = NULL; // checker is inactive start_snapshot_ = NULL; has_checked_ = false; inuse_bytes_increase_ = 0; inuse_allocs_increase_ = 0; keep_profiles_ = false; char* n = new char[strlen(name) + 1]; // do this before we lock IgnoreObject(n); // otherwise it might be treated as live due to our stack { // Heap activity in other threads is paused for this whole scope. SpinLockHolder al(&alignment_checker_lock); SpinLockHolder hl(&heap_checker_lock); MemoryRegionMap::LockHolder ml; if (heap_checker_on && profile_name_prefix != NULL) { RAW_DCHECK(strchr(name, '/') == NULL, "must be a simple name"); memcpy(n, name, strlen(name) + 1); name_ = n; // checker is active if (make_start_snapshot) { start_snapshot_ = heap_profile->TakeSnapshot(); } const HeapProfileTable::Stats& t = heap_profile->total(); const size_t start_inuse_bytes = t.alloc_size - t.free_size; const size_t start_inuse_allocs = t.allocs - t.frees; RAW_VLOG(10, "Start check \"%s\" profile: %" PRIuS " bytes " "in %" PRIuS " objects", name_, start_inuse_bytes, start_inuse_allocs); } else { RAW_LOG(WARNING, "Heap checker is not active, " "hence checker \"%s\" will do nothing!", name); RAW_LOG(WARNING, "To activate set the HEAPCHECK environment variable.\n"); } } if (name_ == NULL) { UnIgnoreObject(n); delete[] n; // must be done after we unlock } } HeapLeakChecker::HeapLeakChecker(const char *name) : lock_(new SpinLock) { RAW_DCHECK(strcmp(name, "_main_") != 0, "_main_ is reserved"); Create(name, true/*create start_snapshot_*/); } HeapLeakChecker::HeapLeakChecker() : lock_(new SpinLock) { if (FLAGS_heap_check_before_constructors) { // We want to check for leaks of objects allocated during global // constructors (i.e., objects allocated already). So we do not // create a baseline snapshot and hence check for leaks of objects // that may have already been created. Create("_main_", false); } else { // We want to ignore leaks of objects allocated during global // constructors (i.e., objects allocated already). So we snapshot // the current heap contents and use them as a baseline that is // not reported by the leak checker. Create("_main_", true); } } ssize_t HeapLeakChecker::BytesLeaked() const { SpinLockHolder l(lock_); if (!has_checked_) { RAW_LOG(FATAL, "*NoLeaks|SameHeap must execute before this call"); } return inuse_bytes_increase_; } ssize_t HeapLeakChecker::ObjectsLeaked() const { SpinLockHolder l(lock_); if (!has_checked_) { RAW_LOG(FATAL, "*NoLeaks|SameHeap must execute before this call"); } return inuse_allocs_increase_; } // Save pid of main thread for using in naming dump files static int32 main_thread_pid = getpid(); #ifdef HAVE_PROGRAM_INVOCATION_NAME #ifdef __UCLIBC__ extern const char* program_invocation_name; extern const char* program_invocation_short_name; #else extern char* program_invocation_name; extern char* program_invocation_short_name; #endif static const char* invocation_name() { return program_invocation_short_name; } static string invocation_path() { return program_invocation_name; } #else static const char* invocation_name() { return "<your binary>"; } static string invocation_path() { return "<your binary>"; } #endif // Prints commands that users can run to get more information // about the reported leaks. static void SuggestPprofCommand(const char* pprof_file_arg) { // Extra help information to print for the user when the test is // being run in a way where the straightforward pprof command will // not suffice. string extra_help; // Common header info to print for remote runs const string remote_header = "This program is being executed remotely and therefore the pprof\n" "command printed above will not work. Either run this program\n" "locally, or adjust the pprof command as follows to allow it to\n" "work on your local machine:\n"; // Extra command for fetching remote data string fetch_cmd; RAW_LOG(WARNING, "\n\n" "If the preceding stack traces are not enough to find " "the leaks, try running THIS shell command:\n\n" "%s%s %s \"%s\" --inuse_objects --lines --heapcheck " " --edgefraction=1e-10 --nodefraction=1e-10 --gv\n" "\n" "%s" "If you are still puzzled about why the leaks are " "there, try rerunning this program with " "HEAP_CHECK_TEST_POINTER_ALIGNMENT=1 and/or with " "HEAP_CHECK_MAX_POINTER_OFFSET=-1\n" "If the leak report occurs in a small fraction of runs, " "try running with TCMALLOC_MAX_FREE_QUEUE_SIZE of few hundred MB " "or with TCMALLOC_RECLAIM_MEMORY=false, " // only works for debugalloc "it might help find leaks more repeatably\n", fetch_cmd.c_str(), "pprof", // works as long as pprof is on your path invocation_path().c_str(), pprof_file_arg, extra_help.c_str() ); } bool HeapLeakChecker::DoNoLeaks(ShouldSymbolize should_symbolize) { SpinLockHolder l(lock_); // The locking also helps us keep the messages // for the two checks close together. SpinLockHolder al(&alignment_checker_lock); // thread-safe: protected by alignment_checker_lock static bool have_disabled_hooks_for_symbolize = false; // Once we've checked for leaks and symbolized the results once, it's // not safe to do it again. This is because in order to symbolize // safely, we had to disable all the malloc hooks here, so we no // longer can be confident we've collected all the data we need. if (have_disabled_hooks_for_symbolize) { RAW_LOG(FATAL, "Must not call heap leak checker manually after " " program-exit's automatic check."); } HeapProfileTable::Snapshot* leaks = NULL; char* pprof_file = NULL; { // Heap activity in other threads is paused during this function // (i.e. until we got all profile difference info). SpinLockHolder hl(&heap_checker_lock); if (heap_checker_on == false) { if (name_ != NULL) { // leak checking enabled when created the checker RAW_LOG(WARNING, "Heap leak checker got turned off after checker " "\"%s\" has been created, no leak check is being done for it!", name_); } return true; } // Update global_region_caller_ranges. They may need to change since // e.g. initialization because shared libraries might have been loaded or // unloaded. Allocator::DeleteAndNullIfNot(&global_region_caller_ranges); ProcMapsResult pm_result = UseProcMapsLocked(DISABLE_LIBRARY_ALLOCS); RAW_CHECK(pm_result == PROC_MAPS_USED, ""); // Keep track of number of internally allocated objects so we // can detect leaks in the heap-leak-checket itself const int initial_allocs = Allocator::alloc_count(); if (name_ == NULL) { RAW_LOG(FATAL, "Heap leak checker must not be turned on " "after construction of a HeapLeakChecker"); } MemoryRegionMap::LockHolder ml; int a_local_var; // Use our stack ptr to make stack data live: // Make the heap profile, other threads are locked out. HeapProfileTable::Snapshot* base = reinterpret_cast<HeapProfileTable::Snapshot*>(start_snapshot_); RAW_DCHECK(FLAGS_heap_check_pointer_source_alignment > 0, ""); pointer_source_alignment = FLAGS_heap_check_pointer_source_alignment; IgnoreAllLiveObjectsLocked(&a_local_var); leaks = heap_profile->NonLiveSnapshot(base); inuse_bytes_increase_ = static_cast<ssize_t>(leaks->total().alloc_size); inuse_allocs_increase_ = static_cast<ssize_t>(leaks->total().allocs); if (leaks->Empty()) { heap_profile->ReleaseSnapshot(leaks); leaks = NULL; // We can only check for internal leaks along the no-user-leak // path since in the leak path we temporarily release // heap_checker_lock and another thread can come in and disturb // allocation counts. if (Allocator::alloc_count() != initial_allocs) { RAW_LOG(FATAL, "Internal HeapChecker leak of %d objects ; %d -> %d", Allocator::alloc_count() - initial_allocs, initial_allocs, Allocator::alloc_count()); } } else if (FLAGS_heap_check_test_pointer_alignment) { if (pointer_source_alignment == 1) { RAW_LOG(WARNING, "--heap_check_test_pointer_alignment has no effect: " "--heap_check_pointer_source_alignment was already set to 1"); } else { // Try with reduced pointer aligment pointer_source_alignment = 1; IgnoreAllLiveObjectsLocked(&a_local_var); HeapProfileTable::Snapshot* leaks_wo_align = heap_profile->NonLiveSnapshot(base); pointer_source_alignment = FLAGS_heap_check_pointer_source_alignment; if (leaks_wo_align->Empty()) { RAW_LOG(WARNING, "Found no leaks without pointer alignment: " "something might be placing pointers at " "unaligned addresses! This needs to be fixed."); } else { RAW_LOG(INFO, "Found leaks without pointer alignment as well: " "unaligned pointers must not be the cause of leaks."); RAW_LOG(INFO, "--heap_check_test_pointer_alignment did not help " "to diagnose the leaks."); } heap_profile->ReleaseSnapshot(leaks_wo_align); } } if (leaks != NULL) { pprof_file = MakeProfileNameLocked(); } } has_checked_ = true; if (leaks == NULL) { if (FLAGS_heap_check_max_pointer_offset == -1) { RAW_LOG(WARNING, "Found no leaks without max_pointer_offset restriction: " "it's possible that the default value of " "heap_check_max_pointer_offset flag is too low. " "Do you use pointers with larger than that offsets " "pointing in the middle of heap-allocated objects?"); } const HeapProfileTable::Stats& stats = heap_profile->total(); RAW_VLOG(heap_checker_info_level, "No leaks found for check \"%s\" " "(but no 100%% guarantee that there aren't any): " "found %" PRId64 " reachable heap objects of %" PRId64 " bytes", name_, int64(stats.allocs - stats.frees), int64(stats.alloc_size - stats.free_size)); } else { if (should_symbolize == SYMBOLIZE) { // To turn addresses into symbols, we need to fork, which is a // problem if both parent and child end up trying to call the // same malloc-hooks we've set up, at the same time. To avoid // trouble, we turn off the hooks before symbolizing. Note that // this makes it unsafe to ever leak-report again! Luckily, we // typically only want to report once in a program's run, at the // very end. if (MallocHook::GetNewHook() == NewHook) MallocHook::SetNewHook(NULL); if (MallocHook::GetDeleteHook() == DeleteHook) MallocHook::SetDeleteHook(NULL); MemoryRegionMap::Shutdown(); // Make sure all the hooks really got unset: RAW_CHECK(MallocHook::GetNewHook() == NULL, ""); RAW_CHECK(MallocHook::GetDeleteHook() == NULL, ""); RAW_CHECK(MallocHook::GetMmapHook() == NULL, ""); RAW_CHECK(MallocHook::GetSbrkHook() == NULL, ""); have_disabled_hooks_for_symbolize = true; leaks->ReportLeaks(name_, pprof_file, true); // true = should_symbolize } else { leaks->ReportLeaks(name_, pprof_file, false); } if (FLAGS_heap_check_identify_leaks) { leaks->ReportIndividualObjects(); } SuggestPprofCommand(pprof_file); { SpinLockHolder hl(&heap_checker_lock); heap_profile->ReleaseSnapshot(leaks); Allocator::Free(pprof_file); } } return (leaks == NULL); } HeapLeakChecker::~HeapLeakChecker() { if (name_ != NULL) { // had leak checking enabled when created the checker if (!has_checked_) { RAW_LOG(FATAL, "Some *NoLeaks|SameHeap method" " must be called on any created HeapLeakChecker"); } // Deallocate any snapshot taken at start if (start_snapshot_ != NULL) { SpinLockHolder l(&heap_checker_lock); heap_profile->ReleaseSnapshot( reinterpret_cast<HeapProfileTable::Snapshot*>(start_snapshot_)); } UnIgnoreObject(name_); delete[] name_; name_ = NULL; } delete lock_; } //---------------------------------------------------------------------- // HeapLeakChecker overall heap check components //---------------------------------------------------------------------- // static bool HeapLeakChecker::IsActive() { SpinLockHolder l(&heap_checker_lock); return heap_checker_on; } vector<HeapCleaner::void_function>* HeapCleaner::heap_cleanups_ = NULL; // When a HeapCleaner object is intialized, add its function to the static list // of cleaners to be run before leaks checking. HeapCleaner::HeapCleaner(void_function f) { if (heap_cleanups_ == NULL) heap_cleanups_ = new vector<HeapCleaner::void_function>; heap_cleanups_->push_back(f); } // Run all of the cleanup functions and delete the vector. void HeapCleaner::RunHeapCleanups() { if (!heap_cleanups_) return; for (int i = 0; i < heap_cleanups_->size(); i++) { void (*f)(void) = (*heap_cleanups_)[i]; f(); } delete heap_cleanups_; heap_cleanups_ = NULL; } // Program exit heap cleanup registered as a module object destructor. // Will not get executed when we crash on a signal. // void HeapLeakChecker_RunHeapCleanups() { if (FLAGS_heap_check == "local") // don't check heap in this mode return; { SpinLockHolder l(&heap_checker_lock); // can get here (via forks?) with other pids if (heap_checker_pid != getpid()) return; } HeapCleaner::RunHeapCleanups(); if (!FLAGS_heap_check_after_destructors) HeapLeakChecker::DoMainHeapCheck(); } static bool internal_init_start_has_run = false; // Called exactly once, before main() (but hopefully just before). // This picks a good unique name for the dumped leak checking heap profiles. // // Because we crash when InternalInitStart is called more than once, // it's fine that we hold heap_checker_lock only around pieces of // this function: this is still enough for thread-safety w.r.t. other functions // of this module. // We can't hold heap_checker_lock throughout because it would deadlock // on a memory allocation since our new/delete hooks can be on. // void HeapLeakChecker_InternalInitStart() { { SpinLockHolder l(&heap_checker_lock); RAW_CHECK(!internal_init_start_has_run, "Heap-check constructor called twice. Perhaps you both linked" " in the heap checker, and also used LD_PRELOAD to load it?"); internal_init_start_has_run = true; #ifdef ADDRESS_SANITIZER // AddressSanitizer's custom malloc conflicts with HeapChecker. FLAGS_heap_check = ""; #endif if (FLAGS_heap_check.empty()) { // turns out we do not need checking in the end; can stop profiling HeapLeakChecker::TurnItselfOffLocked(); return; } else if (RunningOnValgrind()) { // There is no point in trying -- we'll just fail. RAW_LOG(WARNING, "Can't run under Valgrind; will turn itself off"); HeapLeakChecker::TurnItselfOffLocked(); return; } } // Changing this to false can be useful when debugging heap-checker itself: if (!FLAGS_heap_check_run_under_gdb && IsDebuggerAttached()) { RAW_LOG(WARNING, "Someone is ptrace()ing us; will turn itself off"); SpinLockHolder l(&heap_checker_lock); HeapLeakChecker::TurnItselfOffLocked(); return; } { SpinLockHolder l(&heap_checker_lock); if (!constructor_heap_profiling) { RAW_LOG(FATAL, "Can not start so late. You have to enable heap checking " "with HEAPCHECK=<mode>."); } } // Set all flags RAW_DCHECK(FLAGS_heap_check_pointer_source_alignment > 0, ""); if (FLAGS_heap_check == "minimal") { // The least we can check. FLAGS_heap_check_before_constructors = false; // from after main // (ignore more) FLAGS_heap_check_after_destructors = false; // to after cleanup // (most data is live) FLAGS_heap_check_ignore_thread_live = true; // ignore all live FLAGS_heap_check_ignore_global_live = true; // ignore all live } else if (FLAGS_heap_check == "normal") { // Faster than 'minimal' and not much stricter. FLAGS_heap_check_before_constructors = true; // from no profile (fast) FLAGS_heap_check_after_destructors = false; // to after cleanup // (most data is live) FLAGS_heap_check_ignore_thread_live = true; // ignore all live FLAGS_heap_check_ignore_global_live = true; // ignore all live } else if (FLAGS_heap_check == "strict") { // A bit stricter than 'normal': global destructors must fully clean up // after themselves if they are present. FLAGS_heap_check_before_constructors = true; // from no profile (fast) FLAGS_heap_check_after_destructors = true; // to after destructors // (less data live) FLAGS_heap_check_ignore_thread_live = true; // ignore all live FLAGS_heap_check_ignore_global_live = true; // ignore all live } else if (FLAGS_heap_check == "draconian") { // Drop not very portable and not very exact live heap flooding. FLAGS_heap_check_before_constructors = true; // from no profile (fast) FLAGS_heap_check_after_destructors = true; // to after destructors // (need them) FLAGS_heap_check_ignore_thread_live = false; // no live flood (stricter) FLAGS_heap_check_ignore_global_live = false; // no live flood (stricter) } else if (FLAGS_heap_check == "as-is") { // do nothing: use other flags as is } else if (FLAGS_heap_check == "local") { // do nothing } else { RAW_LOG(FATAL, "Unsupported heap_check flag: %s", FLAGS_heap_check.c_str()); } // FreeBSD doesn't seem to honor atexit execution order: // http://code.google.com/p/gperftools/issues/detail?id=375 // Since heap-checking before destructors depends on atexit running // at the right time, on FreeBSD we always check after, even in the // less strict modes. This just means FreeBSD is always a bit // stricter in its checking than other OSes. // This now appears to be the case in other OSes as well; // so always check afterwards. FLAGS_heap_check_after_destructors = true; { SpinLockHolder l(&heap_checker_lock); RAW_DCHECK(heap_checker_pid == getpid(), ""); heap_checker_on = true; RAW_DCHECK(heap_profile, ""); HeapLeakChecker::ProcMapsResult pm_result = HeapLeakChecker::UseProcMapsLocked(HeapLeakChecker::DISABLE_LIBRARY_ALLOCS); // might neeed to do this more than once // if one later dynamically loads libraries that we want disabled if (pm_result != HeapLeakChecker::PROC_MAPS_USED) { // can't function HeapLeakChecker::TurnItselfOffLocked(); return; } } // make a good place and name for heap profile leak dumps string* profile_prefix = new string(FLAGS_heap_check_dump_directory + "/" + invocation_name()); // Finalize prefix for dumping leak checking profiles. const int32 our_pid = getpid(); // safest to call getpid() outside lock { SpinLockHolder l(&heap_checker_lock); // main_thread_pid might still be 0 if this function is being called before // global constructors. In that case, our pid *is* the main pid. if (main_thread_pid == 0) main_thread_pid = our_pid; } char pid_buf[15]; snprintf(pid_buf, sizeof(pid_buf), ".%d", main_thread_pid); *profile_prefix += pid_buf; { SpinLockHolder l(&heap_checker_lock); RAW_DCHECK(profile_name_prefix == NULL, ""); profile_name_prefix = profile_prefix; } // Make sure new/delete hooks are installed properly // and heap profiler is indeed able to keep track // of the objects being allocated. // We test this to make sure we are indeed checking for leaks. char* test_str = new char[5]; size_t size; { SpinLockHolder l(&heap_checker_lock); RAW_CHECK(heap_profile->FindAlloc(test_str, &size), "our own new/delete not linked?"); } delete[] test_str; { SpinLockHolder l(&heap_checker_lock); // This check can fail when it should not if another thread allocates // into this same spot right this moment, // which is unlikely since this code runs in InitGoogle. RAW_CHECK(!heap_profile->FindAlloc(test_str, &size), "our own new/delete not linked?"); } // If we crash in the above code, it probably means that // "nm <this_binary> | grep new" will show that tcmalloc's new/delete // implementation did not get linked-in into this binary // (i.e. nm will list __builtin_new and __builtin_vec_new as undefined). // If this happens, it is a BUILD bug to be fixed. RAW_VLOG(heap_checker_info_level, "WARNING: Perftools heap leak checker is active " "-- Performance may suffer"); if (FLAGS_heap_check != "local") { HeapLeakChecker* main_hc = new HeapLeakChecker(); SpinLockHolder l(&heap_checker_lock); RAW_DCHECK(main_heap_checker == NULL, "Repeated creation of main_heap_checker"); main_heap_checker = main_hc; do_main_heap_check = true; } { SpinLockHolder l(&heap_checker_lock); RAW_CHECK(heap_checker_on && constructor_heap_profiling, "Leak checking is expected to be fully turned on now"); } // For binaries built in debug mode, this will set release queue of // debugallocation.cc to 100M to make it less likely for real leaks to // be hidden due to reuse of heap memory object addresses. // Running a test with --malloc_reclaim_memory=0 would help find leaks even // better, but the test might run out of memory as a result. // The scenario is that a heap object at address X is allocated and freed, // but some other data-structure still retains a pointer to X. // Then the same heap memory is used for another object, which is leaked, // but the leak is not noticed due to the pointer to the original object at X. // TODO(csilvers): support this in some manner. #if 0 SetCommandLineOptionWithMode("max_free_queue_size", "104857600", // 100M SET_FLAG_IF_DEFAULT); #endif } // We want this to run early as well, but not so early as // ::BeforeConstructors (we want flag assignments to have already // happened, for instance). Initializer-registration does the trick. REGISTER_MODULE_INITIALIZER(init_start, HeapLeakChecker_InternalInitStart()); REGISTER_MODULE_DESTRUCTOR(init_start, HeapLeakChecker_RunHeapCleanups()); // static bool HeapLeakChecker::NoGlobalLeaksMaybeSymbolize( ShouldSymbolize should_symbolize) { // we never delete or change main_heap_checker once it's set: HeapLeakChecker* main_hc = GlobalChecker(); if (main_hc) { RAW_VLOG(10, "Checking for whole-program memory leaks"); return main_hc->DoNoLeaks(should_symbolize); } return true; } // static bool HeapLeakChecker::DoMainHeapCheck() { if (FLAGS_heap_check_delay_seconds > 0) { sleep(FLAGS_heap_check_delay_seconds); } { SpinLockHolder l(&heap_checker_lock); if (!do_main_heap_check) return false; RAW_DCHECK(heap_checker_pid == getpid(), ""); do_main_heap_check = false; // will do it now; no need to do it more } // The program is over, so it's safe to symbolize addresses (which // requires a fork) because no serious work is expected to be done // after this. Symbolizing is really useful -- knowing what // function has a leak is better than knowing just an address -- // and while we can only safely symbolize once in a program run, // now is the time (after all, there's no "later" that would be better). if (!NoGlobalLeaksMaybeSymbolize(SYMBOLIZE)) { if (FLAGS_heap_check_identify_leaks) { RAW_LOG(FATAL, "Whole-program memory leaks found."); } RAW_LOG(ERROR, "Exiting with error code (instead of crashing) " "because of whole-program memory leaks"); _exit(1); // we don't want to call atexit() routines! } return true; } // static HeapLeakChecker* HeapLeakChecker::GlobalChecker() { SpinLockHolder l(&heap_checker_lock); return main_heap_checker; } // static bool HeapLeakChecker::NoGlobalLeaks() { // symbolizing requires a fork, which isn't safe to do in general. return NoGlobalLeaksMaybeSymbolize(DO_NOT_SYMBOLIZE); } // static void HeapLeakChecker::CancelGlobalCheck() { SpinLockHolder l(&heap_checker_lock); if (do_main_heap_check) { RAW_VLOG(heap_checker_info_level, "Canceling the automatic at-exit whole-program memory leak check"); do_main_heap_check = false; } } // static void HeapLeakChecker::BeforeConstructorsLocked() { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); RAW_CHECK(!constructor_heap_profiling, "BeforeConstructorsLocked called multiple times"); #ifdef ADDRESS_SANITIZER // AddressSanitizer's custom malloc conflicts with HeapChecker. return; #endif // Set hooks early to crash if 'new' gets called before we make heap_profile, // and make sure no other hooks existed: RAW_CHECK(MallocHook::AddNewHook(&NewHook), ""); RAW_CHECK(MallocHook::AddDeleteHook(&DeleteHook), ""); constructor_heap_profiling = true; MemoryRegionMap::Init(1, /* use_buckets */ false); // Set up MemoryRegionMap with (at least) one caller stack frame to record // (important that it's done before HeapProfileTable creation below). Allocator::Init(); RAW_CHECK(heap_profile == NULL, ""); heap_profile = new(Allocator::Allocate(sizeof(HeapProfileTable))) HeapProfileTable(&Allocator::Allocate, &Allocator::Free, /* profile_mmap */ false); RAW_VLOG(10, "Starting tracking the heap"); heap_checker_on = true; } // static void HeapLeakChecker::TurnItselfOffLocked() { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); // Set FLAGS_heap_check to "", for users who test for it if (!FLAGS_heap_check.empty()) // be a noop in the common case FLAGS_heap_check.clear(); // because clear() could allocate memory if (constructor_heap_profiling) { RAW_CHECK(heap_checker_on, ""); RAW_VLOG(heap_checker_info_level, "Turning perftools heap leak checking off"); heap_checker_on = false; // Unset our hooks checking they were set: RAW_CHECK(MallocHook::RemoveNewHook(&NewHook), ""); RAW_CHECK(MallocHook::RemoveDeleteHook(&DeleteHook), ""); Allocator::DeleteAndNull(&heap_profile); // free our optional global data: Allocator::DeleteAndNullIfNot(&ignored_objects); Allocator::DeleteAndNullIfNot(&disabled_ranges); Allocator::DeleteAndNullIfNot(&global_region_caller_ranges); Allocator::Shutdown(); MemoryRegionMap::Shutdown(); } RAW_CHECK(!heap_checker_on, ""); } extern bool heap_leak_checker_bcad_variable; // in heap-checker-bcad.cc static bool has_called_before_constructors = false; // TODO(maxim): inline this function with // MallocHook_InitAtFirstAllocation_HeapLeakChecker, and also rename // HeapLeakChecker::BeforeConstructorsLocked. void HeapLeakChecker_BeforeConstructors() { SpinLockHolder l(&heap_checker_lock); // We can be called from several places: the first mmap/sbrk/alloc call // or the first global c-tor from heap-checker-bcad.cc: // Do not re-execute initialization: if (has_called_before_constructors) return; has_called_before_constructors = true; heap_checker_pid = getpid(); // set it always heap_leak_checker_bcad_variable = true; // just to reference it, so that heap-checker-bcad.o is linked in // This function can be called *very* early, before the normal // global-constructor that sets FLAGS_verbose. Set it manually now, // so the RAW_LOG messages here are controllable. const char* verbose_str = GetenvBeforeMain("PERFTOOLS_VERBOSE"); if (verbose_str && atoi(verbose_str)) { // different than the default of 0? FLAGS_verbose = atoi(verbose_str); } bool need_heap_check = true; // The user indicates a desire for heap-checking via the HEAPCHECK // environment variable. If it's not set, there's no way to do // heap-checking. if (!GetenvBeforeMain("HEAPCHECK")) { need_heap_check = false; } #ifdef HAVE_GETEUID if (need_heap_check && getuid() != geteuid()) { // heap-checker writes out files. Thus, for security reasons, we don't // recognize the env. var. to turn on heap-checking if we're setuid. RAW_LOG(WARNING, ("HeapChecker: ignoring HEAPCHECK because " "program seems to be setuid\n")); need_heap_check = false; } #endif if (need_heap_check) { HeapLeakChecker::BeforeConstructorsLocked(); } } // This function overrides the weak function defined in malloc_hook.cc and // called by one of the initial malloc hooks (malloc_hook.cc) when the very // first memory allocation or an mmap/sbrk happens. This ensures that // HeapLeakChecker is initialized and installs all its hooks early enough to // track absolutely all memory allocations and all memory region acquisitions // via mmap and sbrk. extern "C" void MallocHook_InitAtFirstAllocation_HeapLeakChecker() { HeapLeakChecker_BeforeConstructors(); } // This function is executed after all global object destructors run. void HeapLeakChecker_AfterDestructors() { { SpinLockHolder l(&heap_checker_lock); // can get here (via forks?) with other pids if (heap_checker_pid != getpid()) return; } if (FLAGS_heap_check_after_destructors) { if (HeapLeakChecker::DoMainHeapCheck()) { const struct timespec sleep_time = { 0, 500000000 }; // 500 ms nanosleep(&sleep_time, NULL); // Need this hack to wait for other pthreads to exit. // Otherwise tcmalloc find errors // on a free() call from pthreads. } } SpinLockHolder l(&heap_checker_lock); RAW_CHECK(!do_main_heap_check, "should have done it"); } //---------------------------------------------------------------------- // HeapLeakChecker disabling helpers //---------------------------------------------------------------------- // These functions are at the end of the file to prevent their inlining: // static void HeapLeakChecker::DisableChecksFromToLocked(const void* start_address, const void* end_address, int max_depth) { RAW_DCHECK(heap_checker_lock.IsHeld(), ""); RAW_DCHECK(start_address < end_address, ""); if (disabled_ranges == NULL) { disabled_ranges = new(Allocator::Allocate(sizeof(DisabledRangeMap))) DisabledRangeMap; } RangeValue value; value.start_address = AsInt(start_address); value.max_depth = max_depth; if (disabled_ranges->insert(make_pair(AsInt(end_address), value)).second) { RAW_VLOG(10, "Disabling leak checking in stack traces " "under frame addresses between %p..%p", start_address, end_address); } else { // check that this is just a verbatim repetition RangeValue const& val = disabled_ranges->find(AsInt(end_address))->second; if (val.max_depth != value.max_depth || val.start_address != value.start_address) { RAW_LOG(FATAL, "Two DisableChecksToHereFrom calls conflict: " "(%p, %p, %d) vs. (%p, %p, %d)", AsPtr(val.start_address), end_address, val.max_depth, start_address, end_address, max_depth); } } } // static inline bool HeapLeakChecker::HaveOnHeapLocked(const void** ptr, size_t* object_size) { // Commented-out because HaveOnHeapLocked is very performance-critical: // RAW_DCHECK(heap_checker_lock.IsHeld(), ""); const uintptr_t addr = AsInt(*ptr); if (heap_profile->FindInsideAlloc( *ptr, max_heap_object_size, ptr, object_size)) { RAW_VLOG(16, "Got pointer into %p at +%" PRIuPTR " offset", *ptr, addr - AsInt(*ptr)); return true; } return false; } // static const void* HeapLeakChecker::GetAllocCaller(void* ptr) { // this is used only in the unittest, so the heavy checks are fine HeapProfileTable::AllocInfo info; { SpinLockHolder l(&heap_checker_lock); RAW_CHECK(heap_profile->FindAllocDetails(ptr, &info), ""); } RAW_CHECK(info.stack_depth >= 1, ""); return info.call_stack[0]; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/heap-profile-table.h
.h
14,779
400
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // Maxim Lifantsev (refactoring) // #ifndef BASE_HEAP_PROFILE_TABLE_H_ #define BASE_HEAP_PROFILE_TABLE_H_ #include "addressmap-inl.h" #include "base/basictypes.h" #include "base/logging.h" // for RawFD #include "heap-profile-stats.h" // Table to maintain a heap profile data inside, // i.e. the set of currently active heap memory allocations. // thread-unsafe and non-reentrant code: // each instance object must be used by one thread // at a time w/o self-recursion. // // TODO(maxim): add a unittest for this class. class HeapProfileTable { public: // Extension to be used for heap pforile files. static const char kFileExt[]; // Longest stack trace we record. static const int kMaxStackDepth = 32; // data types ---------------------------- // Profile stats. typedef HeapProfileStats Stats; // Info we can return about an allocation. struct AllocInfo { size_t object_size; // size of the allocation const void* const* call_stack; // call stack that made the allocation call int stack_depth; // depth of call_stack bool live; bool ignored; }; // Info we return about an allocation context. // An allocation context is a unique caller stack trace // of an allocation operation. struct AllocContextInfo : public Stats { int stack_depth; // Depth of stack trace const void* const* call_stack; // Stack trace }; // Memory (de)allocator interface we'll use. typedef void* (*Allocator)(size_t size); typedef void (*DeAllocator)(void* ptr); // interface --------------------------- HeapProfileTable(Allocator alloc, DeAllocator dealloc, bool profile_mmap); ~HeapProfileTable(); // Collect the stack trace for the function that asked to do the // allocation for passing to RecordAlloc() below. // // The stack trace is stored in 'stack'. The stack depth is returned. // // 'skip_count' gives the number of stack frames between this call // and the memory allocation function. static int GetCallerStackTrace(int skip_count, void* stack[kMaxStackDepth]); // Record an allocation at 'ptr' of 'bytes' bytes. 'stack_depth' // and 'call_stack' identifying the function that requested the // allocation. They can be generated using GetCallerStackTrace() above. void RecordAlloc(const void* ptr, size_t bytes, int stack_depth, const void* const call_stack[]); // Record the deallocation of memory at 'ptr'. void RecordFree(const void* ptr); // Return true iff we have recorded an allocation at 'ptr'. // If yes, fill *object_size with the allocation byte size. bool FindAlloc(const void* ptr, size_t* object_size) const; // Same as FindAlloc, but fills all of *info. bool FindAllocDetails(const void* ptr, AllocInfo* info) const; // Return true iff "ptr" points into a recorded allocation // If yes, fill *object_ptr with the actual allocation address // and *object_size with the allocation byte size. // max_size specifies largest currently possible allocation size. bool FindInsideAlloc(const void* ptr, size_t max_size, const void** object_ptr, size_t* object_size) const; // If "ptr" points to a recorded allocation and it's not marked as live // mark it as live and return true. Else return false. // All allocations start as non-live. bool MarkAsLive(const void* ptr); // If "ptr" points to a recorded allocation, mark it as "ignored". // Ignored objects are treated like other objects, except that they // are skipped in heap checking reports. void MarkAsIgnored(const void* ptr); // Return current total (de)allocation statistics. It doesn't contain // mmap'ed regions. const Stats& total() const { return total_; } // Allocation data iteration callback: gets passed object pointer and // fully-filled AllocInfo. typedef void (*AllocIterator)(const void* ptr, const AllocInfo& info); // Iterate over the allocation profile data calling "callback" // for every allocation. void IterateAllocs(AllocIterator callback) const { address_map_->Iterate(MapArgsAllocIterator, callback); } // Allocation context profile data iteration callback typedef void (*AllocContextIterator)(const AllocContextInfo& info); // Iterate over the allocation context profile data calling "callback" // for every allocation context. Allocation contexts are ordered by the // size of allocated space. void IterateOrderedAllocContexts(AllocContextIterator callback) const; // Fill profile data into buffer 'buf' of size 'size' // and return the actual size occupied by the dump in 'buf'. // The profile buckets are dumped in the decreasing order // of currently allocated bytes. // We do not provision for 0-terminating 'buf'. int FillOrderedProfile(char buf[], int size) const; // Cleanup any old profile files matching prefix + ".*" + kFileExt. static void CleanupOldProfiles(const char* prefix); // Return a snapshot of the current contents of *this. // Caller must call ReleaseSnapshot() on result when no longer needed. // The result is only valid while this exists and until // the snapshot is discarded by calling ReleaseSnapshot(). class Snapshot; Snapshot* TakeSnapshot(); // Release a previously taken snapshot. snapshot must not // be used after this call. void ReleaseSnapshot(Snapshot* snapshot); // Return a snapshot of every non-live, non-ignored object in *this. // If "base" is non-NULL, skip any objects present in "base". // As a side-effect, clears the "live" bit on every live object in *this. // Caller must call ReleaseSnapshot() on result when no longer needed. Snapshot* NonLiveSnapshot(Snapshot* base); private: // data types ---------------------------- // Hash table bucket to hold (de)allocation stats // for a given allocation call stack trace. typedef HeapProfileBucket Bucket; // Info stored in the address map struct AllocValue { // Access to the stack-trace bucket Bucket* bucket() const { return reinterpret_cast<Bucket*>(bucket_rep & ~uintptr_t(kMask)); } // This also does set_live(false). void set_bucket(Bucket* b) { bucket_rep = reinterpret_cast<uintptr_t>(b); } size_t bytes; // Number of bytes in this allocation // Access to the allocation liveness flag (for leak checking) bool live() const { return bucket_rep & kLive; } void set_live(bool l) { bucket_rep = (bucket_rep & ~uintptr_t(kLive)) | (l ? kLive : 0); } // Should this allocation be ignored if it looks like a leak? bool ignore() const { return bucket_rep & kIgnore; } void set_ignore(bool r) { bucket_rep = (bucket_rep & ~uintptr_t(kIgnore)) | (r ? kIgnore : 0); } private: // We store a few bits in the bottom bits of bucket_rep. // (Alignment is at least four, so we have at least two bits.) static const int kLive = 1; static const int kIgnore = 2; static const int kMask = kLive | kIgnore; uintptr_t bucket_rep; }; // helper for FindInsideAlloc static size_t AllocValueSize(const AllocValue& v) { return v.bytes; } typedef AddressMap<AllocValue> AllocationMap; // Arguments that need to be passed DumpBucketIterator callback below. struct BufferArgs { BufferArgs(char* buf_arg, int buflen_arg, int bufsize_arg) : buf(buf_arg), buflen(buflen_arg), bufsize(bufsize_arg) { } char* buf; int buflen; int bufsize; DISALLOW_COPY_AND_ASSIGN(BufferArgs); }; // Arguments that need to be passed DumpNonLiveIterator callback below. struct DumpArgs { DumpArgs(RawFD fd_arg, Stats* profile_stats_arg) : fd(fd_arg), profile_stats(profile_stats_arg) { } RawFD fd; // file to write to Stats* profile_stats; // stats to update (may be NULL) }; // helpers ---------------------------- // Unparse bucket b and print its portion of profile dump into buf. // We return the amount of space in buf that we use. We start printing // at buf + buflen, and promise not to go beyond buf + bufsize. // We do not provision for 0-terminating 'buf'. // // If profile_stats is non-NULL, we update *profile_stats by // counting bucket b. // // "extra" is appended to the unparsed bucket. Typically it is empty, // but may be set to something like " heapprofile" for the total // bucket to indicate the type of the profile. static int UnparseBucket(const Bucket& b, char* buf, int buflen, int bufsize, const char* extra, Stats* profile_stats); // Get the bucket for the caller stack trace 'key' of depth 'depth' // creating the bucket if needed. Bucket* GetBucket(int depth, const void* const key[]); // Helper for IterateAllocs to do callback signature conversion // from AllocationMap::Iterate to AllocIterator. static void MapArgsAllocIterator(const void* ptr, AllocValue* v, AllocIterator callback) { AllocInfo info; info.object_size = v->bytes; info.call_stack = v->bucket()->stack; info.stack_depth = v->bucket()->depth; info.live = v->live(); info.ignored = v->ignore(); callback(ptr, info); } // Helper to dump a bucket. inline static void DumpBucketIterator(const Bucket* bucket, BufferArgs* args); // Helper for DumpNonLiveProfile to do object-granularity // heap profile dumping. It gets passed to AllocationMap::Iterate. inline static void DumpNonLiveIterator(const void* ptr, AllocValue* v, const DumpArgs& args); // Helper for IterateOrderedAllocContexts and FillOrderedProfile. // Creates a sorted list of Buckets whose length is num_buckets_. // The caller is responsible for deallocating the returned list. Bucket** MakeSortedBucketList() const; // Helper for TakeSnapshot. Saves object to snapshot. static void AddToSnapshot(const void* ptr, AllocValue* v, Snapshot* s); // Arguments passed to AddIfNonLive struct AddNonLiveArgs { Snapshot* dest; Snapshot* base; }; // Helper for NonLiveSnapshot. Adds the object to the destination // snapshot if it is non-live. static void AddIfNonLive(const void* ptr, AllocValue* v, AddNonLiveArgs* arg); // Write contents of "*allocations" as a heap profile to // "file_name". "total" must contain the total of all entries in // "*allocations". static bool WriteProfile(const char* file_name, const Bucket& total, AllocationMap* allocations); // data ---------------------------- // Memory (de)allocator that we use. Allocator alloc_; DeAllocator dealloc_; // Overall profile stats; we use only the Stats part, // but make it a Bucket to pass to UnparseBucket. Bucket total_; bool profile_mmap_; // Bucket hash table for malloc. // We hand-craft one instead of using one of the pre-written // ones because we do not want to use malloc when operating on the table. // It is only few lines of code, so no big deal. Bucket** bucket_table_; int num_buckets_; // Map of all currently allocated objects and mapped regions we know about. AllocationMap* address_map_; DISALLOW_COPY_AND_ASSIGN(HeapProfileTable); }; class HeapProfileTable::Snapshot { public: const Stats& total() const { return total_; } // Report anything in this snapshot as a leak. // May use new/delete for temporary storage. // If should_symbolize is true, will fork (which is not threadsafe) // to turn addresses into symbol names. Set to false for maximum safety. // Also writes a heap profile to "filename" that contains // all of the objects in this snapshot. void ReportLeaks(const char* checker_name, const char* filename, bool should_symbolize); // Report the addresses of all leaked objects. // May use new/delete for temporary storage. void ReportIndividualObjects(); bool Empty() const { return (total_.allocs == 0) && (total_.alloc_size == 0); } private: friend class HeapProfileTable; // Total count/size are stored in a Bucket so we can reuse UnparseBucket Bucket total_; // We share the Buckets managed by the parent table, but have our // own object->bucket map. AllocationMap map_; Snapshot(Allocator alloc, DeAllocator dealloc) : map_(alloc, dealloc) { memset(&total_, 0, sizeof(total_)); } // Callback used to populate a Snapshot object with entries found // in another allocation map. inline void Add(const void* ptr, const AllocValue& v) { map_.Insert(ptr, v); total_.allocs++; total_.alloc_size += v.bytes; } // Helpers for sorting and generating leak reports struct Entry; struct ReportState; static void ReportCallback(const void* ptr, AllocValue* v, ReportState*); static void ReportObject(const void* ptr, AllocValue* v, char*); DISALLOW_COPY_AND_ASSIGN(Snapshot); }; #endif // BASE_HEAP_PROFILE_TABLE_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_instrument-inl.h
.h
5,611
156
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2013, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Jean Lee <xiaoyur347@gmail.com> // based on gcc Code-Gen-Options "-finstrument-functions" listed in // http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html . // Should run configure with CXXFLAGS="-finstrument-functions". // This file is a backtrace implementation for systems : // * The glibc implementation of backtrace() may cause a call to malloc, // and cause a deadlock in HeapProfiler. // * The libunwind implementation prints no backtrace. // The backtrace arrays are stored in "thread_back_trace" variable. // Maybe to use thread local storage is better and should save memorys. #ifndef BASE_STACKTRACE_INSTRUMENT_INL_H_ #define BASE_STACKTRACE_INSTRUMENT_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include <execinfo.h> #include <string.h> #include <unistd.h> #include <sys/syscall.h> #include "gperftools/stacktrace.h" #define gettid() syscall(__NR_gettid) #ifndef __x86_64__ #define MAX_THREAD (32768) #else #define MAX_THREAD (65536) #endif #define MAX_DEPTH (30) #define ATTRIBUTE_NOINSTRUMENT __attribute__ ((no_instrument_function)) typedef struct { int stack_depth; void* frame[MAX_DEPTH]; }BACK_TRACE; static BACK_TRACE thread_back_trace[MAX_THREAD]; extern "C" { void __cyg_profile_func_enter(void *func_address, void *call_site) ATTRIBUTE_NOINSTRUMENT; void __cyg_profile_func_enter(void *func_address, void *call_site) { (void)func_address; BACK_TRACE* backtrace = thread_back_trace + gettid(); int stack_depth = backtrace->stack_depth; backtrace->stack_depth = stack_depth + 1; if ( stack_depth >= MAX_DEPTH ) { return; } backtrace->frame[stack_depth] = call_site; } void __cyg_profile_func_exit(void *func_address, void *call_site) ATTRIBUTE_NOINSTRUMENT; void __cyg_profile_func_exit(void *func_address, void *call_site) { (void)func_address; (void)call_site; BACK_TRACE* backtrace = thread_back_trace + gettid(); int stack_depth = backtrace->stack_depth; backtrace->stack_depth = stack_depth - 1; if ( stack_depth >= MAX_DEPTH ) { return; } backtrace->frame[stack_depth] = 0; } } // extern "C" static int cyg_backtrace(void **buffer, int size) { BACK_TRACE* backtrace = thread_back_trace + gettid(); int stack_depth = backtrace->stack_depth; if ( stack_depth >= MAX_DEPTH ) { stack_depth = MAX_DEPTH; } int nSize = (size > stack_depth) ? stack_depth : size; for (int i = 0; i < nSize; i++) { buffer[i] = backtrace->frame[nSize - i - 1]; } return nSize; } #endif // BASE_STACKTRACE_INSTRUMENT_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) static int GET_STACK_TRACE_OR_FRAMES { static const int kStackLength = 64; void * stack[kStackLength]; int size; memset(stack, 0, sizeof(stack)); size = cyg_backtrace(stack, kStackLength); skip_count += 2; // we want to skip the current and parent frame as well int result_count = size - skip_count; if (result_count < 0) result_count = 0; if (result_count > max_depth) result_count = max_depth; for (int i = 0; i < result_count; i++) result[i] = stack[i + skip_count]; #if IS_STACK_FRAMES // No implementation for finding out the stack frame sizes yet. memset(sizes, 0, sizeof(*sizes) * result_count); #endif return result_count; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_arm-inl.h
.h
6,124
149
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Doug Kwan // This is inspired by Craig Silverstein's PowerPC stacktrace code. // #ifndef BASE_STACKTRACE_ARM_INL_H_ #define BASE_STACKTRACE_ARM_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include <stdint.h> // for uintptr_t #include "base/basictypes.h" // for NULL #include <gperftools/stacktrace.h> // WARNING: // This only works if all your code is in either ARM or THUMB mode. With // interworking, the frame pointer of the caller can either be in r11 (ARM // mode) or r7 (THUMB mode). A callee only saves the frame pointer of its // mode in a fixed location on its stack frame. If the caller is a different // mode, there is no easy way to find the frame pointer. It can either be // still in the designated register or saved on stack along with other callee // saved registers. // Given a pointer to a stack frame, locate and return the calling // stackframe, or return NULL if no stackframe can be found. Perform sanity // checks (the strictness of which is controlled by the boolean parameter // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. template<bool STRICT_UNWINDING> static void **NextStackFrame(void **old_sp) { void **new_sp = (void**) old_sp[-1]; // Check that the transition from frame pointer old_sp to frame // pointer new_sp isn't clearly bogus if (STRICT_UNWINDING) { // With the stack growing downwards, older stack frame must be // at a greater address that the current one. if (new_sp <= old_sp) return NULL; // Assume stack frames larger than 100,000 bytes are bogus. if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return NULL; } else { // In the non-strict mode, allow discontiguous stack frames. // (alternate-signal-stacks for example). if (new_sp == old_sp) return NULL; // And allow frames upto about 1MB. if ((new_sp > old_sp) && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return NULL; } if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return NULL; return new_sp; } // This ensures that GetStackTrace stes up the Link Register properly. #ifdef __GNUC__ void StacktraceArmDummyFunction() __attribute__((noinline)); void StacktraceArmDummyFunction() { __asm__ volatile(""); } #else # error StacktraceArmDummyFunction() needs to be ported to this platform. #endif #endif // BASE_STACKTRACE_ARM_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) static int GET_STACK_TRACE_OR_FRAMES { #ifdef __GNUC__ void **sp = reinterpret_cast<void**>(__builtin_frame_address(0)); #else # error reading stack point not yet supported on this platform. #endif // On ARM, the return address is stored in the link register (r14). // This is not saved on the stack frame of a leaf function. To // simplify code that reads return addresses, we call a dummy // function so that the return address of this function is also // stored in the stack frame. This works at least for gcc. StacktraceArmDummyFunction(); skip_count++; // skip parent frame due to indirection in stacktrace.cc int n = 0; while (sp && n < max_depth) { // The GetStackFrames routine is called when we are in some // informational context (the failure signal handler for example). // Use the non-strict unwinding rules to produce a stack trace // that is as complete as possible (even if it contains a few bogus // entries in some rare cases). void **next_sp = NextStackFrame<IS_STACK_FRAMES == 0>(sp); if (skip_count > 0) { skip_count--; } else { result[n] = *sp; #if IS_STACK_FRAMES if (next_sp > sp) { sizes[n] = (uintptr_t)next_sp - (uintptr_t)sp; } else { // A frame-size of 0 is used to indicate unknown frame size. sizes[n] = 0; } #endif n++; } sp = next_sp; } return n; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/memory_region_map.cc
.cc
34,606
839
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- /* Copyright (c) 2006, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Maxim Lifantsev */ // // Background and key design points of MemoryRegionMap. // // MemoryRegionMap is a low-level module with quite atypical requirements that // result in some degree of non-triviality of the implementation and design. // // MemoryRegionMap collects info about *all* memory regions created with // mmap, munmap, mremap, sbrk. // They key word above is 'all': all that are happening in a process // during its lifetime frequently starting even before global object // constructor execution. // // This is needed by the primary client of MemoryRegionMap: // HeapLeakChecker uses the regions and the associated stack traces // to figure out what part of the memory is the heap: // if MemoryRegionMap were to miss some (early) regions, leak checking would // stop working correctly. // // To accomplish the goal of functioning before/during global object // constructor execution MemoryRegionMap is done as a singleton service // that relies on own on-demand initialized static constructor-less data, // and only relies on other low-level modules that can also function properly // even before global object constructors run. // // Accomplishing the goal of collecting data about all mmap, munmap, mremap, // sbrk occurrences is a more involved: conceptually to do this one needs to // record some bits of data in particular about any mmap or sbrk call, // but to do that one needs to allocate memory for that data at some point, // but all memory allocations in the end themselves come from an mmap // or sbrk call (that's how the address space of the process grows). // // Also note that we need to do all the above recording from // within an mmap/sbrk hook which is sometimes/frequently is made by a memory // allocator, including the allocator MemoryRegionMap itself must rely on. // In the case of heap-checker usage this includes even the very first // mmap/sbrk call happening in the program: heap-checker gets activated due to // a link-time installed mmap/sbrk hook and it initializes MemoryRegionMap // and asks it to record info about this very first call right from that // very first hook invocation. // // MemoryRegionMap is doing its memory allocations via LowLevelAlloc: // unlike more complex standard memory allocator, LowLevelAlloc cooperates with // MemoryRegionMap by not holding any of its own locks while it calls mmap // to get memory, thus we are able to call LowLevelAlloc from // our mmap/sbrk hooks without causing a deadlock in it. // For the same reason of deadlock prevention the locking in MemoryRegionMap // itself is write-recursive which is an exception to Google's mutex usage. // // We still need to break the infinite cycle of mmap calling our hook, // which asks LowLevelAlloc for memory to record this mmap, // which (sometimes) causes mmap, which calls our hook, and so on. // We do this as follows: on a recursive call of MemoryRegionMap's // mmap/sbrk/mremap hook we record the data about the allocation in a // static fixed-sized stack (saved_regions and saved_buckets), when the // recursion unwinds but before returning from the outer hook call we unwind // this stack and move the data from saved_regions and saved_buckets to its // permanent place in the RegionSet and "bucket_table" respectively, // which can cause more allocations and mmap-s and recursion and unwinding, // but the whole process ends eventually due to the fact that for the small // allocations we are doing LowLevelAlloc reuses one mmap call and parcels out // the memory it created to satisfy several of our allocation requests. // // ========================================================================= // #include <config.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #ifdef HAVE_MMAP #include <sys/mman.h> #elif !defined(MAP_FAILED) #define MAP_FAILED -1 // the only thing we need from mman.h #endif #ifdef HAVE_PTHREAD #include <pthread.h> // for pthread_t, pthread_self() #endif #include <stddef.h> #include <algorithm> #include <set> #include "memory_region_map.h" #include "base/googleinit.h" #include "base/logging.h" #include "base/low_level_alloc.h" #include "malloc_hook-inl.h" #include <gperftools/stacktrace.h> #include <gperftools/malloc_hook.h> // MREMAP_FIXED is a linux extension. How it's used in this file, // setting it to 0 is equivalent to saying, "This feature isn't // supported", which is right. #ifndef MREMAP_FIXED # define MREMAP_FIXED 0 #endif using std::max; // ========================================================================= // int MemoryRegionMap::client_count_ = 0; int MemoryRegionMap::max_stack_depth_ = 0; MemoryRegionMap::RegionSet* MemoryRegionMap::regions_ = NULL; LowLevelAlloc::Arena* MemoryRegionMap::arena_ = NULL; SpinLock MemoryRegionMap::lock_(SpinLock::LINKER_INITIALIZED); SpinLock MemoryRegionMap::owner_lock_( // ACQUIRED_AFTER(lock_) SpinLock::LINKER_INITIALIZED); int MemoryRegionMap::recursion_count_ = 0; // GUARDED_BY(owner_lock_) pthread_t MemoryRegionMap::lock_owner_tid_; // GUARDED_BY(owner_lock_) int64 MemoryRegionMap::map_size_ = 0; int64 MemoryRegionMap::unmap_size_ = 0; HeapProfileBucket** MemoryRegionMap::bucket_table_ = NULL; // GUARDED_BY(lock_) int MemoryRegionMap::num_buckets_ = 0; // GUARDED_BY(lock_) int MemoryRegionMap::saved_buckets_count_ = 0; // GUARDED_BY(lock_) HeapProfileBucket MemoryRegionMap::saved_buckets_[20]; // GUARDED_BY(lock_) // GUARDED_BY(lock_) const void* MemoryRegionMap::saved_buckets_keys_[20][kMaxStackDepth]; // ========================================================================= // // Simple hook into execution of global object constructors, // so that we do not call pthread_self() when it does not yet work. static bool libpthread_initialized = false; REGISTER_MODULE_INITIALIZER(libpthread_initialized_setter, libpthread_initialized = true); static inline bool current_thread_is(pthread_t should_be) { // Before main() runs, there's only one thread, so we're always that thread if (!libpthread_initialized) return true; // this starts working only sometime well into global constructor execution: return pthread_equal(pthread_self(), should_be); } // ========================================================================= // // Constructor-less place-holder to store a RegionSet in. union MemoryRegionMap::RegionSetRep { char rep[sizeof(RegionSet)]; void* align_it; // do not need a better alignment for 'rep' than this RegionSet* region_set() { return reinterpret_cast<RegionSet*>(rep); } }; // The bytes where MemoryRegionMap::regions_ will point to. // We use RegionSetRep with noop c-tor so that global construction // does not interfere. static MemoryRegionMap::RegionSetRep regions_rep; // ========================================================================= // // Has InsertRegionLocked been called recursively // (or rather should we *not* use regions_ to record a hooked mmap). static bool recursive_insert = false; void MemoryRegionMap::Init(int max_stack_depth, bool use_buckets) { RAW_VLOG(10, "MemoryRegionMap Init"); RAW_CHECK(max_stack_depth >= 0, ""); // Make sure we don't overflow the memory in region stacks: RAW_CHECK(max_stack_depth <= kMaxStackDepth, "need to increase kMaxStackDepth?"); Lock(); client_count_ += 1; max_stack_depth_ = max(max_stack_depth_, max_stack_depth); if (client_count_ > 1) { // not first client: already did initialization-proper Unlock(); RAW_VLOG(10, "MemoryRegionMap Init increment done"); return; } // Set our hooks and make sure they were installed: RAW_CHECK(MallocHook::AddMmapHook(&MmapHook), ""); RAW_CHECK(MallocHook::AddMremapHook(&MremapHook), ""); RAW_CHECK(MallocHook::AddSbrkHook(&SbrkHook), ""); RAW_CHECK(MallocHook::AddMunmapHook(&MunmapHook), ""); // We need to set recursive_insert since the NewArena call itself // will already do some allocations with mmap which our hooks will catch // recursive_insert allows us to buffer info about these mmap calls. // Note that Init() can be (and is) sometimes called // already from within an mmap/sbrk hook. recursive_insert = true; arena_ = LowLevelAlloc::NewArena(0, LowLevelAlloc::DefaultArena()); recursive_insert = false; HandleSavedRegionsLocked(&InsertRegionLocked); // flush the buffered ones // Can't instead use HandleSavedRegionsLocked(&DoInsertRegionLocked) before // recursive_insert = false; as InsertRegionLocked will also construct // regions_ on demand for us. if (use_buckets) { const int table_bytes = kHashTableSize * sizeof(*bucket_table_); recursive_insert = true; bucket_table_ = static_cast<HeapProfileBucket**>( MyAllocator::Allocate(table_bytes)); recursive_insert = false; memset(bucket_table_, 0, table_bytes); num_buckets_ = 0; } if (regions_ == NULL) { // init regions_ InitRegionSetLocked(); } Unlock(); RAW_VLOG(10, "MemoryRegionMap Init done"); } bool MemoryRegionMap::Shutdown() { RAW_VLOG(10, "MemoryRegionMap Shutdown"); Lock(); RAW_CHECK(client_count_ > 0, ""); client_count_ -= 1; if (client_count_ != 0) { // not last client; need not really shutdown Unlock(); RAW_VLOG(10, "MemoryRegionMap Shutdown decrement done"); return true; } if (bucket_table_ != NULL) { for (int i = 0; i < kHashTableSize; i++) { for (HeapProfileBucket* curr = bucket_table_[i]; curr != 0; /**/) { HeapProfileBucket* bucket = curr; curr = curr->next; MyAllocator::Free(bucket->stack, 0); MyAllocator::Free(bucket, 0); } } MyAllocator::Free(bucket_table_, 0); num_buckets_ = 0; bucket_table_ = NULL; } RAW_CHECK(MallocHook::RemoveMmapHook(&MmapHook), ""); RAW_CHECK(MallocHook::RemoveMremapHook(&MremapHook), ""); RAW_CHECK(MallocHook::RemoveSbrkHook(&SbrkHook), ""); RAW_CHECK(MallocHook::RemoveMunmapHook(&MunmapHook), ""); if (regions_) regions_->~RegionSet(); regions_ = NULL; bool deleted_arena = LowLevelAlloc::DeleteArena(arena_); if (deleted_arena) { arena_ = 0; } else { RAW_LOG(WARNING, "Can't delete LowLevelAlloc arena: it's being used"); } Unlock(); RAW_VLOG(10, "MemoryRegionMap Shutdown done"); return deleted_arena; } bool MemoryRegionMap::IsRecordingLocked() { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); return client_count_ > 0; } // Invariants (once libpthread_initialized is true): // * While lock_ is not held, recursion_count_ is 0 (and // lock_owner_tid_ is the previous owner, but we don't rely on // that). // * recursion_count_ and lock_owner_tid_ are only written while // both lock_ and owner_lock_ are held. They may be read under // just owner_lock_. // * At entry and exit of Lock() and Unlock(), the current thread // owns lock_ iff pthread_equal(lock_owner_tid_, pthread_self()) // && recursion_count_ > 0. void MemoryRegionMap::Lock() { { SpinLockHolder l(&owner_lock_); if (recursion_count_ > 0 && current_thread_is(lock_owner_tid_)) { RAW_CHECK(lock_.IsHeld(), "Invariants violated"); recursion_count_++; RAW_CHECK(recursion_count_ <= 5, "recursive lock nesting unexpectedly deep"); return; } } lock_.Lock(); { SpinLockHolder l(&owner_lock_); RAW_CHECK(recursion_count_ == 0, "Last Unlock didn't reset recursion_count_"); if (libpthread_initialized) lock_owner_tid_ = pthread_self(); recursion_count_ = 1; } } void MemoryRegionMap::Unlock() { SpinLockHolder l(&owner_lock_); RAW_CHECK(recursion_count_ > 0, "unlock when not held"); RAW_CHECK(lock_.IsHeld(), "unlock when not held, and recursion_count_ is wrong"); RAW_CHECK(current_thread_is(lock_owner_tid_), "unlock by non-holder"); recursion_count_--; if (recursion_count_ == 0) { lock_.Unlock(); } } bool MemoryRegionMap::LockIsHeld() { SpinLockHolder l(&owner_lock_); return lock_.IsHeld() && current_thread_is(lock_owner_tid_); } const MemoryRegionMap::Region* MemoryRegionMap::DoFindRegionLocked(uintptr_t addr) { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); if (regions_ != NULL) { Region sample; sample.SetRegionSetKey(addr); RegionSet::iterator region = regions_->lower_bound(sample); if (region != regions_->end()) { RAW_CHECK(addr <= region->end_addr, ""); if (region->start_addr <= addr && addr < region->end_addr) { return &(*region); } } } return NULL; } bool MemoryRegionMap::FindRegion(uintptr_t addr, Region* result) { Lock(); const Region* region = DoFindRegionLocked(addr); if (region != NULL) *result = *region; // create it as an independent copy Unlock(); return region != NULL; } bool MemoryRegionMap::FindAndMarkStackRegion(uintptr_t stack_top, Region* result) { Lock(); const Region* region = DoFindRegionLocked(stack_top); if (region != NULL) { RAW_VLOG(10, "Stack at %p is inside region %p..%p", reinterpret_cast<void*>(stack_top), reinterpret_cast<void*>(region->start_addr), reinterpret_cast<void*>(region->end_addr)); const_cast<Region*>(region)->set_is_stack(); // now we know // cast is safe (set_is_stack does not change the set ordering key) *result = *region; // create *result as an independent copy } Unlock(); return region != NULL; } HeapProfileBucket* MemoryRegionMap::GetBucket(int depth, const void* const key[]) { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); // Make hash-value uintptr_t hash = 0; for (int i = 0; i < depth; i++) { hash += reinterpret_cast<uintptr_t>(key[i]); hash += hash << 10; hash ^= hash >> 6; } hash += hash << 3; hash ^= hash >> 11; // Lookup stack trace in table unsigned int hash_index = (static_cast<unsigned int>(hash)) % kHashTableSize; for (HeapProfileBucket* bucket = bucket_table_[hash_index]; bucket != 0; bucket = bucket->next) { if ((bucket->hash == hash) && (bucket->depth == depth) && std::equal(key, key + depth, bucket->stack)) { return bucket; } } // Create new bucket const size_t key_size = sizeof(key[0]) * depth; HeapProfileBucket* bucket; if (recursive_insert) { // recursion: save in saved_buckets_ const void** key_copy = saved_buckets_keys_[saved_buckets_count_]; std::copy(key, key + depth, key_copy); bucket = &saved_buckets_[saved_buckets_count_]; memset(bucket, 0, sizeof(*bucket)); ++saved_buckets_count_; bucket->stack = key_copy; bucket->next = NULL; } else { recursive_insert = true; const void** key_copy = static_cast<const void**>( MyAllocator::Allocate(key_size)); recursive_insert = false; std::copy(key, key + depth, key_copy); recursive_insert = true; bucket = static_cast<HeapProfileBucket*>( MyAllocator::Allocate(sizeof(HeapProfileBucket))); recursive_insert = false; memset(bucket, 0, sizeof(*bucket)); bucket->stack = key_copy; bucket->next = bucket_table_[hash_index]; } bucket->hash = hash; bucket->depth = depth; bucket_table_[hash_index] = bucket; ++num_buckets_; return bucket; } MemoryRegionMap::RegionIterator MemoryRegionMap::BeginRegionLocked() { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); RAW_CHECK(regions_ != NULL, ""); return regions_->begin(); } MemoryRegionMap::RegionIterator MemoryRegionMap::EndRegionLocked() { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); RAW_CHECK(regions_ != NULL, ""); return regions_->end(); } inline void MemoryRegionMap::DoInsertRegionLocked(const Region& region) { RAW_VLOG(12, "Inserting region %p..%p from %p", reinterpret_cast<void*>(region.start_addr), reinterpret_cast<void*>(region.end_addr), reinterpret_cast<void*>(region.caller())); RegionSet::const_iterator i = regions_->lower_bound(region); if (i != regions_->end() && i->start_addr <= region.start_addr) { RAW_DCHECK(region.end_addr <= i->end_addr, ""); // lower_bound ensures this return; // 'region' is a subset of an already recorded region; do nothing // We can be stricter and allow this only when *i has been created via // an mmap with MAP_NORESERVE flag set. } if (DEBUG_MODE) { RAW_CHECK(i == regions_->end() || !region.Overlaps(*i), "Wow, overlapping memory regions"); Region sample; sample.SetRegionSetKey(region.start_addr); i = regions_->lower_bound(sample); RAW_CHECK(i == regions_->end() || !region.Overlaps(*i), "Wow, overlapping memory regions"); } region.AssertIsConsistent(); // just making sure // This inserts and allocates permanent storage for region // and its call stack data: it's safe to do it now: regions_->insert(region); RAW_VLOG(12, "Inserted region %p..%p :", reinterpret_cast<void*>(region.start_addr), reinterpret_cast<void*>(region.end_addr)); if (VLOG_IS_ON(12)) LogAllLocked(); } // These variables are local to MemoryRegionMap::InsertRegionLocked() // and MemoryRegionMap::HandleSavedRegionsLocked() // and are file-level to ensure that they are initialized at load time. // Number of unprocessed region inserts. static int saved_regions_count = 0; // Unprocessed inserts (must be big enough to hold all allocations that can // be caused by a InsertRegionLocked call). // Region has no constructor, so that c-tor execution does not interfere // with the any-time use of the static memory behind saved_regions. static MemoryRegionMap::Region saved_regions[20]; inline void MemoryRegionMap::HandleSavedRegionsLocked( void (*insert_func)(const Region& region)) { while (saved_regions_count > 0) { // Making a local-var copy of the region argument to insert_func // including its stack (w/o doing any memory allocations) is important: // in many cases the memory in saved_regions // will get written-to during the (*insert_func)(r) call below. Region r = saved_regions[--saved_regions_count]; (*insert_func)(r); } } void MemoryRegionMap::RestoreSavedBucketsLocked() { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); while (saved_buckets_count_ > 0) { HeapProfileBucket bucket = saved_buckets_[--saved_buckets_count_]; unsigned int hash_index = static_cast<unsigned int>(bucket.hash) % kHashTableSize; bool is_found = false; for (HeapProfileBucket* curr = bucket_table_[hash_index]; curr != 0; curr = curr->next) { if ((curr->hash == bucket.hash) && (curr->depth == bucket.depth) && std::equal(bucket.stack, bucket.stack + bucket.depth, curr->stack)) { curr->allocs += bucket.allocs; curr->alloc_size += bucket.alloc_size; curr->frees += bucket.frees; curr->free_size += bucket.free_size; is_found = true; break; } } if (is_found) continue; const size_t key_size = sizeof(bucket.stack[0]) * bucket.depth; const void** key_copy = static_cast<const void**>( MyAllocator::Allocate(key_size)); std::copy(bucket.stack, bucket.stack + bucket.depth, key_copy); HeapProfileBucket* new_bucket = static_cast<HeapProfileBucket*>( MyAllocator::Allocate(sizeof(HeapProfileBucket))); memset(new_bucket, 0, sizeof(*new_bucket)); new_bucket->hash = bucket.hash; new_bucket->depth = bucket.depth; new_bucket->stack = key_copy; new_bucket->next = bucket_table_[hash_index]; bucket_table_[hash_index] = new_bucket; ++num_buckets_; } } inline void MemoryRegionMap::InitRegionSetLocked() { RAW_VLOG(12, "Initializing region set"); regions_ = regions_rep.region_set(); recursive_insert = true; new (regions_) RegionSet(); HandleSavedRegionsLocked(&DoInsertRegionLocked); recursive_insert = false; } inline void MemoryRegionMap::InsertRegionLocked(const Region& region) { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); // We can be called recursively, because RegionSet constructor // and DoInsertRegionLocked() (called below) can call the allocator. // recursive_insert tells us if that's the case. When this happens, // region insertion information is recorded in saved_regions[], // and taken into account when the recursion unwinds. // Do the insert: if (recursive_insert) { // recursion: save in saved_regions RAW_VLOG(12, "Saving recursive insert of region %p..%p from %p", reinterpret_cast<void*>(region.start_addr), reinterpret_cast<void*>(region.end_addr), reinterpret_cast<void*>(region.caller())); RAW_CHECK(saved_regions_count < arraysize(saved_regions), ""); // Copy 'region' to saved_regions[saved_regions_count] // together with the contents of its call_stack, // then increment saved_regions_count. saved_regions[saved_regions_count++] = region; } else { // not a recusrive call if (regions_ == NULL) { // init regions_ InitRegionSetLocked(); } recursive_insert = true; // Do the actual insertion work to put new regions into regions_: DoInsertRegionLocked(region); HandleSavedRegionsLocked(&DoInsertRegionLocked); recursive_insert = false; } } // We strip out different number of stack frames in debug mode // because less inlining happens in that case #ifdef NDEBUG static const int kStripFrames = 1; #else static const int kStripFrames = 3; #endif void MemoryRegionMap::RecordRegionAddition(const void* start, size_t size) { // Record start/end info about this memory acquisition call in a new region: Region region; region.Create(start, size); // First get the call stack info into the local varible 'region': int depth = 0; // NOTE: libunwind also does mmap and very much likely while holding // it's own lock(s). So some threads may first take libunwind lock, // and then take region map lock (necessary to record mmap done from // inside libunwind). On the other hand other thread(s) may do // normal mmap. Which would call this method to record it. Which // would then proceed with installing that record to region map // while holding region map lock. That may cause mmap from our own // internal allocators, so attempt to unwind in this case may cause // reverse order of taking libuwind and region map locks. Which is // obvious deadlock. // // Thankfully, we can easily detect if we're holding region map lock // and avoid recording backtrace in this (rare and largely // irrelevant) case. By doing this we "declare" that thread needing // both locks must take region map lock last. In other words we do // not allow taking libuwind lock when we already have region map // lock. Note, this is generally impossible when somebody tries to // mix cpu profiling and heap checking/profiling, because cpu // profiler grabs backtraces at arbitrary places. But at least such // combination is rarer and less relevant. if (max_stack_depth_ > 0 && !LockIsHeld()) { depth = MallocHook::GetCallerStackTrace(const_cast<void**>(region.call_stack), max_stack_depth_, kStripFrames + 1); } region.set_call_stack_depth(depth); // record stack info fully RAW_VLOG(10, "New global region %p..%p from %p", reinterpret_cast<void*>(region.start_addr), reinterpret_cast<void*>(region.end_addr), reinterpret_cast<void*>(region.caller())); // Note: none of the above allocates memory. Lock(); // recursively lock map_size_ += size; InsertRegionLocked(region); // This will (eventually) allocate storage for and copy over the stack data // from region.call_stack_data_ that is pointed by region.call_stack(). if (bucket_table_ != NULL) { HeapProfileBucket* b = GetBucket(depth, region.call_stack); ++b->allocs; b->alloc_size += size; if (!recursive_insert) { recursive_insert = true; RestoreSavedBucketsLocked(); recursive_insert = false; } } Unlock(); } void MemoryRegionMap::RecordRegionRemoval(const void* start, size_t size) { Lock(); if (recursive_insert) { // First remove the removed region from saved_regions, if it's // there, to prevent overrunning saved_regions in recursive // map/unmap call sequences, and also from later inserting regions // which have already been unmapped. uintptr_t start_addr = reinterpret_cast<uintptr_t>(start); uintptr_t end_addr = start_addr + size; int put_pos = 0; int old_count = saved_regions_count; for (int i = 0; i < old_count; ++i, ++put_pos) { Region& r = saved_regions[i]; if (r.start_addr == start_addr && r.end_addr == end_addr) { // An exact match, so it's safe to remove. RecordRegionRemovalInBucket(r.call_stack_depth, r.call_stack, size); --saved_regions_count; --put_pos; RAW_VLOG(10, ("Insta-Removing saved region %p..%p; " "now have %d saved regions"), reinterpret_cast<void*>(start_addr), reinterpret_cast<void*>(end_addr), saved_regions_count); } else { if (put_pos < i) { saved_regions[put_pos] = saved_regions[i]; } } } } if (regions_ == NULL) { // We must have just unset the hooks, // but this thread was already inside the hook. Unlock(); return; } if (!recursive_insert) { HandleSavedRegionsLocked(&InsertRegionLocked); } // first handle adding saved regions if any uintptr_t start_addr = reinterpret_cast<uintptr_t>(start); uintptr_t end_addr = start_addr + size; // subtract start_addr, end_addr from all the regions RAW_VLOG(10, "Removing global region %p..%p; have %" PRIuS " regions", reinterpret_cast<void*>(start_addr), reinterpret_cast<void*>(end_addr), regions_->size()); Region sample; sample.SetRegionSetKey(start_addr); // Only iterate over the regions that might overlap start_addr..end_addr: for (RegionSet::iterator region = regions_->lower_bound(sample); region != regions_->end() && region->start_addr < end_addr; /*noop*/) { RAW_VLOG(13, "Looking at region %p..%p", reinterpret_cast<void*>(region->start_addr), reinterpret_cast<void*>(region->end_addr)); if (start_addr <= region->start_addr && region->end_addr <= end_addr) { // full deletion RAW_VLOG(12, "Deleting region %p..%p", reinterpret_cast<void*>(region->start_addr), reinterpret_cast<void*>(region->end_addr)); RecordRegionRemovalInBucket(region->call_stack_depth, region->call_stack, region->end_addr - region->start_addr); RegionSet::iterator d = region; ++region; regions_->erase(d); continue; } else if (region->start_addr < start_addr && end_addr < region->end_addr) { // cutting-out split RAW_VLOG(12, "Splitting region %p..%p in two", reinterpret_cast<void*>(region->start_addr), reinterpret_cast<void*>(region->end_addr)); RecordRegionRemovalInBucket(region->call_stack_depth, region->call_stack, end_addr - start_addr); // Make another region for the start portion: // The new region has to be the start portion because we can't // just modify region->end_addr as it's the sorting key. Region r = *region; r.set_end_addr(start_addr); InsertRegionLocked(r); // cut *region from start: const_cast<Region&>(*region).set_start_addr(end_addr); } else if (end_addr > region->start_addr && start_addr <= region->start_addr) { // cut from start RAW_VLOG(12, "Start-chopping region %p..%p", reinterpret_cast<void*>(region->start_addr), reinterpret_cast<void*>(region->end_addr)); RecordRegionRemovalInBucket(region->call_stack_depth, region->call_stack, end_addr - region->start_addr); const_cast<Region&>(*region).set_start_addr(end_addr); } else if (start_addr > region->start_addr && start_addr < region->end_addr) { // cut from end RAW_VLOG(12, "End-chopping region %p..%p", reinterpret_cast<void*>(region->start_addr), reinterpret_cast<void*>(region->end_addr)); RecordRegionRemovalInBucket(region->call_stack_depth, region->call_stack, region->end_addr - start_addr); // Can't just modify region->end_addr (it's the sorting key): Region r = *region; r.set_end_addr(start_addr); RegionSet::iterator d = region; ++region; // It's safe to erase before inserting since r is independent of *d: // r contains an own copy of the call stack: regions_->erase(d); InsertRegionLocked(r); continue; } ++region; } RAW_VLOG(12, "Removed region %p..%p; have %" PRIuS " regions", reinterpret_cast<void*>(start_addr), reinterpret_cast<void*>(end_addr), regions_->size()); if (VLOG_IS_ON(12)) LogAllLocked(); unmap_size_ += size; Unlock(); } void MemoryRegionMap::RecordRegionRemovalInBucket(int depth, const void* const stack[], size_t size) { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); if (bucket_table_ == NULL) return; HeapProfileBucket* b = GetBucket(depth, stack); ++b->frees; b->free_size += size; } void MemoryRegionMap::MmapHook(const void* result, const void* start, size_t size, int prot, int flags, int fd, off_t offset) { // TODO(maxim): replace all 0x%" PRIxS " by %p when RAW_VLOG uses a safe // snprintf reimplementation that does not malloc to pretty-print NULL RAW_VLOG(10, "MMap = 0x%" PRIxPTR " of %" PRIuS " at %" PRIu64 " " "prot %d flags %d fd %d offs %" PRId64, reinterpret_cast<uintptr_t>(result), size, reinterpret_cast<uint64>(start), prot, flags, fd, static_cast<int64>(offset)); if (result != reinterpret_cast<void*>(MAP_FAILED) && size != 0) { RecordRegionAddition(result, size); } } void MemoryRegionMap::MunmapHook(const void* ptr, size_t size) { RAW_VLOG(10, "MUnmap of %p %" PRIuS "", ptr, size); if (size != 0) { RecordRegionRemoval(ptr, size); } } void MemoryRegionMap::MremapHook(const void* result, const void* old_addr, size_t old_size, size_t new_size, int flags, const void* new_addr) { RAW_VLOG(10, "MRemap = 0x%" PRIxPTR " of 0x%" PRIxPTR " %" PRIuS " " "to %" PRIuS " flags %d new_addr=0x%" PRIxPTR, (uintptr_t)result, (uintptr_t)old_addr, old_size, new_size, flags, flags & MREMAP_FIXED ? (uintptr_t)new_addr : 0); if (result != reinterpret_cast<void*>(-1)) { RecordRegionRemoval(old_addr, old_size); RecordRegionAddition(result, new_size); } } void MemoryRegionMap::SbrkHook(const void* result, ptrdiff_t increment) { RAW_VLOG(10, "Sbrk = 0x%" PRIxPTR " of %" PRIdS "", (uintptr_t)result, increment); if (result != reinterpret_cast<void*>(-1)) { if (increment > 0) { void* new_end = sbrk(0); RecordRegionAddition(result, reinterpret_cast<uintptr_t>(new_end) - reinterpret_cast<uintptr_t>(result)); } else if (increment < 0) { void* new_end = sbrk(0); RecordRegionRemoval(new_end, reinterpret_cast<uintptr_t>(result) - reinterpret_cast<uintptr_t>(new_end)); } } } void MemoryRegionMap::LogAllLocked() { RAW_CHECK(LockIsHeld(), "should be held (by this thread)"); RAW_LOG(INFO, "List of regions:"); uintptr_t previous = 0; for (RegionSet::const_iterator r = regions_->begin(); r != regions_->end(); ++r) { RAW_LOG(INFO, "Memory region 0x%" PRIxPTR "..0x%" PRIxPTR " " "from 0x%" PRIxPTR " stack=%d", r->start_addr, r->end_addr, r->caller(), r->is_stack); RAW_CHECK(previous < r->end_addr, "wow, we messed up the set order"); // this must be caused by uncontrolled recursive operations on regions_ previous = r->end_addr; } RAW_LOG(INFO, "End of regions list"); }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/heap-checker-bcad.cc
.cc
4,150
94
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Maxim Lifantsev // // A file to ensure that components of heap leak checker run before // all global object constructors and after all global object // destructors. // // This file must be the last library any binary links against. // Otherwise, the heap checker may not be able to run early enough to // catalog all the global objects in your program. If this happens, // and later in the program you allocate memory and have one of these // "uncataloged" global objects point to it, the heap checker will // consider that allocation to be a leak, even though it's not (since // the allocated object is reachable from global data and hence "live"). #include <stdlib.h> // for abort() #include <gperftools/malloc_extension.h> // A dummy variable to refer from heap-checker.cc. This is to make // sure this file is not optimized out by the linker. bool heap_leak_checker_bcad_variable; extern void HeapLeakChecker_AfterDestructors(); // in heap-checker.cc // A helper class to ensure that some components of heap leak checking // can happen before construction and after destruction // of all global/static objects. class HeapLeakCheckerGlobalPrePost { public: HeapLeakCheckerGlobalPrePost() { if (count_ == 0) { // The 'new int' will ensure that we have run an initial malloc // hook, which will set up the heap checker via // MallocHook_InitAtFirstAllocation_HeapLeakChecker. See malloc_hook.cc. // This is done in this roundabout fashion in order to avoid self-deadlock // if we directly called HeapLeakChecker_BeforeConstructors here. delete new int; // This needs to be called before the first allocation of an STL // object, but after libc is done setting up threads (because it // calls setenv, which requires a thread-aware errno). By // putting it here, we hope it's the first bit of code executed // after the libc global-constructor code. MallocExtension::Initialize(); } ++count_; } ~HeapLeakCheckerGlobalPrePost() { if (count_ <= 0) abort(); --count_; if (count_ == 0) HeapLeakChecker_AfterDestructors(); } private: // Counter of constructions/destructions of objects of this class // (just in case there are more than one of them). static int count_; }; int HeapLeakCheckerGlobalPrePost::count_ = 0; // The early-construction/late-destruction global object. static const HeapLeakCheckerGlobalPrePost heap_leak_checker_global_pre_post;
Unknown
3D
mcellteam/mcell
libs/gperftools/src/thread_cache.cc
.cc
18,470
530
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Ken Ashcraft <opensource@google.com> #include <config.h> #include "thread_cache.h" #include <errno.h> #include <string.h> // for memcpy #include <algorithm> // for max, min #include "base/commandlineflags.h" // for SpinLockHolder #include "base/spinlock.h" // for SpinLockHolder #include "getenv_safe.h" // for TCMallocGetenvSafe #include "central_freelist.h" // for CentralFreeListPadded #include "maybe_threads.h" using std::min; using std::max; // Note: this is initialized manually in InitModule to ensure that // it's configured at right time // // DEFINE_int64(tcmalloc_max_total_thread_cache_bytes, // EnvToInt64("TCMALLOC_MAX_TOTAL_THREAD_CACHE_BYTES", // kDefaultOverallThreadCacheSize), // "Bound on the total amount of bytes allocated to " // "thread caches. This bound is not strict, so it is possible " // "for the cache to go over this bound in certain circumstances. " // "Maximum value of this flag is capped to 1 GB."); namespace tcmalloc { static bool phinited = false; volatile size_t ThreadCache::per_thread_cache_size_ = kMaxThreadCacheSize; size_t ThreadCache::overall_thread_cache_size_ = kDefaultOverallThreadCacheSize; ssize_t ThreadCache::unclaimed_cache_space_ = kDefaultOverallThreadCacheSize; PageHeapAllocator<ThreadCache> threadcache_allocator; ThreadCache* ThreadCache::thread_heaps_ = NULL; int ThreadCache::thread_heap_count_ = 0; ThreadCache* ThreadCache::next_memory_steal_ = NULL; #ifdef HAVE_TLS __thread ThreadCache::ThreadLocalData ThreadCache::threadlocal_data_ ATTR_INITIAL_EXEC CACHELINE_ALIGNED; #endif bool ThreadCache::tsd_inited_ = false; pthread_key_t ThreadCache::heap_key_; void ThreadCache::Init(pthread_t tid) { size_ = 0; max_size_ = 0; IncreaseCacheLimitLocked(); if (max_size_ == 0) { // There isn't enough memory to go around. Just give the minimum to // this thread. SetMaxSize(kMinThreadCacheSize); // Take unclaimed_cache_space_ negative. unclaimed_cache_space_ -= kMinThreadCacheSize; ASSERT(unclaimed_cache_space_ < 0); } next_ = NULL; prev_ = NULL; tid_ = tid; in_setspecific_ = false; for (uint32 cl = 0; cl < Static::num_size_classes(); ++cl) { list_[cl].Init(Static::sizemap()->class_to_size(cl)); } uint32_t sampler_seed; memcpy(&sampler_seed, &tid, sizeof(sampler_seed)); sampler_.Init(sampler_seed); } void ThreadCache::Cleanup() { // Put unused memory back into central cache for (uint32 cl = 0; cl < Static::num_size_classes(); ++cl) { if (list_[cl].length() > 0) { ReleaseToCentralCache(&list_[cl], cl, list_[cl].length()); } } } // Remove some objects of class "cl" from central cache and add to thread heap. // On success, return the first object for immediate use; otherwise return NULL. void* ThreadCache::FetchFromCentralCache(uint32 cl, int32_t byte_size, void *(*oom_handler)(size_t size)) { FreeList* list = &list_[cl]; ASSERT(list->empty()); const int batch_size = Static::sizemap()->num_objects_to_move(cl); const int num_to_move = min<int>(list->max_length(), batch_size); void *start, *end; int fetch_count = Static::central_cache()[cl].RemoveRange( &start, &end, num_to_move); if (fetch_count == 0) { ASSERT(start == NULL); return oom_handler(byte_size); } ASSERT(start != NULL); if (--fetch_count >= 0) { size_ += byte_size * fetch_count; list->PushRange(fetch_count, SLL_Next(start), end); } // Increase max length slowly up to batch_size. After that, // increase by batch_size in one shot so that the length is a // multiple of batch_size. if (list->max_length() < batch_size) { list->set_max_length(list->max_length() + 1); } else { // Don't let the list get too long. In 32 bit builds, the length // is represented by a 16 bit int, so we need to watch out for // integer overflow. int new_length = min<int>(list->max_length() + batch_size, kMaxDynamicFreeListLength); // The list's max_length must always be a multiple of batch_size, // and kMaxDynamicFreeListLength is not necessarily a multiple // of batch_size. new_length -= new_length % batch_size; ASSERT(new_length % batch_size == 0); list->set_max_length(new_length); } return start; } void ThreadCache::ListTooLong(FreeList* list, uint32 cl) { size_ += list->object_size(); const int batch_size = Static::sizemap()->num_objects_to_move(cl); ReleaseToCentralCache(list, cl, batch_size); // If the list is too long, we need to transfer some number of // objects to the central cache. Ideally, we would transfer // num_objects_to_move, so the code below tries to make max_length // converge on num_objects_to_move. if (list->max_length() < batch_size) { // Slow start the max_length so we don't overreserve. list->set_max_length(list->max_length() + 1); } else if (list->max_length() > batch_size) { // If we consistently go over max_length, shrink max_length. If we don't // shrink it, some amount of memory will always stay in this freelist. list->set_length_overages(list->length_overages() + 1); if (list->length_overages() > kMaxOverages) { ASSERT(list->max_length() > batch_size); list->set_max_length(list->max_length() - batch_size); list->set_length_overages(0); } } if (PREDICT_FALSE(size_ > max_size_)) { Scavenge(); } } // Remove some objects of class "cl" from thread heap and add to central cache void ThreadCache::ReleaseToCentralCache(FreeList* src, uint32 cl, int N) { ASSERT(src == &list_[cl]); if (N > src->length()) N = src->length(); size_t delta_bytes = N * Static::sizemap()->ByteSizeForClass(cl); // We return prepackaged chains of the correct size to the central cache. // TODO: Use the same format internally in the thread caches? int batch_size = Static::sizemap()->num_objects_to_move(cl); while (N > batch_size) { void *tail, *head; src->PopRange(batch_size, &head, &tail); Static::central_cache()[cl].InsertRange(head, tail, batch_size); N -= batch_size; } void *tail, *head; src->PopRange(N, &head, &tail); Static::central_cache()[cl].InsertRange(head, tail, N); size_ -= delta_bytes; } // Release idle memory to the central cache void ThreadCache::Scavenge() { // If the low-water mark for the free list is L, it means we would // not have had to allocate anything from the central cache even if // we had reduced the free list size by L. We aim to get closer to // that situation by dropping L/2 nodes from the free list. This // may not release much memory, but if so we will call scavenge again // pretty soon and the low-water marks will be high on that call. for (int cl = 0; cl < Static::num_size_classes(); cl++) { FreeList* list = &list_[cl]; const int lowmark = list->lowwatermark(); if (lowmark > 0) { const int drop = (lowmark > 1) ? lowmark/2 : 1; ReleaseToCentralCache(list, cl, drop); // Shrink the max length if it isn't used. Only shrink down to // batch_size -- if the thread was active enough to get the max_length // above batch_size, it will likely be that active again. If // max_length shinks below batch_size, the thread will have to // go through the slow-start behavior again. The slow-start is useful // mainly for threads that stay relatively idle for their entire // lifetime. const int batch_size = Static::sizemap()->num_objects_to_move(cl); if (list->max_length() > batch_size) { list->set_max_length( max<int>(list->max_length() - batch_size, batch_size)); } } list->clear_lowwatermark(); } IncreaseCacheLimit(); } void ThreadCache::IncreaseCacheLimit() { SpinLockHolder h(Static::pageheap_lock()); IncreaseCacheLimitLocked(); } void ThreadCache::IncreaseCacheLimitLocked() { if (unclaimed_cache_space_ > 0) { // Possibly make unclaimed_cache_space_ negative. unclaimed_cache_space_ -= kStealAmount; SetMaxSize(max_size_ + kStealAmount); return; } // Don't hold pageheap_lock too long. Try to steal from 10 other // threads before giving up. The i < 10 condition also prevents an // infinite loop in case none of the existing thread heaps are // suitable places to steal from. for (int i = 0; i < 10; ++i, next_memory_steal_ = next_memory_steal_->next_) { // Reached the end of the linked list. Start at the beginning. if (next_memory_steal_ == NULL) { ASSERT(thread_heaps_ != NULL); next_memory_steal_ = thread_heaps_; } if (next_memory_steal_ == this || next_memory_steal_->max_size_ <= kMinThreadCacheSize) { continue; } next_memory_steal_->SetMaxSize(next_memory_steal_->max_size_ - kStealAmount); SetMaxSize(max_size_ + kStealAmount); next_memory_steal_ = next_memory_steal_->next_; return; } } int ThreadCache::GetSamplePeriod() { return Sampler::GetSamplePeriod(); } void ThreadCache::InitModule() { { SpinLockHolder h(Static::pageheap_lock()); if (phinited) { return; } const char *tcb = TCMallocGetenvSafe("TCMALLOC_MAX_TOTAL_THREAD_CACHE_BYTES"); if (tcb) { set_overall_thread_cache_size(strtoll(tcb, NULL, 10)); } Static::InitStaticVars(); threadcache_allocator.Init(); phinited = 1; } // We do "late" part of initialization without holding lock since // there is chance it'll recurse into malloc Static::InitLateMaybeRecursive(); } void ThreadCache::InitTSD() { ASSERT(!tsd_inited_); perftools_pthread_key_create(&heap_key_, DestroyThreadCache); tsd_inited_ = true; #ifdef PTHREADS_CRASHES_IF_RUN_TOO_EARLY // We may have used a fake pthread_t for the main thread. Fix it. pthread_t zero; memset(&zero, 0, sizeof(zero)); SpinLockHolder h(Static::pageheap_lock()); for (ThreadCache* h = thread_heaps_; h != NULL; h = h->next_) { if (h->tid_ == zero) { h->tid_ = pthread_self(); } } #endif } ThreadCache* ThreadCache::CreateCacheIfNecessary() { if (!tsd_inited_) { #ifndef NDEBUG // tests that freeing nullptr very early is working free(NULL); #endif InitModule(); } // Initialize per-thread data if necessary ThreadCache* heap = NULL; bool seach_condition = true; #ifdef HAVE_TLS static __thread ThreadCache** current_heap_ptr ATTR_INITIAL_EXEC; if (tsd_inited_) { // In most common case we're avoiding expensive linear search // through all heaps (see below). Working TLS enables faster // protection from malloc recursion in pthread_setspecific seach_condition = false; if (current_heap_ptr != NULL) { // we're being recursively called by pthread_setspecific below. return *current_heap_ptr; } current_heap_ptr = &heap; } #endif { SpinLockHolder h(Static::pageheap_lock()); // On some old glibc's, and on freebsd's libc (as of freebsd 8.1), // calling pthread routines (even pthread_self) too early could // cause a segfault. Since we can call pthreads quite early, we // have to protect against that in such situations by making a // 'fake' pthread. This is not ideal since it doesn't work well // when linking tcmalloc statically with apps that create threads // before main, so we only do it if we have to. #ifdef PTHREADS_CRASHES_IF_RUN_TOO_EARLY pthread_t me; if (!tsd_inited_) { memset(&me, 0, sizeof(me)); } else { me = pthread_self(); } #else const pthread_t me = pthread_self(); #endif // This may be a recursive malloc call from pthread_setspecific() // In that case, the heap for this thread has already been created // and added to the linked list. So we search for that first. if (seach_condition) { for (ThreadCache* h = thread_heaps_; h != NULL; h = h->next_) { if (h->tid_ == me) { heap = h; break; } } } if (heap == NULL) heap = NewHeap(me); } // We call pthread_setspecific() outside the lock because it may // call malloc() recursively. We check for the recursive call using // the "in_setspecific_" flag so that we can avoid calling // pthread_setspecific() if we are already inside pthread_setspecific(). if (!heap->in_setspecific_ && tsd_inited_) { heap->in_setspecific_ = true; perftools_pthread_setspecific(heap_key_, heap); #ifdef HAVE_TLS // Also keep a copy in __thread for faster retrieval threadlocal_data_.heap = heap; threadlocal_data_.fast_path_heap = heap; #endif heap->in_setspecific_ = false; } #ifdef HAVE_TLS current_heap_ptr = NULL; #endif return heap; } ThreadCache* ThreadCache::NewHeap(pthread_t tid) { // Create the heap and add it to the linked list ThreadCache *heap = threadcache_allocator.New(); heap->Init(tid); heap->next_ = thread_heaps_; heap->prev_ = NULL; if (thread_heaps_ != NULL) { thread_heaps_->prev_ = heap; } else { // This is the only thread heap at the momment. ASSERT(next_memory_steal_ == NULL); next_memory_steal_ = heap; } thread_heaps_ = heap; thread_heap_count_++; return heap; } void ThreadCache::BecomeIdle() { if (!tsd_inited_) return; // No caches yet ThreadCache* heap = GetThreadHeap(); if (heap == NULL) return; // No thread cache to remove if (heap->in_setspecific_) return; // Do not disturb the active caller heap->in_setspecific_ = true; perftools_pthread_setspecific(heap_key_, NULL); #ifdef HAVE_TLS // Also update the copy in __thread threadlocal_data_.heap = NULL; threadlocal_data_.fast_path_heap = NULL; #endif heap->in_setspecific_ = false; if (GetThreadHeap() == heap) { // Somehow heap got reinstated by a recursive call to malloc // from pthread_setspecific. We give up in this case. return; } // We can now get rid of the heap DeleteCache(heap); } void ThreadCache::BecomeTemporarilyIdle() { ThreadCache* heap = GetCacheIfPresent(); if (heap) heap->Cleanup(); } void ThreadCache::DestroyThreadCache(void* ptr) { // Note that "ptr" cannot be NULL since pthread promises not // to invoke the destructor on NULL values, but for safety, // we check anyway. if (ptr == NULL) return; #ifdef HAVE_TLS // Prevent fast path of GetThreadHeap() from returning heap. threadlocal_data_.heap = NULL; threadlocal_data_.fast_path_heap = NULL; #endif DeleteCache(reinterpret_cast<ThreadCache*>(ptr)); } void ThreadCache::DeleteCache(ThreadCache* heap) { // Remove all memory from heap heap->Cleanup(); // Remove from linked list SpinLockHolder h(Static::pageheap_lock()); if (heap->next_ != NULL) heap->next_->prev_ = heap->prev_; if (heap->prev_ != NULL) heap->prev_->next_ = heap->next_; if (thread_heaps_ == heap) thread_heaps_ = heap->next_; thread_heap_count_--; if (next_memory_steal_ == heap) next_memory_steal_ = heap->next_; if (next_memory_steal_ == NULL) next_memory_steal_ = thread_heaps_; unclaimed_cache_space_ += heap->max_size_; threadcache_allocator.Delete(heap); } void ThreadCache::RecomputePerThreadCacheSize() { // Divide available space across threads int n = thread_heap_count_ > 0 ? thread_heap_count_ : 1; size_t space = overall_thread_cache_size_ / n; // Limit to allowed range if (space < kMinThreadCacheSize) space = kMinThreadCacheSize; if (space > kMaxThreadCacheSize) space = kMaxThreadCacheSize; double ratio = space / max<double>(1, per_thread_cache_size_); size_t claimed = 0; for (ThreadCache* h = thread_heaps_; h != NULL; h = h->next_) { // Increasing the total cache size should not circumvent the // slow-start growth of max_size_. if (ratio < 1.0) { h->SetMaxSize(h->max_size_ * ratio); } claimed += h->max_size_; } unclaimed_cache_space_ = overall_thread_cache_size_ - claimed; per_thread_cache_size_ = space; } void ThreadCache::GetThreadStats(uint64_t* total_bytes, uint64_t* class_count) { for (ThreadCache* h = thread_heaps_; h != NULL; h = h->next_) { *total_bytes += h->Size(); if (class_count) { for (int cl = 0; cl < Static::num_size_classes(); ++cl) { class_count[cl] += h->freelist_length(cl); } } } } void ThreadCache::set_overall_thread_cache_size(size_t new_size) { // Clip the value to a reasonable range if (new_size < kMinThreadCacheSize) new_size = kMinThreadCacheSize; if (new_size > (1<<30)) new_size = (1<<30); // Limit to 1GB overall_thread_cache_size_ = new_size; RecomputePerThreadCacheSize(); } } // namespace tcmalloc
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_win32-inl.h
.h
4,606
108
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // --- // Produces a stack trace for Windows. Normally, one could use // stacktrace_x86-inl.h or stacktrace_x86_64-inl.h -- and indeed, that // should work for binaries compiled using MSVC in "debug" mode. // However, in "release" mode, Windows uses frame-pointer // optimization, which makes getting a stack trace very difficult. // // There are several approaches one can take. One is to use Windows // intrinsics like StackWalk64. These can work, but have restrictions // on how successful they can be. Another attempt is to write a // version of stacktrace_x86-inl.h that has heuristic support for // dealing with FPO, similar to what WinDbg does (see // http://www.nynaeve.net/?p=97). // // The solution we've ended up doing is to call the undocumented // windows function RtlCaptureStackBackTrace, which probably doesn't // work with FPO but at least is fast, and doesn't require a symbol // server. // // This code is inspired by a patch from David Vitek: // http://code.google.com/p/gperftools/issues/detail?id=83 #ifndef BASE_STACKTRACE_WIN32_INL_H_ #define BASE_STACKTRACE_WIN32_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include "config.h" #include <windows.h> // for GetProcAddress and GetModuleHandle #include <assert.h> typedef USHORT NTAPI RtlCaptureStackBackTrace_Function( IN ULONG frames_to_skip, IN ULONG frames_to_capture, OUT PVOID *backtrace, OUT PULONG backtrace_hash); // Load the function we need at static init time, where we don't have // to worry about someone else holding the loader's lock. static RtlCaptureStackBackTrace_Function* const RtlCaptureStackBackTrace_fn = (RtlCaptureStackBackTrace_Function*) GetProcAddress(GetModuleHandleA("ntdll.dll"), "RtlCaptureStackBackTrace"); static int GetStackTrace_win32(void** result, int max_depth, int skip_count) { if (!RtlCaptureStackBackTrace_fn) { // TODO(csilvers): should we log an error here? return 0; // can't find a stacktrace with no function to call } return (int)RtlCaptureStackBackTrace_fn(skip_count + 3, max_depth, result, 0); } static int not_implemented(void) { assert(0 == "Not yet implemented"); return 0; } static int GetStackFrames_win32(void** /* pcs */, int* /* sizes */, int /* max_depth */, int /* skip_count */) { return not_implemented(); } static int GetStackFramesWithContext_win32(void** result, int* sizes, int max_depth, int skip_count, const void *uc) { return not_implemented(); } static int GetStackTraceWithContext_win32(void** result, int max_depth, int skip_count, const void *uc) { return not_implemented(); } #endif // BASE_STACKTRACE_WIN32_INL_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/libc_override_redefine.h
.h
5,938
132
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein <opensource@google.com> // // Used on systems that don't have their own definition of // malloc/new/etc. (Typically this will be a windows msvcrt.dll that // has been edited to remove the definitions.) We can just define our // own as normal functions. // // This should also work on systems were all the malloc routines are // defined as weak symbols, and there's no support for aliasing. #ifndef TCMALLOC_LIBC_OVERRIDE_REDEFINE_H_ #define TCMALLOC_LIBC_OVERRIDE_REDEFINE_H_ void* operator new(size_t size) { return tc_new(size); } void operator delete(void* p) CPP_NOTHROW { tc_delete(p); } void* operator new[](size_t size) { return tc_newarray(size); } void operator delete[](void* p) CPP_NOTHROW { tc_deletearray(p); } void* operator new(size_t size, const std::nothrow_t& nt) CPP_NOTHROW { return tc_new_nothrow(size, nt); } void* operator new[](size_t size, const std::nothrow_t& nt) CPP_NOTHROW { return tc_newarray_nothrow(size, nt); } void operator delete(void* ptr, const std::nothrow_t& nt) CPP_NOTHROW { return tc_delete_nothrow(ptr, nt); } void operator delete[](void* ptr, const std::nothrow_t& nt) CPP_NOTHROW { return tc_deletearray_nothrow(ptr, nt); } #ifdef ENABLE_SIZED_DELETE void operator delete(void* p, size_t s) CPP_NOTHROW { tc_delete_sized(p, s); } void operator delete[](void* p, size_t s) CPP_NOTHROW{ tc_deletearray_sized(p, s);} #endif #if defined(ENABLE_ALIGNED_NEW_DELETE) void* operator new(size_t size, std::align_val_t al) { return tc_new_aligned(size, al); } void operator delete(void* p, std::align_val_t al) CPP_NOTHROW { tc_delete_aligned(p, al); } void* operator new[](size_t size, std::align_val_t al) { return tc_newarray_aligned(size, al); } void operator delete[](void* p, std::align_val_t al) CPP_NOTHROW { tc_deletearray_aligned(p, al); } void* operator new(size_t size, std::align_val_t al, const std::nothrow_t& nt) CPP_NOTHROW { return tc_new_aligned_nothrow(size, al, nt); } void* operator new[](size_t size, std::align_val_t al, const std::nothrow_t& nt) CPP_NOTHROW { return tc_newarray_aligned_nothrow(size, al, nt); } void operator delete(void* ptr, std::align_val_t al, const std::nothrow_t& nt) CPP_NOTHROW { return tc_delete_aligned_nothrow(ptr, al, nt); } void operator delete[](void* ptr, std::align_val_t al, const std::nothrow_t& nt) CPP_NOTHROW { return tc_deletearray_aligned_nothrow(ptr, al, nt); } #ifdef ENABLE_SIZED_DELETE void operator delete(void* p, size_t s, std::align_val_t al) CPP_NOTHROW { tc_delete_sized_aligned(p, s, al); } void operator delete[](void* p, size_t s, std::align_val_t al) CPP_NOTHROW { tc_deletearray_sized_aligned(p, s, al); } #endif #endif // defined(ENABLE_ALIGNED_NEW_DELETE) extern "C" { void* malloc(size_t s) { return tc_malloc(s); } void free(void* p) { tc_free(p); } void* realloc(void* p, size_t s) { return tc_realloc(p, s); } void* calloc(size_t n, size_t s) { return tc_calloc(n, s); } void cfree(void* p) { tc_cfree(p); } void* memalign(size_t a, size_t s) { return tc_memalign(a, s); } void* aligned_alloc(size_t a, size_t s) { return tc_memalign(a, s); } void* valloc(size_t s) { return tc_valloc(s); } void* pvalloc(size_t s) { return tc_pvalloc(s); } int posix_memalign(void** r, size_t a, size_t s) { return tc_posix_memalign(r, a, s); } void malloc_stats(void) { tc_malloc_stats(); } int mallopt(int cmd, int v) { return tc_mallopt(cmd, v); } #ifdef HAVE_STRUCT_MALLINFO struct mallinfo mallinfo(void) { return tc_mallinfo(); } #endif size_t malloc_size(void* p) { return tc_malloc_size(p); } size_t malloc_usable_size(void* p) { return tc_malloc_size(p); } } // extern "C" // No need to do anything at tcmalloc-registration time: we do it all // via overriding weak symbols (at link time). static void ReplaceSystemAlloc() { } #endif // TCMALLOC_LIBC_OVERRIDE_REDEFINE_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/static_vars.h
.h
5,088
127
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Ken Ashcraft <opensource@google.com> // // Static variables shared by multiple classes. #ifndef TCMALLOC_STATIC_VARS_H_ #define TCMALLOC_STATIC_VARS_H_ #include <config.h> #include "base/basictypes.h" #include "base/spinlock.h" #include "central_freelist.h" #include "common.h" #include "page_heap.h" #include "page_heap_allocator.h" #include "span.h" #include "stack_trace_table.h" namespace tcmalloc { class Static { public: // Linker initialized, so this lock can be accessed at any time. static SpinLock* pageheap_lock() { return &pageheap_lock_; } // Must be called before calling any of the accessors below. static void InitStaticVars(); static void InitLateMaybeRecursive(); // Central cache -- an array of free-lists, one per size-class. // We have a separate lock per free-list to reduce contention. static CentralFreeListPadded* central_cache() { return central_cache_; } static SizeMap* sizemap() { return &sizemap_; } static unsigned num_size_classes() { return sizemap_.num_size_classes; } ////////////////////////////////////////////////////////////////////// // In addition to the explicit initialization comment, the variables below // must be protected by pageheap_lock. // Page-level allocator. static PageHeap* pageheap() { return reinterpret_cast<PageHeap *>(&pageheap_.memory); } static PageHeapAllocator<Span>* span_allocator() { return &span_allocator_; } static PageHeapAllocator<StackTrace>* stacktrace_allocator() { return &stacktrace_allocator_; } static StackTrace* growth_stacks() { return growth_stacks_; } static void set_growth_stacks(StackTrace* s) { growth_stacks_ = s; } // State kept for sampled allocations (/pprof/heap support) static Span* sampled_objects() { return &sampled_objects_; } // Check if InitStaticVars() has been run. static bool IsInited() { return inited_; } private: // some unit tests depend on this and link to static vars // imperfectly. Thus we keep those unhidden for now. Thankfully // they're not performance-critical. /* ATTRIBUTE_HIDDEN */ static bool inited_; /* ATTRIBUTE_HIDDEN */ static SpinLock pageheap_lock_; // These static variables require explicit initialization. We cannot // count on their constructors to do any initialization because other // static variables may try to allocate memory before these variables // can run their constructors. ATTRIBUTE_HIDDEN static SizeMap sizemap_; ATTRIBUTE_HIDDEN static CentralFreeListPadded central_cache_[kClassSizesMax]; ATTRIBUTE_HIDDEN static PageHeapAllocator<Span> span_allocator_; ATTRIBUTE_HIDDEN static PageHeapAllocator<StackTrace> stacktrace_allocator_; ATTRIBUTE_HIDDEN static Span sampled_objects_; // Linked list of stack traces recorded every time we allocated memory // from the system. Useful for finding allocation sites that cause // increase in the footprint of the system. The linked list pointer // is stored in trace->stack[kMaxStackDepth-1]. ATTRIBUTE_HIDDEN static StackTrace* growth_stacks_; // PageHeap uses a constructor for initialization. Like the members above, // we can't depend on initialization order, so pageheap is new'd // into this buffer. union PageHeapStorage { char memory[sizeof(PageHeap)]; uintptr_t extra; // To force alignment }; ATTRIBUTE_HIDDEN static PageHeapStorage pageheap_; }; } // namespace tcmalloc #endif // TCMALLOC_STATIC_VARS_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace.cc
.cc
11,176
341
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // // Produce stack trace. // // There are three different ways we can try to get the stack trace: // // 1) Our hand-coded stack-unwinder. This depends on a certain stack // layout, which is used by gcc (and those systems using a // gcc-compatible ABI) on x86 systems, at least since gcc 2.95. // It uses the frame pointer to do its work. // // 2) The libunwind library. This is still in development, and as a // separate library adds a new dependency, abut doesn't need a frame // pointer. It also doesn't call malloc. // // 3) The gdb unwinder -- also the one used by the c++ exception code. // It's obviously well-tested, but has a fatal flaw: it can call // malloc() from the unwinder. This is a problem because we're // trying to use the unwinder to instrument malloc(). // // Note: if you add a new implementation here, make sure it works // correctly when GetStackTrace() is called with max_depth == 0. // Some code may do that. #include <config.h> #include <stdlib.h> // for getenv #include <string.h> // for strcmp #include <stdio.h> // for fprintf #include "gperftools/stacktrace.h" #include "base/commandlineflags.h" #include "base/googleinit.h" #include "getenv_safe.h" // we're using plain struct and not class to avoid any possible issues // during initialization. Struct of pointers is easy to init at // link-time. struct GetStackImplementation { int (*GetStackFramesPtr)(void** result, int* sizes, int max_depth, int skip_count); int (*GetStackFramesWithContextPtr)(void** result, int* sizes, int max_depth, int skip_count, const void *uc); int (*GetStackTracePtr)(void** result, int max_depth, int skip_count); int (*GetStackTraceWithContextPtr)(void** result, int max_depth, int skip_count, const void *uc); const char *name; }; #if HAVE_DECL_BACKTRACE #define STACKTRACE_INL_HEADER "stacktrace_generic-inl.h" #define GST_SUFFIX generic #include "stacktrace_impl_setup-inl.h" #undef GST_SUFFIX #undef STACKTRACE_INL_HEADER #define HAVE_GST_generic #endif #ifdef HAVE_UNWIND_BACKTRACE #define STACKTRACE_INL_HEADER "stacktrace_libgcc-inl.h" #define GST_SUFFIX libgcc #include "stacktrace_impl_setup-inl.h" #undef GST_SUFFIX #undef STACKTRACE_INL_HEADER #define HAVE_GST_libgcc #endif // libunwind uses __thread so we check for both libunwind.h and // __thread support #if defined(HAVE_LIBUNWIND_H) && defined(HAVE_TLS) #define STACKTRACE_INL_HEADER "stacktrace_libunwind-inl.h" #define GST_SUFFIX libunwind #include "stacktrace_impl_setup-inl.h" #undef GST_SUFFIX #undef STACKTRACE_INL_HEADER #define HAVE_GST_libunwind #endif // HAVE_LIBUNWIND_H #if defined(__i386__) || defined(__x86_64__) #define STACKTRACE_INL_HEADER "stacktrace_x86-inl.h" #define GST_SUFFIX x86 #include "stacktrace_impl_setup-inl.h" #undef GST_SUFFIX #undef STACKTRACE_INL_HEADER #define HAVE_GST_x86 #endif // i386 || x86_64 #if defined(__ppc__) || defined(__PPC__) #if defined(__linux__) #define STACKTRACE_INL_HEADER "stacktrace_powerpc-linux-inl.h" #else #define STACKTRACE_INL_HEADER "stacktrace_powerpc-darwin-inl.h" #endif #define GST_SUFFIX ppc #include "stacktrace_impl_setup-inl.h" #undef GST_SUFFIX #undef STACKTRACE_INL_HEADER #define HAVE_GST_ppc #endif #if defined(__arm__) #define STACKTRACE_INL_HEADER "stacktrace_arm-inl.h" #define GST_SUFFIX arm #include "stacktrace_impl_setup-inl.h" #undef GST_SUFFIX #undef STACKTRACE_INL_HEADER #define HAVE_GST_arm #endif #ifdef TCMALLOC_ENABLE_INSTRUMENT_STACKTRACE #define STACKTRACE_INL_HEADER "stacktrace_instrument-inl.h" #define GST_SUFFIX instrument #include "stacktrace_impl_setup-inl.h" #undef GST_SUFFIX #undef STACKTRACE_INL_HEADER #define HAVE_GST_instrument #endif // The Windows case -- probably cygwin and mingw will use one of the // x86-includes above, but if not, we can fall back to windows intrinsics. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW32__) #define STACKTRACE_INL_HEADER "stacktrace_win32-inl.h" #define GST_SUFFIX win32 #include "stacktrace_impl_setup-inl.h" #undef GST_SUFFIX #undef STACKTRACE_INL_HEADER #define HAVE_GST_win32 #endif static GetStackImplementation *all_impls[] = { #ifdef HAVE_GST_libgcc &impl__libgcc, #endif #ifdef HAVE_GST_generic &impl__generic, #endif #ifdef HAVE_GST_libunwind &impl__libunwind, #endif #ifdef HAVE_GST_x86 &impl__x86, #endif #ifdef HAVE_GST_arm &impl__arm, #endif #ifdef HAVE_GST_ppc &impl__ppc, #endif #ifdef HAVE_GST_instrument &impl__instrument, #endif #ifdef HAVE_GST_win32 &impl__win32, #endif NULL }; // ppc and i386 implementations prefer arch-specific asm implementations. // arm's asm implementation is broken #if defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || defined(__PPC__) #if !defined(NO_FRAME_POINTER) #define TCMALLOC_DONT_PREFER_LIBUNWIND #endif #endif static bool get_stack_impl_inited; #if defined(HAVE_GST_instrument) static GetStackImplementation *get_stack_impl = &impl__instrument; #elif defined(HAVE_GST_win32) static GetStackImplementation *get_stack_impl = &impl__win32; #elif defined(HAVE_GST_x86) && defined(TCMALLOC_DONT_PREFER_LIBUNWIND) static GetStackImplementation *get_stack_impl = &impl__x86; #elif defined(HAVE_GST_ppc) && defined(TCMALLOC_DONT_PREFER_LIBUNWIND) static GetStackImplementation *get_stack_impl = &impl__ppc; #elif defined(HAVE_GST_libunwind) static GetStackImplementation *get_stack_impl = &impl__libunwind; #elif defined(HAVE_GST_libgcc) static GetStackImplementation *get_stack_impl = &impl__libgcc; #elif defined(HAVE_GST_generic) static GetStackImplementation *get_stack_impl = &impl__generic; #elif defined(HAVE_GST_arm) static GetStackImplementation *get_stack_impl = &impl__arm; #elif 0 // This is for the benefit of code analysis tools that may have // trouble with the computed #include above. # include "stacktrace_x86-inl.h" # include "stacktrace_libunwind-inl.h" # include "stacktrace_generic-inl.h" # include "stacktrace_powerpc-inl.h" # include "stacktrace_win32-inl.h" # include "stacktrace_arm-inl.h" # include "stacktrace_instrument-inl.h" #else #error Cannot calculate stack trace: will need to write for your environment #endif static int ATTRIBUTE_NOINLINE frame_forcer(int rv) { return rv; } static void init_default_stack_impl_inner(void); namespace tcmalloc { bool EnterStacktraceScope(void); void LeaveStacktraceScope(void); } namespace { using tcmalloc::EnterStacktraceScope; using tcmalloc::LeaveStacktraceScope; class StacktraceScope { bool stacktrace_allowed; public: StacktraceScope() { stacktrace_allowed = true; stacktrace_allowed = EnterStacktraceScope(); } bool IsStacktraceAllowed() { return stacktrace_allowed; } ~StacktraceScope() { if (stacktrace_allowed) { LeaveStacktraceScope(); } } }; } PERFTOOLS_DLL_DECL int GetStackFrames(void** result, int* sizes, int max_depth, int skip_count) { StacktraceScope scope; if (!scope.IsStacktraceAllowed()) { return 0; } init_default_stack_impl_inner(); return frame_forcer(get_stack_impl->GetStackFramesPtr(result, sizes, max_depth, skip_count)); } PERFTOOLS_DLL_DECL int GetStackFramesWithContext(void** result, int* sizes, int max_depth, int skip_count, const void *uc) { StacktraceScope scope; if (!scope.IsStacktraceAllowed()) { return 0; } init_default_stack_impl_inner(); return frame_forcer(get_stack_impl->GetStackFramesWithContextPtr( result, sizes, max_depth, skip_count, uc)); } PERFTOOLS_DLL_DECL int GetStackTrace(void** result, int max_depth, int skip_count) { StacktraceScope scope; if (!scope.IsStacktraceAllowed()) { return 0; } init_default_stack_impl_inner(); return frame_forcer(get_stack_impl->GetStackTracePtr(result, max_depth, skip_count)); } PERFTOOLS_DLL_DECL int GetStackTraceWithContext(void** result, int max_depth, int skip_count, const void *uc) { StacktraceScope scope; if (!scope.IsStacktraceAllowed()) { return 0; } init_default_stack_impl_inner(); return frame_forcer(get_stack_impl->GetStackTraceWithContextPtr( result, max_depth, skip_count, uc)); } static void init_default_stack_impl_inner(void) { if (get_stack_impl_inited) { return; } get_stack_impl_inited = true; const char *val = TCMallocGetenvSafe("TCMALLOC_STACKTRACE_METHOD"); if (!val || !*val) { return; } for (GetStackImplementation **p = all_impls; *p; p++) { GetStackImplementation *c = *p; if (strcmp(c->name, val) == 0) { get_stack_impl = c; return; } } fprintf(stderr, "Unknown or unsupported stacktrace method requested: %s. Ignoring it\n", val); } static void init_default_stack_impl(void) { init_default_stack_impl_inner(); if (EnvToBool("TCMALLOC_STACKTRACE_METHOD_VERBOSE", false)) { fprintf(stderr, "Chosen stacktrace method is %s\nSupported methods:\n", get_stack_impl->name); for (GetStackImplementation **p = all_impls; *p; p++) { GetStackImplementation *c = *p; fprintf(stderr, "* %s\n", c->name); } fputs("\n", stderr); } } REGISTER_MODULE_INITIALIZER(stacktrace_init_default_stack_impl, init_default_stack_impl());
Unknown
3D
mcellteam/mcell
libs/gperftools/src/libc_override.h
.h
4,055
100
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein <opensource@google.com> // // This .h file imports the code that causes tcmalloc to override libc // versions of malloc/free/new/delete/etc. That is, it provides the // logic that makes it so calls to malloc(10) go through tcmalloc, // rather than the default (libc) malloc. // // This file also provides a method: ReplaceSystemAlloc(), that every // libc_override_*.h file it #includes is required to provide. This // is called when first setting up tcmalloc -- that is, when a global // constructor in tcmalloc.cc is executed -- to do any initialization // work that may be required for this OS. (Note we cannot entirely // control when tcmalloc is initialized, and the system may do some // mallocs and frees before this routine is called.) It may be a // noop. // // Every libc has its own way of doing this, and sometimes the compiler // matters too, so we have a different file for each libc, and often // for different compilers and OS's. #ifndef TCMALLOC_LIBC_OVERRIDE_INL_H_ #define TCMALLOC_LIBC_OVERRIDE_INL_H_ #include <config.h> #ifdef HAVE_FEATURES_H #include <features.h> // for __GLIBC__ #endif #include <gperftools/tcmalloc.h> #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900) #define CPP_NOTHROW noexcept #define CPP_BADALLOC #else #define CPP_NOTHROW throw() #define CPP_BADALLOC throw(std::bad_alloc) #endif static void ReplaceSystemAlloc(); // defined in the .h files below // For windows, there are two ways to get tcmalloc. If we're // patching, then src/windows/patch_function.cc will do the necessary // overriding here. Otherwise, we doing the 'redefine' trick, where // we remove malloc/new/etc from mscvcrt.dll, and just need to define // them now. #if defined(_WIN32) && defined(WIN32_DO_PATCHING) void PatchWindowsFunctions(); // in src/windows/patch_function.cc static void ReplaceSystemAlloc() { PatchWindowsFunctions(); } #elif defined(_WIN32) && !defined(WIN32_DO_PATCHING) #include "libc_override_redefine.h" #elif defined(__APPLE__) #include "libc_override_osx.h" #elif defined(__GLIBC__) #include "libc_override_glibc.h" // Not all gcc systems necessarily support weak symbols, but all the // ones I know of do, so for now just assume they all do. #elif defined(__GNUC__) #include "libc_override_gcc_and_weak.h" #else #error Need to add support for your libc/OS here #endif #endif // TCMALLOC_LIBC_OVERRIDE_INL_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/profile-handler.h
.h
6,158
143
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- /* Copyright (c) 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Nabeel Mian * * This module manages the cpu profile timers and the associated interrupt * handler. When enabled, all threads in the program are profiled. * * Any component interested in receiving a profile timer interrupt can do so by * registering a callback. All registered callbacks must be async-signal-safe. * * Note: This module requires the sole ownership of the configured timer and * signal. The timer defaults to ITIMER_PROF, can be changed to ITIMER_REAL by * the environment variable CPUPROFILE_REALTIME, or is changed to a POSIX timer * with CPUPROFILE_PER_THREAD_TIMERS. The signal defaults to SIGPROF/SIGALRM to * match the choice of timer and can be set to an arbitrary value using * CPUPROFILE_TIMER_SIGNAL with CPUPROFILE_PER_THREAD_TIMERS. */ #ifndef BASE_PROFILE_HANDLER_H_ #define BASE_PROFILE_HANDLER_H_ #include "config.h" #include <signal.h> #ifdef COMPILER_MSVC #include "conflict-signal.h" #endif #include "base/basictypes.h" /* Forward declaration. */ struct ProfileHandlerToken; /* * Callback function to be used with ProfilefHandlerRegisterCallback. This * function will be called in the context of SIGPROF signal handler and must * be async-signal-safe. The first three arguments are the values provided by * the SIGPROF signal handler. We use void* to avoid using ucontext_t on * non-POSIX systems. * * Requirements: * - Callback must be async-signal-safe. * - None of the functions in ProfileHandler are async-signal-safe. Therefore, * callback function *must* not call any of the ProfileHandler functions. * - Callback is not required to be re-entrant. At most one instance of * callback can run at a time. * * Notes: * - The SIGPROF signal handler saves and restores errno, so the callback * doesn't need to. * - Callback code *must* not acquire lock(s) to serialize access to data shared * with the code outside the signal handler (callback must be * async-signal-safe). If such a serialization is needed, follow the model * used by profiler.cc: * * When code other than the signal handler modifies the shared data it must: * - Acquire lock. * - Unregister the callback with the ProfileHandler. * - Modify shared data. * - Re-register the callback. * - Release lock. * and the callback code gets a lockless, read-write access to the data. */ typedef void (*ProfileHandlerCallback)(int sig, siginfo_t* sig_info, void* ucontext, void* callback_arg); /* * Registers a new thread with profile handler and should be called only once * per thread. The main thread is registered at program startup. This routine * is called by the Thread module in google3/thread whenever a new thread is * created. This function is not async-signal-safe. */ void ProfileHandlerRegisterThread(); /* * Registers a callback routine. This callback function will be called in the * context of SIGPROF handler, so must be async-signal-safe. The returned token * is to be used when unregistering this callback via * ProfileHandlerUnregisterCallback. Registering the first callback enables * the SIGPROF signal handler. Caller must not free the returned token. This * function is not async-signal-safe. */ ProfileHandlerToken* ProfileHandlerRegisterCallback( ProfileHandlerCallback callback, void* callback_arg); /* * Unregisters a previously registered callback. Expects the token returned * by the corresponding ProfileHandlerRegisterCallback and asserts that the * passed token is valid. Unregistering the last callback disables the SIGPROF * signal handler. It waits for the currently running callback to * complete before returning. This function is not async-signal-safe. */ void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token); /* * FOR TESTING ONLY * Unregisters all the callbacks, stops the timers (if shared) and disables the * SIGPROF handler. All the threads, including the main thread, need to be * re-registered after this call. This function is not async-signal-safe. */ void ProfileHandlerReset(); /* * Stores profile handler's current state. This function is not * async-signal-safe. */ struct ProfileHandlerState { int32 frequency; /* Profiling frequency */ int32 callback_count; /* Number of callbacks registered */ int64 interrupts; /* Number of interrupts received */ bool allowed; /* Profiling is allowed */ }; void ProfileHandlerGetState(struct ProfileHandlerState* state); #endif /* BASE_PROFILE_HANDLER_H_ */
Unknown
3D
mcellteam/mcell
libs/gperftools/src/span.cc
.cc
3,227
103
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #include <config.h> #include "span.h" #include <string.h> // for NULL, memset #include "internal_logging.h" // for ASSERT #include "page_heap_allocator.h" // for PageHeapAllocator #include "static_vars.h" // for Static namespace tcmalloc { #ifdef SPAN_HISTORY void Event(Span* span, char op, int v = 0) { span->history[span->nexthistory] = op; span->value[span->nexthistory] = v; span->nexthistory++; if (span->nexthistory == sizeof(span->history)) span->nexthistory = 0; } #endif Span* NewSpan(PageID p, Length len) { Span* result = Static::span_allocator()->New(); memset(result, 0, sizeof(*result)); result->start = p; result->length = len; #ifdef SPAN_HISTORY result->nexthistory = 0; #endif return result; } void DeleteSpan(Span* span) { #ifndef NDEBUG // In debug mode, trash the contents of deleted Spans memset(span, 0x3f, sizeof(*span)); #endif Static::span_allocator()->Delete(span); } void DLL_Init(Span* list) { list->next = list; list->prev = list; } void DLL_Remove(Span* span) { span->prev->next = span->next; span->next->prev = span->prev; span->prev = NULL; span->next = NULL; } int DLL_Length(const Span* list) { int result = 0; for (Span* s = list->next; s != list; s = s->next) { result++; } return result; } void DLL_Prepend(Span* list, Span* span) { ASSERT(span->next == NULL); ASSERT(span->prev == NULL); span->next = list->next; span->prev = list; list->next->prev = span; list->next = span; } } // namespace tcmalloc
Unknown
3D
mcellteam/mcell
libs/gperftools/src/raw_printer.h
.h
3,424
91
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // // A printf() wrapper that writes into a fixed length buffer. // Useful in low-level code that does not want to use allocating // routines like StringPrintf(). // // The implementation currently uses vsnprintf(). This seems to // be fine for use in many low-level contexts, but we may need to // rethink this decision if we hit a problem with it calling // down into malloc() etc. #ifndef BASE_RAW_PRINTER_H_ #define BASE_RAW_PRINTER_H_ #include <config.h> #include "base/basictypes.h" namespace base { class RawPrinter { public: // REQUIRES: "length > 0" // Will printf any data added to this into "buf[0,length-1]" and // will arrange to always keep buf[] null-terminated. RawPrinter(char* buf, int length); // Return the number of bytes that have been appended to the string // so far. Does not count any bytes that were dropped due to overflow. int length() const { return (ptr_ - base_); } // Return the number of bytes that can be added to this. int space_left() const { return (limit_ - ptr_); } // Format the supplied arguments according to the "format" string // and append to this. Will silently truncate the output if it does // not fit. void Printf(const char* format, ...) #ifdef HAVE___ATTRIBUTE__ __attribute__ ((__format__ (__printf__, 2, 3))) #endif ; private: // We can write into [ptr_ .. limit_-1]. // *limit_ is also writable, but reserved for a terminating \0 // in case we overflow. // // Invariants: *ptr_ == \0 // Invariants: *limit_ == \0 char* base_; // Initial pointer char* ptr_; // Where should we write next char* limit_; // One past last non-\0 char we can write DISALLOW_COPY_AND_ASSIGN(RawPrinter); }; } #endif // BASE_RAW_PRINTER_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/tcmalloc.cc
.cc
78,762
2,202
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> // // A malloc that uses a per-thread cache to satisfy small malloc requests. // (The time for malloc/free of a small object drops from 300 ns to 50 ns.) // // See docs/tcmalloc.html for a high-level // description of how this malloc works. // // SYNCHRONIZATION // 1. The thread-specific lists are accessed without acquiring any locks. // This is safe because each such list is only accessed by one thread. // 2. We have a lock per central free-list, and hold it while manipulating // the central free list for a particular size. // 3. The central page allocator is protected by "pageheap_lock". // 4. The pagemap (which maps from page-number to descriptor), // can be read without holding any locks, and written while holding // the "pageheap_lock". // 5. To improve performance, a subset of the information one can get // from the pagemap is cached in a data structure, pagemap_cache_, // that atomically reads and writes its entries. This cache can be // read and written without locking. // // This multi-threaded access to the pagemap is safe for fairly // subtle reasons. We basically assume that when an object X is // allocated by thread A and deallocated by thread B, there must // have been appropriate synchronization in the handoff of object // X from thread A to thread B. The same logic applies to pagemap_cache_. // // THE PAGEID-TO-SIZECLASS CACHE // Hot PageID-to-sizeclass mappings are held by pagemap_cache_. If this cache // returns 0 for a particular PageID then that means "no information," not that // the sizeclass is 0. The cache may have stale information for pages that do // not hold the beginning of any free()'able object. Staleness is eliminated // in Populate() for pages with sizeclass > 0 objects, and in do_malloc() and // do_memalign() for all other relevant pages. // // PAGEMAP // ------- // Page map contains a mapping from page id to Span. // // If Span s occupies pages [p..q], // pagemap[p] == s // pagemap[q] == s // pagemap[p+1..q-1] are undefined // pagemap[p-1] and pagemap[q+1] are defined: // NULL if the corresponding page is not yet in the address space. // Otherwise it points to a Span. This span may be free // or allocated. If free, it is in one of pageheap's freelist. // // TODO: Bias reclamation to larger addresses // TODO: implement mallinfo/mallopt // TODO: Better testing // // 9/28/2003 (new page-level allocator replaces ptmalloc2): // * malloc/free of small objects goes from ~300 ns to ~50 ns. // * allocation of a reasonably complicated struct // goes from about 1100 ns to about 300 ns. #include "config.h" // At least for gcc on Linux/i386 and Linux/amd64 not adding throw() // to tc_xxx functions actually ends up generating better code. #define PERFTOOLS_NOTHROW #include <gperftools/tcmalloc.h> #include <errno.h> // for ENOMEM, EINVAL, errno #if defined HAVE_STDINT_H #include <stdint.h> #elif defined HAVE_INTTYPES_H #include <inttypes.h> #else #include <sys/types.h> #endif #include <stddef.h> // for size_t, NULL #include <stdlib.h> // for getenv #include <string.h> // for strcmp, memset, strlen, etc #ifdef HAVE_UNISTD_H #include <unistd.h> // for getpagesize, write, etc #endif #include <algorithm> // for max, min #include <limits> // for numeric_limits #include <new> // for nothrow_t (ptr only), etc #include <vector> // for vector #include <gperftools/malloc_extension.h> #include <gperftools/malloc_hook.h> // for MallocHook #include <gperftools/nallocx.h> #include "base/basictypes.h" // for int64 #include "base/commandlineflags.h" // for RegisterFlagValidator, etc #include "base/dynamic_annotations.h" // for RunningOnValgrind #include "base/spinlock.h" // for SpinLockHolder #include "central_freelist.h" // for CentralFreeListPadded #include "common.h" // for StackTrace, kPageShift, etc #include "internal_logging.h" // for ASSERT, TCMalloc_Printer, etc #include "linked_list.h" // for SLL_SetNext #include "malloc_hook-inl.h" // for MallocHook::InvokeNewHook, etc #include "page_heap.h" // for PageHeap, PageHeap::Stats #include "page_heap_allocator.h" // for PageHeapAllocator #include "span.h" // for Span, DLL_Prepend, etc #include "stack_trace_table.h" // for StackTraceTable #include "static_vars.h" // for Static #include "system-alloc.h" // for DumpSystemAllocatorStats, etc #include "tcmalloc_guard.h" // for TCMallocGuard #include "thread_cache.h" // for ThreadCache #include "maybe_emergency_malloc.h" #if (defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)) && !defined(WIN32_OVERRIDE_ALLOCATORS) # define WIN32_DO_PATCHING 1 #endif // Some windows file somewhere (at least on cygwin) #define's small (!) #undef small using STL_NAMESPACE::max; using STL_NAMESPACE::min; using STL_NAMESPACE::numeric_limits; using STL_NAMESPACE::vector; #include "libc_override.h" using tcmalloc::AlignmentForSize; using tcmalloc::kLog; using tcmalloc::kCrash; using tcmalloc::kCrashWithStats; using tcmalloc::Log; using tcmalloc::PageHeap; using tcmalloc::PageHeapAllocator; using tcmalloc::SizeMap; using tcmalloc::Span; using tcmalloc::StackTrace; using tcmalloc::Static; using tcmalloc::ThreadCache; DECLARE_double(tcmalloc_release_rate); // Those common architectures are known to be safe w.r.t. aliasing function // with "extra" unused args to function with fewer arguments (e.g. // tc_delete_nothrow being aliased to tc_delete). // // Benefit of aliasing is relatively moderate. It reduces instruction // cache pressure a bit (not relevant for largely unused // tc_delete_nothrow, but is potentially relevant for // tc_delete_aligned (or sized)). It also used to be the case that gcc // 5+ optimization for merging identical functions kicked in and // "screwed" one of the otherwise identical functions with extra // jump. I am not able to reproduce that anymore. #if !defined(__i386__) && !defined(__x86_64__) && \ !defined(__ppc__) && !defined(__PPC__) && \ !defined(__aarch64__) && !defined(__mips__) && !defined(__arm__) #undef TCMALLOC_NO_ALIASES #define TCMALLOC_NO_ALIASES #endif #if defined(__GNUC__) && defined(__ELF__) && !defined(TCMALLOC_NO_ALIASES) #define TC_ALIAS(name) __attribute__((alias(#name))) #endif // For windows, the printf we use to report large allocs is // potentially dangerous: it could cause a malloc that would cause an // infinite loop. So by default we set the threshold to a huge number // on windows, so this bad situation will never trigger. You can // always set TCMALLOC_LARGE_ALLOC_REPORT_THRESHOLD manually if you // want this functionality. #ifdef _WIN32 const int64 kDefaultLargeAllocReportThreshold = static_cast<int64>(1) << 62; #else const int64 kDefaultLargeAllocReportThreshold = static_cast<int64>(1) << 30; #endif DEFINE_int64(tcmalloc_large_alloc_report_threshold, EnvToInt64("TCMALLOC_LARGE_ALLOC_REPORT_THRESHOLD", kDefaultLargeAllocReportThreshold), "Allocations larger than this value cause a stack " "trace to be dumped to stderr. The threshold for " "dumping stack traces is increased by a factor of 1.125 " "every time we print a message so that the threshold " "automatically goes up by a factor of ~1000 every 60 " "messages. This bounds the amount of extra logging " "generated by this flag. Default value of this flag " "is very large and therefore you should see no extra " "logging unless the flag is overridden. Set to 0 to " "disable reporting entirely."); // We already declared these functions in tcmalloc.h, but we have to // declare them again to give them an ATTRIBUTE_SECTION: we want to // put all callers of MallocHook::Invoke* in this module into // ATTRIBUTE_SECTION(google_malloc) section, so that // MallocHook::GetCallerStackTrace can function accurately. #ifndef _WIN32 // windows doesn't have attribute_section, so don't bother extern "C" { void* tc_malloc(size_t size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_free(void* ptr) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_free_sized(void* ptr, size_t size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_realloc(void* ptr, size_t size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_calloc(size_t nmemb, size_t size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_cfree(void* ptr) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_memalign(size_t __alignment, size_t __size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); int tc_posix_memalign(void** ptr, size_t align, size_t size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_valloc(size_t __size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_pvalloc(size_t __size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_malloc_stats(void) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); int tc_mallopt(int cmd, int value) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); #ifdef HAVE_STRUCT_MALLINFO struct mallinfo tc_mallinfo(void) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); #endif void* tc_new(size_t size) ATTRIBUTE_SECTION(google_malloc); void tc_delete(void* p) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_delete_sized(void* p, size_t size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_newarray(size_t size) ATTRIBUTE_SECTION(google_malloc); void tc_deletearray(void* p) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_deletearray_sized(void* p, size_t size) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); // And the nothrow variants of these: void* tc_new_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_newarray_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); // Surprisingly, standard C++ library implementations use a // nothrow-delete internally. See, eg: // http://www.dinkumware.com/manuals/?manual=compleat&page=new.html void tc_delete_nothrow(void* ptr, const std::nothrow_t&) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_deletearray_nothrow(void* ptr, const std::nothrow_t&) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); #if defined(ENABLE_ALIGNED_NEW_DELETE) void* tc_new_aligned(size_t size, std::align_val_t al) ATTRIBUTE_SECTION(google_malloc); void tc_delete_aligned(void* p, std::align_val_t al) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_delete_sized_aligned(void* p, size_t size, std::align_val_t al) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_newarray_aligned(size_t size, std::align_val_t al) ATTRIBUTE_SECTION(google_malloc); void tc_deletearray_aligned(void* p, std::align_val_t al) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_deletearray_sized_aligned(void* p, size_t size, std::align_val_t al) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); // And the nothrow variants of these: void* tc_new_aligned_nothrow(size_t size, std::align_val_t al, const std::nothrow_t&) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void* tc_newarray_aligned_nothrow(size_t size, std::align_val_t al, const std::nothrow_t&) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_delete_aligned_nothrow(void* ptr, std::align_val_t al, const std::nothrow_t&) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); void tc_deletearray_aligned_nothrow(void* ptr, std::align_val_t al, const std::nothrow_t&) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); #endif // defined(ENABLE_ALIGNED_NEW_DELETE) // Some non-standard extensions that we support. // This is equivalent to // OS X: malloc_size() // glibc: malloc_usable_size() // Windows: _msize() size_t tc_malloc_size(void* p) PERFTOOLS_NOTHROW ATTRIBUTE_SECTION(google_malloc); } // extern "C" #endif // #ifndef _WIN32 // ----------------------- IMPLEMENTATION ------------------------------- static int tc_new_mode = 0; // See tc_set_new_mode(). // Routines such as free() and realloc() catch some erroneous pointers // passed to them, and invoke the below when they do. (An erroneous pointer // won't be caught if it's within a valid span or a stale span for which // the pagemap cache has a non-zero sizeclass.) This is a cheap (source-editing // required) kind of exception handling for these routines. namespace { ATTRIBUTE_NOINLINE void InvalidFree(void* ptr) { if (tcmalloc::IsEmergencyPtr(ptr)) { tcmalloc::EmergencyFree(ptr); return; } Log(kCrash, __FILE__, __LINE__, "Attempt to free invalid pointer", ptr); } size_t InvalidGetSizeForRealloc(const void* old_ptr) { Log(kCrash, __FILE__, __LINE__, "Attempt to realloc invalid pointer", old_ptr); return 0; } size_t InvalidGetAllocatedSize(const void* ptr) { Log(kCrash, __FILE__, __LINE__, "Attempt to get the size of an invalid pointer", ptr); return 0; } } // unnamed namespace // Extract interesting stats struct TCMallocStats { uint64_t thread_bytes; // Bytes in thread caches uint64_t central_bytes; // Bytes in central cache uint64_t transfer_bytes; // Bytes in central transfer cache uint64_t metadata_bytes; // Bytes alloced for metadata PageHeap::Stats pageheap; // Stats from page heap }; // Get stats into "r". Also, if class_count != NULL, class_count[k] // will be set to the total number of objects of size class k in the // central cache, transfer cache, and per-thread caches. If small_spans // is non-NULL, it is filled. Same for large_spans. static void ExtractStats(TCMallocStats* r, uint64_t* class_count, PageHeap::SmallSpanStats* small_spans, PageHeap::LargeSpanStats* large_spans) { r->central_bytes = 0; r->transfer_bytes = 0; for (int cl = 0; cl < Static::num_size_classes(); ++cl) { const int length = Static::central_cache()[cl].length(); const int tc_length = Static::central_cache()[cl].tc_length(); const size_t cache_overhead = Static::central_cache()[cl].OverheadBytes(); const size_t size = static_cast<uint64_t>( Static::sizemap()->ByteSizeForClass(cl)); r->central_bytes += (size * length) + cache_overhead; r->transfer_bytes += (size * tc_length); if (class_count) { // Sum the lengths of all per-class freelists, except the per-thread // freelists, which get counted when we call GetThreadStats(), below. class_count[cl] = length + tc_length; } } // Add stats from per-thread heaps r->thread_bytes = 0; { // scope SpinLockHolder h(Static::pageheap_lock()); ThreadCache::GetThreadStats(&r->thread_bytes, class_count); r->metadata_bytes = tcmalloc::metadata_system_bytes(); r->pageheap = Static::pageheap()->stats(); if (small_spans != NULL) { Static::pageheap()->GetSmallSpanStats(small_spans); } if (large_spans != NULL) { Static::pageheap()->GetLargeSpanStats(large_spans); } } } static double PagesToMiB(uint64_t pages) { return (pages << kPageShift) / 1048576.0; } // WRITE stats to "out" static void DumpStats(TCMalloc_Printer* out, int level) { TCMallocStats stats; uint64_t class_count[kClassSizesMax]; PageHeap::SmallSpanStats small; PageHeap::LargeSpanStats large; if (level >= 2) { ExtractStats(&stats, class_count, &small, &large); } else { ExtractStats(&stats, NULL, NULL, NULL); } static const double MiB = 1048576.0; const uint64_t virtual_memory_used = (stats.pageheap.system_bytes + stats.metadata_bytes); const uint64_t physical_memory_used = (virtual_memory_used - stats.pageheap.unmapped_bytes); const uint64_t bytes_in_use_by_app = (physical_memory_used - stats.metadata_bytes - stats.pageheap.free_bytes - stats.central_bytes - stats.transfer_bytes - stats.thread_bytes); #ifdef TCMALLOC_SMALL_BUT_SLOW out->printf( "NOTE: SMALL MEMORY MODEL IS IN USE, PERFORMANCE MAY SUFFER.\n"); #endif out->printf( "------------------------------------------------\n" "MALLOC: %12" PRIu64 " (%7.1f MiB) Bytes in use by application\n" "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in page heap freelist\n" "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in central cache freelist\n" "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in transfer cache freelist\n" "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in thread cache freelists\n" "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in malloc metadata\n" "MALLOC: ------------\n" "MALLOC: = %12" PRIu64 " (%7.1f MiB) Actual memory used (physical + swap)\n" "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes released to OS (aka unmapped)\n" "MALLOC: ------------\n" "MALLOC: = %12" PRIu64 " (%7.1f MiB) Virtual address space used\n" "MALLOC:\n" "MALLOC: %12" PRIu64 " Spans in use\n" "MALLOC: %12" PRIu64 " Thread heaps in use\n" "MALLOC: %12" PRIu64 " Tcmalloc page size\n" "------------------------------------------------\n" "Call ReleaseFreeMemory() to release freelist memory to the OS" " (via madvise()).\n" "Bytes released to the OS take up virtual address space" " but no physical memory.\n", bytes_in_use_by_app, bytes_in_use_by_app / MiB, stats.pageheap.free_bytes, stats.pageheap.free_bytes / MiB, stats.central_bytes, stats.central_bytes / MiB, stats.transfer_bytes, stats.transfer_bytes / MiB, stats.thread_bytes, stats.thread_bytes / MiB, stats.metadata_bytes, stats.metadata_bytes / MiB, physical_memory_used, physical_memory_used / MiB, stats.pageheap.unmapped_bytes, stats.pageheap.unmapped_bytes / MiB, virtual_memory_used, virtual_memory_used / MiB, uint64_t(Static::span_allocator()->inuse()), uint64_t(ThreadCache::HeapsInUse()), uint64_t(kPageSize)); if (level >= 2) { out->printf("------------------------------------------------\n"); out->printf("Total size of freelists for per-thread caches,\n"); out->printf("transfer cache, and central cache, by size class\n"); out->printf("------------------------------------------------\n"); uint64_t cumulative_bytes = 0; uint64_t cumulative_overhead = 0; for (uint32 cl = 0; cl < Static::num_size_classes(); ++cl) { if (class_count[cl] > 0) { size_t cl_size = Static::sizemap()->ByteSizeForClass(cl); const uint64_t class_bytes = class_count[cl] * cl_size; cumulative_bytes += class_bytes; const uint64_t class_overhead = Static::central_cache()[cl].OverheadBytes(); cumulative_overhead += class_overhead; out->printf("class %3d [ %8" PRIuS " bytes ] : " "%8" PRIu64 " objs; %5.1f MiB; %5.1f cum MiB; " "%8.3f overhead MiB; %8.3f cum overhead MiB\n", cl, cl_size, class_count[cl], class_bytes / MiB, cumulative_bytes / MiB, class_overhead / MiB, cumulative_overhead / MiB); } } // append page heap info int nonempty_sizes = 0; for (int s = 0; s < kMaxPages; s++) { if (small.normal_length[s] + small.returned_length[s] > 0) { nonempty_sizes++; } } out->printf("------------------------------------------------\n"); out->printf("PageHeap: %d sizes; %6.1f MiB free; %6.1f MiB unmapped\n", nonempty_sizes, stats.pageheap.free_bytes / MiB, stats.pageheap.unmapped_bytes / MiB); out->printf("------------------------------------------------\n"); uint64_t total_normal = 0; uint64_t total_returned = 0; for (int s = 1; s <= kMaxPages; s++) { const int n_length = small.normal_length[s - 1]; const int r_length = small.returned_length[s - 1]; if (n_length + r_length > 0) { uint64_t n_pages = s * n_length; uint64_t r_pages = s * r_length; total_normal += n_pages; total_returned += r_pages; out->printf("%6u pages * %6u spans ~ %6.1f MiB; %6.1f MiB cum" "; unmapped: %6.1f MiB; %6.1f MiB cum\n", s, (n_length + r_length), PagesToMiB(n_pages + r_pages), PagesToMiB(total_normal + total_returned), PagesToMiB(r_pages), PagesToMiB(total_returned)); } } total_normal += large.normal_pages; total_returned += large.returned_pages; out->printf(">%-5u large * %6u spans ~ %6.1f MiB; %6.1f MiB cum" "; unmapped: %6.1f MiB; %6.1f MiB cum\n", static_cast<unsigned int>(kMaxPages), static_cast<unsigned int>(large.spans), PagesToMiB(large.normal_pages + large.returned_pages), PagesToMiB(total_normal + total_returned), PagesToMiB(large.returned_pages), PagesToMiB(total_returned)); } } static void PrintStats(int level) { const int kBufferSize = 16 << 10; char* buffer = new char[kBufferSize]; TCMalloc_Printer printer(buffer, kBufferSize); DumpStats(&printer, level); write(STDERR_FILENO, buffer, strlen(buffer)); delete[] buffer; } static void** DumpHeapGrowthStackTraces() { // Count how much space we need int needed_slots = 0; { SpinLockHolder h(Static::pageheap_lock()); for (StackTrace* t = Static::growth_stacks(); t != NULL; t = reinterpret_cast<StackTrace*>( t->stack[tcmalloc::kMaxStackDepth-1])) { needed_slots += 3 + t->depth; } needed_slots += 100; // Slop in case list grows needed_slots += needed_slots/8; // An extra 12.5% slop } void** result = new void*[needed_slots]; if (result == NULL) { Log(kLog, __FILE__, __LINE__, "tcmalloc: allocation failed for stack trace slots", needed_slots * sizeof(*result)); return NULL; } SpinLockHolder h(Static::pageheap_lock()); int used_slots = 0; for (StackTrace* t = Static::growth_stacks(); t != NULL; t = reinterpret_cast<StackTrace*>( t->stack[tcmalloc::kMaxStackDepth-1])) { ASSERT(used_slots < needed_slots); // Need to leave room for terminator if (used_slots + 3 + t->depth >= needed_slots) { // No more room break; } result[used_slots+0] = reinterpret_cast<void*>(static_cast<uintptr_t>(1)); result[used_slots+1] = reinterpret_cast<void*>(t->size); result[used_slots+2] = reinterpret_cast<void*>(t->depth); for (int d = 0; d < t->depth; d++) { result[used_slots+3+d] = t->stack[d]; } used_slots += 3 + t->depth; } result[used_slots] = reinterpret_cast<void*>(static_cast<uintptr_t>(0)); return result; } static void IterateOverRanges(void* arg, MallocExtension::RangeFunction func) { PageID page = 1; // Some code may assume that page==0 is never used bool done = false; while (!done) { // Accumulate a small number of ranges in a local buffer static const int kNumRanges = 16; static base::MallocRange ranges[kNumRanges]; int n = 0; { SpinLockHolder h(Static::pageheap_lock()); while (n < kNumRanges) { if (!Static::pageheap()->GetNextRange(page, &ranges[n])) { done = true; break; } else { uintptr_t limit = ranges[n].address + ranges[n].length; page = (limit + kPageSize - 1) >> kPageShift; n++; } } } for (int i = 0; i < n; i++) { (*func)(arg, &ranges[i]); } } } // TCMalloc's support for extra malloc interfaces class TCMallocImplementation : public MallocExtension { private: // ReleaseToSystem() might release more than the requested bytes because // the page heap releases at the span granularity, and spans are of wildly // different sizes. This member keeps track of the extra bytes bytes // released so that the app can periodically call ReleaseToSystem() to // release memory at a constant rate. // NOTE: Protected by Static::pageheap_lock(). size_t extra_bytes_released_; public: TCMallocImplementation() : extra_bytes_released_(0) { } virtual void GetStats(char* buffer, int buffer_length) { ASSERT(buffer_length > 0); TCMalloc_Printer printer(buffer, buffer_length); // Print level one stats unless lots of space is available if (buffer_length < 10000) { DumpStats(&printer, 1); } else { DumpStats(&printer, 2); } } // We may print an extra, tcmalloc-specific warning message here. virtual void GetHeapSample(MallocExtensionWriter* writer) { if (FLAGS_tcmalloc_sample_parameter == 0) { const char* const kWarningMsg = "%warn\n" "%warn This heap profile does not have any data in it, because\n" "%warn the application was run with heap sampling turned off.\n" "%warn To get useful data from GetHeapSample(), you must\n" "%warn set the environment variable TCMALLOC_SAMPLE_PARAMETER to\n" "%warn a positive sampling period, such as 524288.\n" "%warn\n"; writer->append(kWarningMsg, strlen(kWarningMsg)); } MallocExtension::GetHeapSample(writer); } virtual void** ReadStackTraces(int* sample_period) { tcmalloc::StackTraceTable table; { SpinLockHolder h(Static::pageheap_lock()); Span* sampled = Static::sampled_objects(); for (Span* s = sampled->next; s != sampled; s = s->next) { table.AddTrace(*reinterpret_cast<StackTrace*>(s->objects)); } } *sample_period = ThreadCache::GetCache()->GetSamplePeriod(); return table.ReadStackTracesAndClear(); // grabs and releases pageheap_lock } virtual void** ReadHeapGrowthStackTraces() { return DumpHeapGrowthStackTraces(); } virtual size_t GetThreadCacheSize() { ThreadCache* tc = ThreadCache::GetCacheIfPresent(); if (!tc) return 0; return tc->Size(); } virtual void MarkThreadTemporarilyIdle() { ThreadCache::BecomeTemporarilyIdle(); } virtual void Ranges(void* arg, RangeFunction func) { IterateOverRanges(arg, func); } virtual bool GetNumericProperty(const char* name, size_t* value) { ASSERT(name != NULL); if (strcmp(name, "generic.current_allocated_bytes") == 0) { TCMallocStats stats; ExtractStats(&stats, NULL, NULL, NULL); *value = stats.pageheap.system_bytes - stats.thread_bytes - stats.central_bytes - stats.transfer_bytes - stats.pageheap.free_bytes - stats.pageheap.unmapped_bytes; return true; } if (strcmp(name, "generic.heap_size") == 0) { TCMallocStats stats; ExtractStats(&stats, NULL, NULL, NULL); *value = stats.pageheap.system_bytes; return true; } if (strcmp(name, "generic.total_physical_bytes") == 0) { TCMallocStats stats; ExtractStats(&stats, NULL, NULL, NULL); *value = stats.pageheap.system_bytes + stats.metadata_bytes - stats.pageheap.unmapped_bytes; return true; } if (strcmp(name, "tcmalloc.slack_bytes") == 0) { // Kept for backwards compatibility. Now defined externally as: // pageheap_free_bytes + pageheap_unmapped_bytes. SpinLockHolder l(Static::pageheap_lock()); PageHeap::Stats stats = Static::pageheap()->stats(); *value = stats.free_bytes + stats.unmapped_bytes; return true; } if (strcmp(name, "tcmalloc.central_cache_free_bytes") == 0) { TCMallocStats stats; ExtractStats(&stats, NULL, NULL, NULL); *value = stats.central_bytes; return true; } if (strcmp(name, "tcmalloc.transfer_cache_free_bytes") == 0) { TCMallocStats stats; ExtractStats(&stats, NULL, NULL, NULL); *value = stats.transfer_bytes; return true; } if (strcmp(name, "tcmalloc.thread_cache_free_bytes") == 0) { TCMallocStats stats; ExtractStats(&stats, NULL, NULL, NULL); *value = stats.thread_bytes; return true; } if (strcmp(name, "tcmalloc.pageheap_free_bytes") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().free_bytes; return true; } if (strcmp(name, "tcmalloc.pageheap_unmapped_bytes") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().unmapped_bytes; return true; } if (strcmp(name, "tcmalloc.pageheap_committed_bytes") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().committed_bytes; return true; } if (strcmp(name, "tcmalloc.pageheap_scavenge_count") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().scavenge_count; return true; } if (strcmp(name, "tcmalloc.pageheap_commit_count") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().commit_count; return true; } if (strcmp(name, "tcmalloc.pageheap_total_commit_bytes") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().total_commit_bytes; return true; } if (strcmp(name, "tcmalloc.pageheap_decommit_count") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().decommit_count; return true; } if (strcmp(name, "tcmalloc.pageheap_total_decommit_bytes") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().total_decommit_bytes; return true; } if (strcmp(name, "tcmalloc.pageheap_reserve_count") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().reserve_count; return true; } if (strcmp(name, "tcmalloc.pageheap_total_reserve_bytes") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = Static::pageheap()->stats().total_reserve_bytes; return true; } if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = ThreadCache::overall_thread_cache_size(); return true; } if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) { TCMallocStats stats; ExtractStats(&stats, NULL, NULL, NULL); *value = stats.thread_bytes; return true; } if (strcmp(name, "tcmalloc.aggressive_memory_decommit") == 0) { SpinLockHolder l(Static::pageheap_lock()); *value = size_t(Static::pageheap()->GetAggressiveDecommit()); return true; } return false; } virtual bool SetNumericProperty(const char* name, size_t value) { ASSERT(name != NULL); if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) { SpinLockHolder l(Static::pageheap_lock()); ThreadCache::set_overall_thread_cache_size(value); return true; } if (strcmp(name, "tcmalloc.aggressive_memory_decommit") == 0) { SpinLockHolder l(Static::pageheap_lock()); Static::pageheap()->SetAggressiveDecommit(value != 0); return true; } return false; } virtual void MarkThreadIdle() { ThreadCache::BecomeIdle(); } virtual void MarkThreadBusy(); // Implemented below virtual SysAllocator* GetSystemAllocator() { SpinLockHolder h(Static::pageheap_lock()); return tcmalloc_sys_alloc; } virtual void SetSystemAllocator(SysAllocator* alloc) { SpinLockHolder h(Static::pageheap_lock()); tcmalloc_sys_alloc = alloc; } virtual void ReleaseToSystem(size_t num_bytes) { SpinLockHolder h(Static::pageheap_lock()); if (num_bytes <= extra_bytes_released_) { // We released too much on a prior call, so don't release any // more this time. extra_bytes_released_ = extra_bytes_released_ - num_bytes; return; } num_bytes = num_bytes - extra_bytes_released_; // num_bytes might be less than one page. If we pass zero to // ReleaseAtLeastNPages, it won't do anything, so we release a whole // page now and let extra_bytes_released_ smooth it out over time. Length num_pages = max<Length>(num_bytes >> kPageShift, 1); size_t bytes_released = Static::pageheap()->ReleaseAtLeastNPages( num_pages) << kPageShift; if (bytes_released > num_bytes) { extra_bytes_released_ = bytes_released - num_bytes; } else { // The PageHeap wasn't able to release num_bytes. Don't try to // compensate with a big release next time. Specifically, // ReleaseFreeMemory() calls ReleaseToSystem(LONG_MAX). extra_bytes_released_ = 0; } } virtual void SetMemoryReleaseRate(double rate) { FLAGS_tcmalloc_release_rate = rate; } virtual double GetMemoryReleaseRate() { return FLAGS_tcmalloc_release_rate; } virtual size_t GetEstimatedAllocatedSize(size_t size); // This just calls GetSizeWithCallback, but because that's in an // unnamed namespace, we need to move the definition below it in the // file. virtual size_t GetAllocatedSize(const void* ptr); // This duplicates some of the logic in GetSizeWithCallback, but is // faster. This is important on OS X, where this function is called // on every allocation operation. virtual Ownership GetOwnership(const void* ptr) { const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift; // The rest of tcmalloc assumes that all allocated pointers use at // most kAddressBits bits. If ptr doesn't, then it definitely // wasn't alloacted by tcmalloc. if ((p >> (kAddressBits - kPageShift)) > 0) { return kNotOwned; } uint32 cl; if (Static::pageheap()->TryGetSizeClass(p, &cl)) { return kOwned; } const Span *span = Static::pageheap()->GetDescriptor(p); return span ? kOwned : kNotOwned; } virtual void GetFreeListSizes(vector<MallocExtension::FreeListInfo>* v) { static const char kCentralCacheType[] = "tcmalloc.central"; static const char kTransferCacheType[] = "tcmalloc.transfer"; static const char kThreadCacheType[] = "tcmalloc.thread"; static const char kPageHeapType[] = "tcmalloc.page"; static const char kPageHeapUnmappedType[] = "tcmalloc.page_unmapped"; static const char kLargeSpanType[] = "tcmalloc.large"; static const char kLargeUnmappedSpanType[] = "tcmalloc.large_unmapped"; v->clear(); // central class information int64 prev_class_size = 0; for (int cl = 1; cl < Static::num_size_classes(); ++cl) { size_t class_size = Static::sizemap()->ByteSizeForClass(cl); MallocExtension::FreeListInfo i; i.min_object_size = prev_class_size + 1; i.max_object_size = class_size; i.total_bytes_free = Static::central_cache()[cl].length() * class_size; i.type = kCentralCacheType; v->push_back(i); // transfer cache i.total_bytes_free = Static::central_cache()[cl].tc_length() * class_size; i.type = kTransferCacheType; v->push_back(i); prev_class_size = Static::sizemap()->ByteSizeForClass(cl); } // Add stats from per-thread heaps uint64_t class_count[kClassSizesMax]; memset(class_count, 0, sizeof(class_count)); { SpinLockHolder h(Static::pageheap_lock()); uint64_t thread_bytes = 0; ThreadCache::GetThreadStats(&thread_bytes, class_count); } prev_class_size = 0; for (int cl = 1; cl < Static::num_size_classes(); ++cl) { MallocExtension::FreeListInfo i; i.min_object_size = prev_class_size + 1; i.max_object_size = Static::sizemap()->ByteSizeForClass(cl); i.total_bytes_free = class_count[cl] * Static::sizemap()->ByteSizeForClass(cl); i.type = kThreadCacheType; v->push_back(i); prev_class_size = Static::sizemap()->ByteSizeForClass(cl); } // append page heap info PageHeap::SmallSpanStats small; PageHeap::LargeSpanStats large; { SpinLockHolder h(Static::pageheap_lock()); Static::pageheap()->GetSmallSpanStats(&small); Static::pageheap()->GetLargeSpanStats(&large); } // large spans: mapped MallocExtension::FreeListInfo span_info; span_info.type = kLargeSpanType; span_info.max_object_size = (numeric_limits<size_t>::max)(); span_info.min_object_size = kMaxPages << kPageShift; span_info.total_bytes_free = large.normal_pages << kPageShift; v->push_back(span_info); // large spans: unmapped span_info.type = kLargeUnmappedSpanType; span_info.total_bytes_free = large.returned_pages << kPageShift; v->push_back(span_info); // small spans for (int s = 1; s <= kMaxPages; s++) { MallocExtension::FreeListInfo i; i.max_object_size = (s << kPageShift); i.min_object_size = ((s - 1) << kPageShift); i.type = kPageHeapType; i.total_bytes_free = (s << kPageShift) * small.normal_length[s - 1]; v->push_back(i); i.type = kPageHeapUnmappedType; i.total_bytes_free = (s << kPageShift) * small.returned_length[s - 1]; v->push_back(i); } } }; static inline ATTRIBUTE_ALWAYS_INLINE size_t align_size_up(size_t size, size_t align) { ASSERT(align <= kPageSize); size_t new_size = (size + align - 1) & ~(align - 1); if (PREDICT_FALSE(new_size == 0)) { // Note, new_size == 0 catches both integer overflow and size // being 0. if (size == 0) { new_size = align; } else { new_size = size; } } return new_size; } // Puts in *cl size class that is suitable for allocation of size bytes with // align alignment. Returns true if such size class exists and false otherwise. static bool size_class_with_alignment(size_t size, size_t align, uint32_t* cl) { if (PREDICT_FALSE(align > kPageSize)) { return false; } size = align_size_up(size, align); if (PREDICT_FALSE(!Static::sizemap()->GetSizeClass(size, cl))) { return false; } ASSERT((Static::sizemap()->class_to_size(*cl) & (align - 1)) == 0); return true; } // nallocx slow path. Moved to a separate function because // ThreadCache::InitModule is not inlined which would cause nallocx to // become non-leaf function with stack frame and stack spills. static ATTRIBUTE_NOINLINE size_t nallocx_slow(size_t size, int flags) { if (PREDICT_FALSE(!Static::IsInited())) ThreadCache::InitModule(); size_t align = static_cast<size_t>(1ull << (flags & 0x3f)); uint32 cl; bool ok = size_class_with_alignment(size, align, &cl); if (ok) { return Static::sizemap()->ByteSizeForClass(cl); } else { return tcmalloc::pages(size) << kPageShift; } } // The nallocx function allocates no memory, but it performs the same size // computation as the malloc function, and returns the real size of the // allocation that would result from the equivalent malloc function call. // nallocx is a malloc extension originally implemented by jemalloc: // http://www.unix.com/man-page/freebsd/3/nallocx/ extern "C" PERFTOOLS_DLL_DECL size_t tc_nallocx(size_t size, int flags) { if (PREDICT_FALSE(flags != 0)) { return nallocx_slow(size, flags); } uint32 cl; // size class 0 is only possible if malloc is not yet initialized if (Static::sizemap()->GetSizeClass(size, &cl) && cl != 0) { return Static::sizemap()->ByteSizeForClass(cl); } else { return nallocx_slow(size, 0); } } extern "C" PERFTOOLS_DLL_DECL size_t nallocx(size_t size, int flags) #ifdef TC_ALIAS TC_ALIAS(tc_nallocx); #else { return nallocx_slow(size, flags); } #endif size_t TCMallocImplementation::GetEstimatedAllocatedSize(size_t size) { return tc_nallocx(size, 0); } // The constructor allocates an object to ensure that initialization // runs before main(), and therefore we do not have a chance to become // multi-threaded before initialization. We also create the TSD key // here. Presumably by the time this constructor runs, glibc is in // good enough shape to handle pthread_key_create(). // // The constructor also takes the opportunity to tell STL to use // tcmalloc. We want to do this early, before construct time, so // all user STL allocations go through tcmalloc (which works really // well for STL). // // The destructor prints stats when the program exits. static int tcmallocguard_refcount = 0; // no lock needed: runs before main() TCMallocGuard::TCMallocGuard() { if (tcmallocguard_refcount++ == 0) { ReplaceSystemAlloc(); // defined in libc_override_*.h tc_free(tc_malloc(1)); ThreadCache::InitTSD(); tc_free(tc_malloc(1)); // Either we, or debugallocation.cc, or valgrind will control memory // management. We register our extension if we're the winner. #ifdef TCMALLOC_USING_DEBUGALLOCATION // Let debugallocation register its extension. #else if (RunningOnValgrind()) { // Let Valgrind uses its own malloc (so don't register our extension). } else { MallocExtension::Register(new TCMallocImplementation); } #endif } } TCMallocGuard::~TCMallocGuard() { if (--tcmallocguard_refcount == 0) { const char* env = NULL; if (!RunningOnValgrind()) { // Valgrind uses it's own malloc so we cannot do MALLOCSTATS env = getenv("MALLOCSTATS"); } if (env != NULL) { int level = atoi(env); if (level < 1) level = 1; PrintStats(level); } } } #ifndef WIN32_OVERRIDE_ALLOCATORS static TCMallocGuard module_enter_exit_hook; #endif //------------------------------------------------------------------- // Helpers for the exported routines below //------------------------------------------------------------------- static inline bool CheckCachedSizeClass(void *ptr) { PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift; uint32 cached_value; if (!Static::pageheap()->TryGetSizeClass(p, &cached_value)) { return true; } return cached_value == Static::pageheap()->GetDescriptor(p)->sizeclass; } static inline ATTRIBUTE_ALWAYS_INLINE void* CheckedMallocResult(void *result) { ASSERT(result == NULL || CheckCachedSizeClass(result)); return result; } static inline ATTRIBUTE_ALWAYS_INLINE void* SpanToMallocResult(Span *span) { Static::pageheap()->InvalidateCachedSizeClass(span->start); return CheckedMallocResult(reinterpret_cast<void*>(span->start << kPageShift)); } static void* DoSampledAllocation(size_t size) { #ifndef NO_TCMALLOC_SAMPLES // Grab the stack trace outside the heap lock StackTrace tmp; tmp.depth = GetStackTrace(tmp.stack, tcmalloc::kMaxStackDepth, 1); tmp.size = size; SpinLockHolder h(Static::pageheap_lock()); // Allocate span Span *span = Static::pageheap()->New(tcmalloc::pages(size == 0 ? 1 : size)); if (PREDICT_FALSE(span == NULL)) { return NULL; } // Allocate stack trace StackTrace *stack = Static::stacktrace_allocator()->New(); if (PREDICT_FALSE(stack == NULL)) { // Sampling failed because of lack of memory return span; } *stack = tmp; span->sample = 1; span->objects = stack; tcmalloc::DLL_Prepend(Static::sampled_objects(), span); return SpanToMallocResult(span); #else abort(); #endif } namespace { typedef void* (*malloc_fn)(void *arg); SpinLock set_new_handler_lock(SpinLock::LINKER_INITIALIZED); void* handle_oom(malloc_fn retry_fn, void* retry_arg, bool from_operator, bool nothrow) { // we hit out of memory condition, usually if it happens we've // called sbrk or mmap and failed, and thus errno is set. But there // is support for setting up custom system allocator or setting up // page heap size limit, in which cases errno may remain // untouched. // // So we set errno here. C++ operator new doesn't require ENOMEM to // be set, but doesn't forbid it too (and often C++ oom does happen // with ENOMEM set). errno = ENOMEM; if (!from_operator && !tc_new_mode) { // we're out of memory in C library function (malloc etc) and no // "new mode" forced on us. Just return NULL return NULL; } // we're OOM in operator new or "new mode" is set. We might have to // call new_handle and maybe retry allocation. for (;;) { // Get the current new handler. NB: this function is not // thread-safe. We make a feeble stab at making it so here, but // this lock only protects against tcmalloc interfering with // itself, not with other libraries calling set_new_handler. std::new_handler nh; { SpinLockHolder h(&set_new_handler_lock); nh = std::set_new_handler(0); (void) std::set_new_handler(nh); } #if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS) if (!nh) { return NULL; } // Since exceptions are disabled, we don't really know if new_handler // failed. Assume it will abort if it fails. (*nh)(); #else // If no new_handler is established, the allocation failed. if (!nh) { if (nothrow) { return NULL; } throw std::bad_alloc(); } // Otherwise, try the new_handler. If it returns, retry the // allocation. If it throws std::bad_alloc, fail the allocation. // if it throws something else, don't interfere. try { (*nh)(); } catch (const std::bad_alloc&) { if (!nothrow) throw; return NULL; } #endif // (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS) // we get here if new_handler returns successfully. So we retry // allocation. void* rv = retry_fn(retry_arg); if (rv != NULL) { return rv; } // if allocation failed again we go to next loop iteration } } // Copy of FLAGS_tcmalloc_large_alloc_report_threshold with // automatic increases factored in. #ifdef ENABLE_LARGE_ALLOC_REPORT static int64_t large_alloc_threshold = (kPageSize > FLAGS_tcmalloc_large_alloc_report_threshold ? kPageSize : FLAGS_tcmalloc_large_alloc_report_threshold); #endif static void ReportLargeAlloc(Length num_pages, void* result) { StackTrace stack; stack.depth = GetStackTrace(stack.stack, tcmalloc::kMaxStackDepth, 1); static const int N = 1000; char buffer[N]; TCMalloc_Printer printer(buffer, N); printer.printf("tcmalloc: large alloc %" PRIu64 " bytes == %p @ ", static_cast<uint64>(num_pages) << kPageShift, result); for (int i = 0; i < stack.depth; i++) { printer.printf(" %p", stack.stack[i]); } printer.printf("\n"); write(STDERR_FILENO, buffer, strlen(buffer)); } // Must be called with the page lock held. inline bool should_report_large(Length num_pages) { #ifdef ENABLE_LARGE_ALLOC_REPORT const int64 threshold = large_alloc_threshold; if (threshold > 0 && num_pages >= (threshold >> kPageShift)) { // Increase the threshold by 1/8 every time we generate a report. // We cap the threshold at 8GiB to avoid overflow problems. large_alloc_threshold = (threshold + threshold/8 < 8ll<<30 ? threshold + threshold/8 : 8ll<<30); return true; } #endif return false; } // Helper for do_malloc(). static void* do_malloc_pages(ThreadCache* heap, size_t size) { void* result; bool report_large; Length num_pages = tcmalloc::pages(size); // NOTE: we're passing original size here as opposed to rounded-up // size as we do in do_malloc_small. The difference is small here // (at most 4k out of at least 256k). And not rounding up saves us // from possibility of overflow, which rounding up could produce. // // See https://github.com/gperftools/gperftools/issues/723 if (heap->SampleAllocation(size)) { result = DoSampledAllocation(size); SpinLockHolder h(Static::pageheap_lock()); report_large = should_report_large(num_pages); } else { SpinLockHolder h(Static::pageheap_lock()); Span* span = Static::pageheap()->New(num_pages); result = (PREDICT_FALSE(span == NULL) ? NULL : SpanToMallocResult(span)); report_large = should_report_large(num_pages); } if (report_large) { ReportLargeAlloc(num_pages, result); } return result; } static void *nop_oom_handler(size_t size) { return NULL; } ATTRIBUTE_ALWAYS_INLINE inline void* do_malloc(size_t size) { if (PREDICT_FALSE(ThreadCache::IsUseEmergencyMalloc())) { return tcmalloc::EmergencyMalloc(size); } // note: it will force initialization of malloc if necessary ThreadCache* cache = ThreadCache::GetCache(); uint32 cl; ASSERT(Static::IsInited()); ASSERT(cache != NULL); if (PREDICT_FALSE(!Static::sizemap()->GetSizeClass(size, &cl))) { return do_malloc_pages(cache, size); } size_t allocated_size = Static::sizemap()->class_to_size(cl); if (PREDICT_FALSE(cache->SampleAllocation(allocated_size))) { return DoSampledAllocation(size); } // The common case, and also the simplest. This just pops the // size-appropriate freelist, after replenishing it if it's empty. return CheckedMallocResult(cache->Allocate(allocated_size, cl, nop_oom_handler)); } static void *retry_malloc(void* size) { return do_malloc(reinterpret_cast<size_t>(size)); } ATTRIBUTE_ALWAYS_INLINE inline void* do_malloc_or_cpp_alloc(size_t size) { void *rv = do_malloc(size); if (PREDICT_TRUE(rv != NULL)) { return rv; } return handle_oom(retry_malloc, reinterpret_cast<void *>(size), false, true); } ATTRIBUTE_ALWAYS_INLINE inline void* do_calloc(size_t n, size_t elem_size) { // Overflow check const size_t size = n * elem_size; if (elem_size != 0 && size / elem_size != n) return NULL; void* result = do_malloc_or_cpp_alloc(size); if (result != NULL) { memset(result, 0, tc_nallocx(size, 0)); } return result; } // If ptr is NULL, do nothing. Otherwise invoke the given function. inline void free_null_or_invalid(void* ptr, void (*invalid_free_fn)(void*)) { if (ptr != NULL) { (*invalid_free_fn)(ptr); } } static ATTRIBUTE_NOINLINE void do_free_pages(Span* span, void* ptr) { SpinLockHolder h(Static::pageheap_lock()); if (span->sample) { StackTrace* st = reinterpret_cast<StackTrace*>(span->objects); tcmalloc::DLL_Remove(span); Static::stacktrace_allocator()->Delete(st); span->objects = NULL; } Static::pageheap()->Delete(span); } // Helper for the object deletion (free, delete, etc.). Inputs: // ptr is object to be freed // invalid_free_fn is a function that gets invoked on certain "bad frees" // // We can usually detect the case where ptr is not pointing to a page that // tcmalloc is using, and in those cases we invoke invalid_free_fn. ATTRIBUTE_ALWAYS_INLINE inline void do_free_with_callback(void* ptr, void (*invalid_free_fn)(void*), bool use_hint, size_t size_hint) { ThreadCache* heap = ThreadCache::GetCacheIfPresent(); const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift; uint32 cl; #ifndef NO_TCMALLOC_SAMPLES // we only pass size hint when ptr is not page aligned. Which // implies that it must be very small object. ASSERT(!use_hint || size_hint < kPageSize); #endif if (!use_hint || PREDICT_FALSE(!Static::sizemap()->GetSizeClass(size_hint, &cl))) { // if we're in sized delete, but size is too large, no need to // probe size cache bool cache_hit = !use_hint && Static::pageheap()->TryGetSizeClass(p, &cl); if (PREDICT_FALSE(!cache_hit)) { Span* span = Static::pageheap()->GetDescriptor(p); if (PREDICT_FALSE(!span)) { // span can be NULL because the pointer passed in is NULL or invalid // (not something returned by malloc or friends), or because the // pointer was allocated with some other allocator besides // tcmalloc. The latter can happen if tcmalloc is linked in via // a dynamic library, but is not listed last on the link line. // In that case, libraries after it on the link line will // allocate with libc malloc, but free with tcmalloc's free. free_null_or_invalid(ptr, invalid_free_fn); return; } cl = span->sizeclass; if (PREDICT_FALSE(cl == 0)) { ASSERT(reinterpret_cast<uintptr_t>(ptr) % kPageSize == 0); ASSERT(span != NULL && span->start == p); do_free_pages(span, ptr); return; } if (!use_hint) { Static::pageheap()->SetCachedSizeClass(p, cl); } } } if (PREDICT_TRUE(heap != NULL)) { ASSERT(Static::IsInited()); // If we've hit initialized thread cache, so we're done. heap->Deallocate(ptr, cl); return; } if (PREDICT_FALSE(!Static::IsInited())) { // if free was called very early we've could have missed the case // of invalid or nullptr free. I.e. because probing size classes // cache could return bogus result (cl = 0 as of this // writing). But since there is no way we could be dealing with // ptr we've allocated, since successfull malloc implies IsInited, // we can just call "invalid free" handling code. free_null_or_invalid(ptr, invalid_free_fn); return; } // Otherwise, delete directly into central cache tcmalloc::SLL_SetNext(ptr, NULL); Static::central_cache()[cl].InsertRange(ptr, ptr, 1); } // The default "do_free" that uses the default callback. ATTRIBUTE_ALWAYS_INLINE inline void do_free(void* ptr) { return do_free_with_callback(ptr, &InvalidFree, false, 0); } // NOTE: some logic here is duplicated in GetOwnership (above), for // speed. If you change this function, look at that one too. inline size_t GetSizeWithCallback(const void* ptr, size_t (*invalid_getsize_fn)(const void*)) { if (ptr == NULL) return 0; const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift; uint32 cl; if (Static::pageheap()->TryGetSizeClass(p, &cl)) { return Static::sizemap()->ByteSizeForClass(cl); } const Span *span = Static::pageheap()->GetDescriptor(p); if (PREDICT_FALSE(span == NULL)) { // means we do not own this memory return (*invalid_getsize_fn)(ptr); } if (span->sizeclass != 0) { return Static::sizemap()->ByteSizeForClass(span->sizeclass); } if (span->sample) { size_t orig_size = reinterpret_cast<StackTrace*>(span->objects)->size; return tc_nallocx(orig_size, 0); } return span->length << kPageShift; } // This lets you call back to a given function pointer if ptr is invalid. // It is used primarily by windows code which wants a specialized callback. ATTRIBUTE_ALWAYS_INLINE inline void* do_realloc_with_callback( void* old_ptr, size_t new_size, void (*invalid_free_fn)(void*), size_t (*invalid_get_size_fn)(const void*)) { // Get the size of the old entry const size_t old_size = GetSizeWithCallback(old_ptr, invalid_get_size_fn); // Reallocate if the new size is larger than the old size, // or if the new size is significantly smaller than the old size. // We do hysteresis to avoid resizing ping-pongs: // . If we need to grow, grow to max(new_size, old_size * 1.X) // . Don't shrink unless new_size < old_size * 0.Y // X and Y trade-off time for wasted space. For now we do 1.25 and 0.5. const size_t min_growth = min(old_size / 4, (std::numeric_limits<size_t>::max)() - old_size); // Avoid overflow. const size_t lower_bound_to_grow = old_size + min_growth; const size_t upper_bound_to_shrink = old_size / 2ul; if ((new_size > old_size) || (new_size < upper_bound_to_shrink)) { // Need to reallocate. void* new_ptr = NULL; if (new_size > old_size && new_size < lower_bound_to_grow) { new_ptr = do_malloc_or_cpp_alloc(lower_bound_to_grow); } if (new_ptr == NULL) { // Either new_size is not a tiny increment, or last do_malloc failed. new_ptr = do_malloc_or_cpp_alloc(new_size); } if (PREDICT_FALSE(new_ptr == NULL)) { return NULL; } MallocHook::InvokeNewHook(new_ptr, new_size); memcpy(new_ptr, old_ptr, ((old_size < new_size) ? old_size : new_size)); MallocHook::InvokeDeleteHook(old_ptr); // We could use a variant of do_free() that leverages the fact // that we already know the sizeclass of old_ptr. The benefit // would be small, so don't bother. do_free_with_callback(old_ptr, invalid_free_fn, false, 0); return new_ptr; } else { // We still need to call hooks to report the updated size: MallocHook::InvokeDeleteHook(old_ptr); MallocHook::InvokeNewHook(old_ptr, new_size); return old_ptr; } } ATTRIBUTE_ALWAYS_INLINE inline void* do_realloc(void* old_ptr, size_t new_size) { return do_realloc_with_callback(old_ptr, new_size, &InvalidFree, &InvalidGetSizeForRealloc); } static ATTRIBUTE_ALWAYS_INLINE inline void* do_memalign_pages(size_t align, size_t size) { ASSERT((align & (align - 1)) == 0); ASSERT(align > kPageSize); if (size + align < size) return NULL; // Overflow if (PREDICT_FALSE(Static::pageheap() == NULL)) ThreadCache::InitModule(); // Allocate at least one byte to avoid boundary conditions below if (size == 0) size = 1; // We will allocate directly from the page heap SpinLockHolder h(Static::pageheap_lock()); // Allocate extra pages and carve off an aligned portion const Length alloc = tcmalloc::pages(size + align); Span* span = Static::pageheap()->New(alloc); if (PREDICT_FALSE(span == NULL)) return NULL; // Skip starting portion so that we end up aligned Length skip = 0; while ((((span->start+skip) << kPageShift) & (align - 1)) != 0) { skip++; } ASSERT(skip < alloc); if (skip > 0) { Span* rest = Static::pageheap()->Split(span, skip); Static::pageheap()->Delete(span); span = rest; } // Skip trailing portion that we do not need to return const Length needed = tcmalloc::pages(size); ASSERT(span->length >= needed); if (span->length > needed) { Span* trailer = Static::pageheap()->Split(span, needed); Static::pageheap()->Delete(trailer); } return SpanToMallocResult(span); } // Helpers for use by exported routines below: inline void do_malloc_stats() { PrintStats(1); } inline int do_mallopt(int cmd, int value) { return 1; // Indicates error } #ifdef HAVE_STRUCT_MALLINFO inline struct mallinfo do_mallinfo() { TCMallocStats stats; ExtractStats(&stats, NULL, NULL, NULL); // Just some of the fields are filled in. struct mallinfo info; memset(&info, 0, sizeof(info)); // Unfortunately, the struct contains "int" field, so some of the // size values will be truncated. info.arena = static_cast<int>(stats.pageheap.system_bytes); info.fsmblks = static_cast<int>(stats.thread_bytes + stats.central_bytes + stats.transfer_bytes); info.fordblks = static_cast<int>(stats.pageheap.free_bytes + stats.pageheap.unmapped_bytes); info.uordblks = static_cast<int>(stats.pageheap.system_bytes - stats.thread_bytes - stats.central_bytes - stats.transfer_bytes - stats.pageheap.free_bytes - stats.pageheap.unmapped_bytes); return info; } #endif // HAVE_STRUCT_MALLINFO } // end unnamed namespace // As promised, the definition of this function, declared above. size_t TCMallocImplementation::GetAllocatedSize(const void* ptr) { if (ptr == NULL) return 0; ASSERT(TCMallocImplementation::GetOwnership(ptr) != TCMallocImplementation::kNotOwned); return GetSizeWithCallback(ptr, &InvalidGetAllocatedSize); } void TCMallocImplementation::MarkThreadBusy() { // Allocate to force the creation of a thread cache, but avoid // invoking any hooks. do_free(do_malloc(0)); } //------------------------------------------------------------------- // Exported routines //------------------------------------------------------------------- extern "C" PERFTOOLS_DLL_DECL const char* tc_version( int* major, int* minor, const char** patch) PERFTOOLS_NOTHROW { if (major) *major = TC_VERSION_MAJOR; if (minor) *minor = TC_VERSION_MINOR; if (patch) *patch = TC_VERSION_PATCH; return TC_VERSION_STRING; } // This function behaves similarly to MSVC's _set_new_mode. // If flag is 0 (default), calls to malloc will behave normally. // If flag is 1, calls to malloc will behave like calls to new, // and the std_new_handler will be invoked on failure. // Returns the previous mode. extern "C" PERFTOOLS_DLL_DECL int tc_set_new_mode(int flag) PERFTOOLS_NOTHROW { int old_mode = tc_new_mode; tc_new_mode = flag; return old_mode; } extern "C" PERFTOOLS_DLL_DECL int tc_query_new_mode() PERFTOOLS_NOTHROW { return tc_new_mode; } #ifndef TCMALLOC_USING_DEBUGALLOCATION // debugallocation.cc defines its own // CAVEAT: The code structure below ensures that MallocHook methods are always // called from the stack frame of the invoked allocation function. // heap-checker.cc depends on this to start a stack trace from // the call to the (de)allocation function. namespace tcmalloc { static ATTRIBUTE_SECTION(google_malloc) void invoke_hooks_and_free(void *ptr) { MallocHook::InvokeDeleteHook(ptr); do_free(ptr); } ATTRIBUTE_SECTION(google_malloc) void* cpp_throw_oom(size_t size) { return handle_oom(retry_malloc, reinterpret_cast<void *>(size), true, false); } ATTRIBUTE_SECTION(google_malloc) void* cpp_nothrow_oom(size_t size) { return handle_oom(retry_malloc, reinterpret_cast<void *>(size), true, true); } ATTRIBUTE_SECTION(google_malloc) void* malloc_oom(size_t size) { return handle_oom(retry_malloc, reinterpret_cast<void *>(size), false, true); } // tcmalloc::allocate_full_XXX is called by fast-path malloc when some // complex handling is needed (such as fetching object from central // freelist or malloc sampling). It contains all 'operator new' logic, // as opposed to malloc_fast_path which only deals with important // subset of cases. // // Note that this is under tcmalloc namespace so that pprof // can automatically filter it out of growthz/heapz profiles. // // We have slightly fancy setup because we need to call hooks from // function in 'google_malloc' section and we cannot place template // into this section. Thus 3 separate functions 'built' by macros. // // Also note that we're carefully orchestrating for // MallocHook::GetCallerStackTrace to work even if compiler isn't // optimizing tail calls (e.g. -O0 is given). We still require // ATTRIBUTE_ALWAYS_INLINE to work for that case, but it was seen to // work for -O0 -fno-inline across both GCC and clang. I.e. in this // case we'll get stack frame for tc_new, followed by stack frame for // allocate_full_cpp_throw_oom, followed by hooks machinery and user // code's stack frames. So GetCallerStackTrace will find 2 // subsequent stack frames in google_malloc section and correctly // 'cut' stack trace just before tc_new. template <void* OOMHandler(size_t)> ATTRIBUTE_ALWAYS_INLINE inline static void* do_allocate_full(size_t size) { void* p = do_malloc(size); if (PREDICT_FALSE(p == NULL)) { p = OOMHandler(size); } MallocHook::InvokeNewHook(p, size); return CheckedMallocResult(p); } #define AF(oom) \ ATTRIBUTE_SECTION(google_malloc) \ void* allocate_full_##oom(size_t size) { \ return do_allocate_full<oom>(size); \ } AF(cpp_throw_oom) AF(cpp_nothrow_oom) AF(malloc_oom) #undef AF template <void* OOMHandler(size_t)> static ATTRIBUTE_ALWAYS_INLINE inline void* dispatch_allocate_full(size_t size) { if (OOMHandler == cpp_throw_oom) { return allocate_full_cpp_throw_oom(size); } if (OOMHandler == cpp_nothrow_oom) { return allocate_full_cpp_nothrow_oom(size); } ASSERT(OOMHandler == malloc_oom); return allocate_full_malloc_oom(size); } struct retry_memalign_data { size_t align; size_t size; }; static void *retry_do_memalign(void *arg) { retry_memalign_data *data = static_cast<retry_memalign_data *>(arg); return do_memalign_pages(data->align, data->size); } static ATTRIBUTE_SECTION(google_malloc) void* memalign_pages(size_t align, size_t size, bool from_operator, bool nothrow) { void *rv = do_memalign_pages(align, size); if (PREDICT_FALSE(rv == NULL)) { retry_memalign_data data; data.align = align; data.size = size; rv = handle_oom(retry_do_memalign, &data, from_operator, nothrow); } MallocHook::InvokeNewHook(rv, size); return CheckedMallocResult(rv); } } // namespace tcmalloc // This is quick, fast-path-only implementation of malloc/new. It is // designed to only have support for fast-path. It checks if more // complex handling is needed (such as a pageheap allocation or // sampling) and only performs allocation if none of those uncommon // conditions hold. When we have one of those odd cases it simply // tail-calls to one of tcmalloc::allocate_full_XXX defined above. // // Such approach was found to be quite effective. Generated code for // tc_{new,malloc} either succeeds quickly or tail-calls to // allocate_full. Terseness of the source and lack of // non-tail calls enables compiler to produce better code. Also // produced code is short enough to enable effort-less human // comprehension. Which itself led to elimination of various checks // that were not necessary for fast-path. template <void* OOMHandler(size_t)> ATTRIBUTE_ALWAYS_INLINE inline static void * malloc_fast_path(size_t size) { if (PREDICT_FALSE(!base::internal::new_hooks_.empty())) { return tcmalloc::dispatch_allocate_full<OOMHandler>(size); } ThreadCache *cache = ThreadCache::GetFastPathCache(); if (PREDICT_FALSE(cache == NULL)) { return tcmalloc::dispatch_allocate_full<OOMHandler>(size); } uint32 cl; if (PREDICT_FALSE(!Static::sizemap()->GetSizeClass(size, &cl))) { return tcmalloc::dispatch_allocate_full<OOMHandler>(size); } size_t allocated_size = Static::sizemap()->ByteSizeForClass(cl); if (PREDICT_FALSE(!cache->TryRecordAllocationFast(allocated_size))) { return tcmalloc::dispatch_allocate_full<OOMHandler>(size); } return CheckedMallocResult(cache->Allocate(allocated_size, cl, OOMHandler)); } template <void* OOMHandler(size_t)> ATTRIBUTE_ALWAYS_INLINE inline static void* memalign_fast_path(size_t align, size_t size) { if (PREDICT_FALSE(align > kPageSize)) { if (OOMHandler == tcmalloc::cpp_throw_oom) { return tcmalloc::memalign_pages(align, size, true, false); } else if (OOMHandler == tcmalloc::cpp_nothrow_oom) { return tcmalloc::memalign_pages(align, size, true, true); } else { ASSERT(OOMHandler == tcmalloc::malloc_oom); return tcmalloc::memalign_pages(align, size, false, true); } } // Everything with alignment <= kPageSize we can easily delegate to // regular malloc return malloc_fast_path<OOMHandler>(align_size_up(size, align)); } extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN void* tc_malloc(size_t size) PERFTOOLS_NOTHROW { return malloc_fast_path<tcmalloc::malloc_oom>(size); } static ATTRIBUTE_ALWAYS_INLINE inline void free_fast_path(void *ptr) { if (PREDICT_FALSE(!base::internal::delete_hooks_.empty())) { tcmalloc::invoke_hooks_and_free(ptr); return; } do_free(ptr); } extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN void tc_free(void* ptr) PERFTOOLS_NOTHROW { free_fast_path(ptr); } extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN void tc_free_sized(void *ptr, size_t size) PERFTOOLS_NOTHROW { if (PREDICT_FALSE(!base::internal::delete_hooks_.empty())) { tcmalloc::invoke_hooks_and_free(ptr); return; } #ifndef NO_TCMALLOC_SAMPLES // if ptr is kPageSize-aligned, then it could be sampled allocation, // thus we don't trust hint and just do plain free. It also handles // nullptr for us. if (PREDICT_FALSE((reinterpret_cast<uintptr_t>(ptr) & (kPageSize-1)) == 0)) { tc_free(ptr); return; } #else if (!ptr) { return; } #endif do_free_with_callback(ptr, &InvalidFree, true, size); } #ifdef TC_ALIAS extern "C" PERFTOOLS_DLL_DECL void tc_delete_sized(void *p, size_t size) PERFTOOLS_NOTHROW TC_ALIAS(tc_free_sized); extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_sized(void *p, size_t size) PERFTOOLS_NOTHROW TC_ALIAS(tc_free_sized); #else extern "C" PERFTOOLS_DLL_DECL void tc_delete_sized(void *p, size_t size) PERFTOOLS_NOTHROW { tc_free_sized(p, size); } extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_sized(void *p, size_t size) PERFTOOLS_NOTHROW { tc_free_sized(p, size); } #endif extern "C" PERFTOOLS_DLL_DECL void* tc_calloc(size_t n, size_t elem_size) PERFTOOLS_NOTHROW { if (ThreadCache::IsUseEmergencyMalloc()) { return tcmalloc::EmergencyCalloc(n, elem_size); } void* result = do_calloc(n, elem_size); MallocHook::InvokeNewHook(result, n * elem_size); return result; } extern "C" PERFTOOLS_DLL_DECL void tc_cfree(void* ptr) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_free); #else { free_fast_path(ptr); } #endif extern "C" PERFTOOLS_DLL_DECL void* tc_realloc(void* old_ptr, size_t new_size) PERFTOOLS_NOTHROW { if (old_ptr == NULL) { void* result = do_malloc_or_cpp_alloc(new_size); MallocHook::InvokeNewHook(result, new_size); return result; } if (new_size == 0) { MallocHook::InvokeDeleteHook(old_ptr); do_free(old_ptr); return NULL; } if (PREDICT_FALSE(tcmalloc::IsEmergencyPtr(old_ptr))) { return tcmalloc::EmergencyRealloc(old_ptr, new_size); } return do_realloc(old_ptr, new_size); } extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN void* tc_new(size_t size) { return malloc_fast_path<tcmalloc::cpp_throw_oom>(size); } extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN void* tc_new_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW { return malloc_fast_path<tcmalloc::cpp_nothrow_oom>(size); } extern "C" PERFTOOLS_DLL_DECL void tc_delete(void* p) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_free); #else { free_fast_path(p); } #endif // Standard C++ library implementations define and use this // (via ::operator delete(ptr, nothrow)). // But it's really the same as normal delete, so we just do the same thing. extern "C" PERFTOOLS_DLL_DECL void tc_delete_nothrow(void* p, const std::nothrow_t&) PERFTOOLS_NOTHROW { if (PREDICT_FALSE(!base::internal::delete_hooks_.empty())) { tcmalloc::invoke_hooks_and_free(p); return; } do_free(p); } extern "C" PERFTOOLS_DLL_DECL void* tc_newarray(size_t size) #ifdef TC_ALIAS TC_ALIAS(tc_new); #else { return malloc_fast_path<tcmalloc::cpp_throw_oom>(size); } #endif extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_new_nothrow); #else { return malloc_fast_path<tcmalloc::cpp_nothrow_oom>(size); } #endif extern "C" PERFTOOLS_DLL_DECL void tc_deletearray(void* p) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_free); #else { free_fast_path(p); } #endif extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_nothrow(void* p, const std::nothrow_t&) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_delete_nothrow); #else { free_fast_path(p); } #endif extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN void* tc_memalign(size_t align, size_t size) PERFTOOLS_NOTHROW { return memalign_fast_path<tcmalloc::malloc_oom>(align, size); } extern "C" PERFTOOLS_DLL_DECL int tc_posix_memalign( void** result_ptr, size_t align, size_t size) PERFTOOLS_NOTHROW { if (((align % sizeof(void*)) != 0) || ((align & (align - 1)) != 0) || (align == 0)) { return EINVAL; } void* result = tc_memalign(align, size); if (PREDICT_FALSE(result == NULL)) { return ENOMEM; } else { *result_ptr = result; return 0; } } #if defined(ENABLE_ALIGNED_NEW_DELETE) extern "C" PERFTOOLS_DLL_DECL void* tc_new_aligned(size_t size, std::align_val_t align) { return memalign_fast_path<tcmalloc::cpp_throw_oom>(static_cast<size_t>(align), size); } extern "C" PERFTOOLS_DLL_DECL void* tc_new_aligned_nothrow(size_t size, std::align_val_t align, const std::nothrow_t&) PERFTOOLS_NOTHROW { return memalign_fast_path<tcmalloc::cpp_nothrow_oom>(static_cast<size_t>(align), size); } extern "C" PERFTOOLS_DLL_DECL void tc_delete_aligned(void* p, std::align_val_t) PERFTOOLS_NOTHROW { free_fast_path(p); } // There is no easy way to obtain the actual size used by do_memalign to allocate aligned storage, so for now // just ignore the size. It might get useful in the future. extern "C" PERFTOOLS_DLL_DECL void tc_delete_sized_aligned(void* p, size_t size, std::align_val_t align) PERFTOOLS_NOTHROW { free_fast_path(p); } extern "C" PERFTOOLS_DLL_DECL void tc_delete_aligned_nothrow(void* p, std::align_val_t, const std::nothrow_t&) PERFTOOLS_NOTHROW { free_fast_path(p); } extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_aligned(size_t size, std::align_val_t align) #ifdef TC_ALIAS TC_ALIAS(tc_new_aligned); #else { return memalign_fast_path<tcmalloc::cpp_throw_oom>(static_cast<size_t>(align), size); } #endif extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_aligned_nothrow(size_t size, std::align_val_t align, const std::nothrow_t& nt) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_new_aligned_nothrow); #else { return memalign_fast_path<tcmalloc::cpp_nothrow_oom>(static_cast<size_t>(align), size); } #endif extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_aligned(void* p, std::align_val_t) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_delete_aligned); #else { free_fast_path(p); } #endif // There is no easy way to obtain the actual size used by do_memalign to allocate aligned storage, so for now // just ignore the size. It might get useful in the future. extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_sized_aligned(void* p, size_t size, std::align_val_t align) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_delete_sized_aligned); #else { free_fast_path(p); } #endif extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_aligned_nothrow(void* p, std::align_val_t, const std::nothrow_t&) PERFTOOLS_NOTHROW #ifdef TC_ALIAS TC_ALIAS(tc_delete_aligned_nothrow); #else { free_fast_path(p); } #endif #endif // defined(ENABLE_ALIGNED_NEW_DELETE) static size_t pagesize = 0; extern "C" PERFTOOLS_DLL_DECL void* tc_valloc(size_t size) PERFTOOLS_NOTHROW { // Allocate page-aligned object of length >= size bytes if (pagesize == 0) pagesize = getpagesize(); return tc_memalign(pagesize, size); } extern "C" PERFTOOLS_DLL_DECL void* tc_pvalloc(size_t size) PERFTOOLS_NOTHROW { // Round up size to a multiple of pagesize if (pagesize == 0) pagesize = getpagesize(); if (size == 0) { // pvalloc(0) should allocate one page, according to size = pagesize; // http://man.free4web.biz/man3/libmpatrol.3.html } size = (size + pagesize - 1) & ~(pagesize - 1); return tc_memalign(pagesize, size); } extern "C" PERFTOOLS_DLL_DECL void tc_malloc_stats(void) PERFTOOLS_NOTHROW { do_malloc_stats(); } extern "C" PERFTOOLS_DLL_DECL int tc_mallopt(int cmd, int value) PERFTOOLS_NOTHROW { return do_mallopt(cmd, value); } #ifdef HAVE_STRUCT_MALLINFO extern "C" PERFTOOLS_DLL_DECL struct mallinfo tc_mallinfo(void) PERFTOOLS_NOTHROW { return do_mallinfo(); } #endif extern "C" PERFTOOLS_DLL_DECL size_t tc_malloc_size(void* ptr) PERFTOOLS_NOTHROW { return MallocExtension::instance()->GetAllocatedSize(ptr); } extern "C" PERFTOOLS_DLL_DECL void* tc_malloc_skip_new_handler(size_t size) PERFTOOLS_NOTHROW { void* result = do_malloc(size); MallocHook::InvokeNewHook(result, size); return result; } #endif // TCMALLOC_USING_DEBUGALLOCATION
Unknown
3D
mcellteam/mcell
libs/gperftools/src/heap-profiler.cc
.cc
22,469
623
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // // TODO: Log large allocations #include <config.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> // for open() #endif #ifdef HAVE_MMAP #include <sys/mman.h> #endif #include <errno.h> #include <assert.h> #include <sys/types.h> #include <signal.h> #include <algorithm> #include <string> #include <gperftools/heap-profiler.h> #include "base/logging.h" #include "base/basictypes.h" // for PRId64, among other things #include "base/googleinit.h" #include "base/commandlineflags.h" #include "malloc_hook-inl.h" #include "tcmalloc_guard.h" #include <gperftools/malloc_hook.h> #include <gperftools/malloc_extension.h> #include "base/spinlock.h" #include "base/low_level_alloc.h" #include "base/sysinfo.h" // for GetUniquePathFromEnv() #include "heap-profile-table.h" #include "memory_region_map.h" #ifndef PATH_MAX #ifdef MAXPATHLEN #define PATH_MAX MAXPATHLEN #else #define PATH_MAX 4096 // seems conservative for max filename len! #endif #endif using STL_NAMESPACE::string; using STL_NAMESPACE::sort; //---------------------------------------------------------------------- // Flags that control heap-profiling // // The thread-safety of the profiler depends on these being immutable // after main starts, so don't change them. //---------------------------------------------------------------------- DEFINE_int64(heap_profile_allocation_interval, EnvToInt64("HEAP_PROFILE_ALLOCATION_INTERVAL", 1 << 30 /*1GB*/), "If non-zero, dump heap profiling information once every " "specified number of bytes allocated by the program since " "the last dump."); DEFINE_int64(heap_profile_deallocation_interval, EnvToInt64("HEAP_PROFILE_DEALLOCATION_INTERVAL", 0), "If non-zero, dump heap profiling information once every " "specified number of bytes deallocated by the program " "since the last dump."); // We could also add flags that report whenever inuse_bytes changes by // X or -X, but there hasn't been a need for that yet, so we haven't. DEFINE_int64(heap_profile_inuse_interval, EnvToInt64("HEAP_PROFILE_INUSE_INTERVAL", 100 << 20 /*100MB*/), "If non-zero, dump heap profiling information whenever " "the high-water memory usage mark increases by the specified " "number of bytes."); DEFINE_int64(heap_profile_time_interval, EnvToInt64("HEAP_PROFILE_TIME_INTERVAL", 0), "If non-zero, dump heap profiling information once every " "specified number of seconds since the last dump."); DEFINE_bool(mmap_log, EnvToBool("HEAP_PROFILE_MMAP_LOG", false), "Should mmap/munmap calls be logged?"); DEFINE_bool(mmap_profile, EnvToBool("HEAP_PROFILE_MMAP", false), "If heap-profiling is on, also profile mmap, mremap, and sbrk)"); DEFINE_bool(only_mmap_profile, EnvToBool("HEAP_PROFILE_ONLY_MMAP", false), "If heap-profiling is on, only profile mmap, mremap, and sbrk; " "do not profile malloc/new/etc"); //---------------------------------------------------------------------- // Locking //---------------------------------------------------------------------- // A pthread_mutex has way too much lock contention to be used here. // // I would like to use Mutex, but it can call malloc(), // which can cause us to fall into an infinite recursion. // // So we use a simple spinlock. static SpinLock heap_lock(SpinLock::LINKER_INITIALIZED); //---------------------------------------------------------------------- // Simple allocator for heap profiler's internal memory //---------------------------------------------------------------------- static LowLevelAlloc::Arena *heap_profiler_memory; static void* ProfilerMalloc(size_t bytes) { return LowLevelAlloc::AllocWithArena(bytes, heap_profiler_memory); } static void ProfilerFree(void* p) { LowLevelAlloc::Free(p); } // We use buffers of this size in DoGetHeapProfile. static const int kProfileBufferSize = 1 << 20; // This is a last-ditch buffer we use in DumpProfileLocked in case we // can't allocate more memory from ProfilerMalloc. We expect this // will be used by HeapProfileEndWriter when the application has to // exit due to out-of-memory. This buffer is allocated in // HeapProfilerStart. Access to this must be protected by heap_lock. static char* global_profiler_buffer = NULL; //---------------------------------------------------------------------- // Profiling control/state data //---------------------------------------------------------------------- // Access to all of these is protected by heap_lock. static bool is_on = false; // If are on as a subsytem. static bool dumping = false; // Dumping status to prevent recursion static char* filename_prefix = NULL; // Prefix used for profile file names // (NULL if no need for dumping yet) static int dump_count = 0; // How many dumps so far static int64 last_dump_alloc = 0; // alloc_size when did we last dump static int64 last_dump_free = 0; // free_size when did we last dump static int64 high_water_mark = 0; // In-use-bytes at last high-water dump static int64 last_dump_time = 0; // The time of the last dump static HeapProfileTable* heap_profile = NULL; // the heap profile table //---------------------------------------------------------------------- // Profile generation //---------------------------------------------------------------------- // Input must be a buffer of size at least 1MB. static char* DoGetHeapProfileLocked(char* buf, int buflen) { // We used to be smarter about estimating the required memory and // then capping it to 1MB and generating the profile into that. if (buf == NULL || buflen < 1) return NULL; RAW_DCHECK(heap_lock.IsHeld(), ""); int bytes_written = 0; if (is_on) { HeapProfileTable::Stats const stats = heap_profile->total(); (void)stats; // avoid an unused-variable warning in non-debug mode. bytes_written = heap_profile->FillOrderedProfile(buf, buflen - 1); // FillOrderedProfile should not reduce the set of active mmap-ed regions, // hence MemoryRegionMap will let us remove everything we've added above: RAW_DCHECK(stats.Equivalent(heap_profile->total()), ""); // if this fails, we somehow removed by FillOrderedProfile // more than we have added. } buf[bytes_written] = '\0'; RAW_DCHECK(bytes_written == strlen(buf), ""); return buf; } extern "C" char* GetHeapProfile() { // Use normal malloc: we return the profile to the user to free it: char* buffer = reinterpret_cast<char*>(malloc(kProfileBufferSize)); SpinLockHolder l(&heap_lock); return DoGetHeapProfileLocked(buffer, kProfileBufferSize); } // defined below static void NewHook(const void* ptr, size_t size); static void DeleteHook(const void* ptr); // Helper for HeapProfilerDump. static void DumpProfileLocked(const char* reason) { RAW_DCHECK(heap_lock.IsHeld(), ""); RAW_DCHECK(is_on, ""); RAW_DCHECK(!dumping, ""); if (filename_prefix == NULL) return; // we do not yet need dumping dumping = true; // Make file name char file_name[1000]; dump_count++; snprintf(file_name, sizeof(file_name), "%s.%04d%s", filename_prefix, dump_count, HeapProfileTable::kFileExt); // Dump the profile RAW_VLOG(0, "Dumping heap profile to %s (%s)", file_name, reason); // We must use file routines that don't access memory, since we hold // a memory lock now. RawFD fd = RawOpenForWriting(file_name); if (fd == kIllegalRawFD) { RAW_LOG(ERROR, "Failed dumping heap profile to %s", file_name); dumping = false; return; } // This case may be impossible, but it's best to be safe. // It's safe to use the global buffer: we're protected by heap_lock. if (global_profiler_buffer == NULL) { global_profiler_buffer = reinterpret_cast<char*>(ProfilerMalloc(kProfileBufferSize)); } char* profile = DoGetHeapProfileLocked(global_profiler_buffer, kProfileBufferSize); RawWrite(fd, profile, strlen(profile)); RawClose(fd); dumping = false; } //---------------------------------------------------------------------- // Profile collection //---------------------------------------------------------------------- // Dump a profile after either an allocation or deallocation, if // the memory use has changed enough since the last dump. static void MaybeDumpProfileLocked() { if (!dumping) { const HeapProfileTable::Stats& total = heap_profile->total(); const int64 inuse_bytes = total.alloc_size - total.free_size; bool need_to_dump = false; char buf[128]; if (FLAGS_heap_profile_allocation_interval > 0 && total.alloc_size >= last_dump_alloc + FLAGS_heap_profile_allocation_interval) { snprintf(buf, sizeof(buf), ("%" PRId64 " MB allocated cumulatively, " "%" PRId64 " MB currently in use"), total.alloc_size >> 20, inuse_bytes >> 20); need_to_dump = true; } else if (FLAGS_heap_profile_deallocation_interval > 0 && total.free_size >= last_dump_free + FLAGS_heap_profile_deallocation_interval) { snprintf(buf, sizeof(buf), ("%" PRId64 " MB freed cumulatively, " "%" PRId64 " MB currently in use"), total.free_size >> 20, inuse_bytes >> 20); need_to_dump = true; } else if (FLAGS_heap_profile_inuse_interval > 0 && inuse_bytes > high_water_mark + FLAGS_heap_profile_inuse_interval) { snprintf(buf, sizeof(buf), "%" PRId64 " MB currently in use", inuse_bytes >> 20); need_to_dump = true; } else if (FLAGS_heap_profile_time_interval > 0 ) { int64 current_time = time(NULL); if (current_time - last_dump_time >= FLAGS_heap_profile_time_interval) { snprintf(buf, sizeof(buf), "%" PRId64 " sec since the last dump", current_time - last_dump_time); need_to_dump = true; last_dump_time = current_time; } } if (need_to_dump) { DumpProfileLocked(buf); last_dump_alloc = total.alloc_size; last_dump_free = total.free_size; if (inuse_bytes > high_water_mark) high_water_mark = inuse_bytes; } } } // Record an allocation in the profile. static void RecordAlloc(const void* ptr, size_t bytes, int skip_count) { // Take the stack trace outside the critical section. void* stack[HeapProfileTable::kMaxStackDepth]; int depth = HeapProfileTable::GetCallerStackTrace(skip_count + 1, stack); SpinLockHolder l(&heap_lock); if (is_on) { heap_profile->RecordAlloc(ptr, bytes, depth, stack); MaybeDumpProfileLocked(); } } // Record a deallocation in the profile. static void RecordFree(const void* ptr) { SpinLockHolder l(&heap_lock); if (is_on) { heap_profile->RecordFree(ptr); MaybeDumpProfileLocked(); } } //---------------------------------------------------------------------- // Allocation/deallocation hooks for MallocHook //---------------------------------------------------------------------- // static void NewHook(const void* ptr, size_t size) { if (ptr != NULL) RecordAlloc(ptr, size, 0); } // static void DeleteHook(const void* ptr) { if (ptr != NULL) RecordFree(ptr); } // TODO(jandrews): Re-enable stack tracing #ifdef TODO_REENABLE_STACK_TRACING static void RawInfoStackDumper(const char* message, void*) { RAW_LOG(INFO, "%.*s", static_cast<int>(strlen(message) - 1), message); // -1 is to chop the \n which will be added by RAW_LOG } #endif static void MmapHook(const void* result, const void* start, size_t size, int prot, int flags, int fd, off_t offset) { if (FLAGS_mmap_log) { // log it // We use PRIxS not just '%p' to avoid deadlocks // in pretty-printing of NULL as "nil". // TODO(maxim): instead should use a safe snprintf reimplementation RAW_LOG(INFO, "mmap(start=0x%" PRIxPTR ", len=%" PRIuS ", prot=0x%x, flags=0x%x, " "fd=%d, offset=0x%x) = 0x%" PRIxPTR "", (uintptr_t) start, size, prot, flags, fd, (unsigned int) offset, (uintptr_t) result); #ifdef TODO_REENABLE_STACK_TRACING DumpStackTrace(1, RawInfoStackDumper, NULL); #endif } } static void MremapHook(const void* result, const void* old_addr, size_t old_size, size_t new_size, int flags, const void* new_addr) { if (FLAGS_mmap_log) { // log it // We use PRIxS not just '%p' to avoid deadlocks // in pretty-printing of NULL as "nil". // TODO(maxim): instead should use a safe snprintf reimplementation RAW_LOG(INFO, "mremap(old_addr=0x%" PRIxPTR ", old_size=%" PRIuS ", " "new_size=%" PRIuS ", flags=0x%x, new_addr=0x%" PRIxPTR ") = " "0x%" PRIxPTR "", (uintptr_t) old_addr, old_size, new_size, flags, (uintptr_t) new_addr, (uintptr_t) result); #ifdef TODO_REENABLE_STACK_TRACING DumpStackTrace(1, RawInfoStackDumper, NULL); #endif } } static void MunmapHook(const void* ptr, size_t size) { if (FLAGS_mmap_log) { // log it // We use PRIxS not just '%p' to avoid deadlocks // in pretty-printing of NULL as "nil". // TODO(maxim): instead should use a safe snprintf reimplementation RAW_LOG(INFO, "munmap(start=0x%" PRIxPTR ", len=%" PRIuS ")", (uintptr_t) ptr, size); #ifdef TODO_REENABLE_STACK_TRACING DumpStackTrace(1, RawInfoStackDumper, NULL); #endif } } static void SbrkHook(const void* result, ptrdiff_t increment) { if (FLAGS_mmap_log) { // log it RAW_LOG(INFO, "sbrk(inc=%" PRIdS ") = 0x%" PRIxPTR "", increment, (uintptr_t) result); #ifdef TODO_REENABLE_STACK_TRACING DumpStackTrace(1, RawInfoStackDumper, NULL); #endif } } //---------------------------------------------------------------------- // Starting/stopping/dumping //---------------------------------------------------------------------- extern "C" void HeapProfilerStart(const char* prefix) { SpinLockHolder l(&heap_lock); if (is_on) return; is_on = true; RAW_VLOG(0, "Starting tracking the heap"); // This should be done before the hooks are set up, since it should // call new, and we want that to be accounted for correctly. MallocExtension::Initialize(); if (FLAGS_only_mmap_profile) { FLAGS_mmap_profile = true; } if (FLAGS_mmap_profile) { // Ask MemoryRegionMap to record all mmap, mremap, and sbrk // call stack traces of at least size kMaxStackDepth: MemoryRegionMap::Init(HeapProfileTable::kMaxStackDepth, /* use_buckets */ true); } if (FLAGS_mmap_log) { // Install our hooks to do the logging: RAW_CHECK(MallocHook::AddMmapHook(&MmapHook), ""); RAW_CHECK(MallocHook::AddMremapHook(&MremapHook), ""); RAW_CHECK(MallocHook::AddMunmapHook(&MunmapHook), ""); RAW_CHECK(MallocHook::AddSbrkHook(&SbrkHook), ""); } heap_profiler_memory = LowLevelAlloc::NewArena(0, LowLevelAlloc::DefaultArena()); // Reserve space now for the heap profiler, so we can still write a // heap profile even if the application runs out of memory. global_profiler_buffer = reinterpret_cast<char*>(ProfilerMalloc(kProfileBufferSize)); heap_profile = new(ProfilerMalloc(sizeof(HeapProfileTable))) HeapProfileTable(ProfilerMalloc, ProfilerFree, FLAGS_mmap_profile); last_dump_alloc = 0; last_dump_free = 0; high_water_mark = 0; last_dump_time = 0; // We do not reset dump_count so if the user does a sequence of // HeapProfilerStart/HeapProfileStop, we will get a continuous // sequence of profiles. if (FLAGS_only_mmap_profile == false) { // Now set the hooks that capture new/delete and malloc/free. RAW_CHECK(MallocHook::AddNewHook(&NewHook), ""); RAW_CHECK(MallocHook::AddDeleteHook(&DeleteHook), ""); } // Copy filename prefix RAW_DCHECK(filename_prefix == NULL, ""); const int prefix_length = strlen(prefix); filename_prefix = reinterpret_cast<char*>(ProfilerMalloc(prefix_length + 1)); memcpy(filename_prefix, prefix, prefix_length); filename_prefix[prefix_length] = '\0'; } extern "C" int IsHeapProfilerRunning() { SpinLockHolder l(&heap_lock); return is_on ? 1 : 0; // return an int, because C code doesn't have bool } extern "C" void HeapProfilerStop() { SpinLockHolder l(&heap_lock); if (!is_on) return; if (FLAGS_only_mmap_profile == false) { // Unset our new/delete hooks, checking they were set: RAW_CHECK(MallocHook::RemoveNewHook(&NewHook), ""); RAW_CHECK(MallocHook::RemoveDeleteHook(&DeleteHook), ""); } if (FLAGS_mmap_log) { // Restore mmap/sbrk hooks, checking that our hooks were set: RAW_CHECK(MallocHook::RemoveMmapHook(&MmapHook), ""); RAW_CHECK(MallocHook::RemoveMremapHook(&MremapHook), ""); RAW_CHECK(MallocHook::RemoveSbrkHook(&SbrkHook), ""); RAW_CHECK(MallocHook::RemoveMunmapHook(&MunmapHook), ""); } // free profile heap_profile->~HeapProfileTable(); ProfilerFree(heap_profile); heap_profile = NULL; // free output-buffer memory ProfilerFree(global_profiler_buffer); // free prefix ProfilerFree(filename_prefix); filename_prefix = NULL; if (!LowLevelAlloc::DeleteArena(heap_profiler_memory)) { RAW_LOG(FATAL, "Memory leak in HeapProfiler:"); } if (FLAGS_mmap_profile) { MemoryRegionMap::Shutdown(); } is_on = false; } extern "C" void HeapProfilerDump(const char *reason) { SpinLockHolder l(&heap_lock); if (is_on && !dumping) { DumpProfileLocked(reason); } } // Signal handler that is registered when a user selectable signal // number is defined in the environment variable HEAPPROFILESIGNAL. static void HeapProfilerDumpSignal(int signal_number) { (void)signal_number; if (!heap_lock.TryLock()) { return; } if (is_on && !dumping) { DumpProfileLocked("signal"); } heap_lock.Unlock(); } //---------------------------------------------------------------------- // Initialization/finalization code //---------------------------------------------------------------------- // Initialization code static void HeapProfilerInit() { // Everything after this point is for setting up the profiler based on envvar char fname[PATH_MAX]; if (!GetUniquePathFromEnv("HEAPPROFILE", fname)) { return; } // We do a uid check so we don't write out files in a setuid executable. #ifdef HAVE_GETEUID if (getuid() != geteuid()) { RAW_LOG(WARNING, ("HeapProfiler: ignoring HEAPPROFILE because " "program seems to be setuid\n")); return; } #endif char *signal_number_str = getenv("HEAPPROFILESIGNAL"); if (signal_number_str != NULL) { long int signal_number = strtol(signal_number_str, NULL, 10); intptr_t old_signal_handler = reinterpret_cast<intptr_t>(signal(signal_number, HeapProfilerDumpSignal)); if (old_signal_handler == reinterpret_cast<intptr_t>(SIG_ERR)) { RAW_LOG(FATAL, "Failed to set signal. Perhaps signal number %s is invalid\n", signal_number_str); } else if (old_signal_handler == 0) { RAW_LOG(INFO,"Using signal %d as heap profiling switch", signal_number); } else { RAW_LOG(FATAL, "Signal %d already in use\n", signal_number); } } HeapProfileTable::CleanupOldProfiles(fname); HeapProfilerStart(fname); } // class used for finalization -- dumps the heap-profile at program exit struct HeapProfileEndWriter { ~HeapProfileEndWriter() { char buf[128]; if (heap_profile) { const HeapProfileTable::Stats& total = heap_profile->total(); const int64 inuse_bytes = total.alloc_size - total.free_size; if ((inuse_bytes >> 20) > 0) { snprintf(buf, sizeof(buf), ("Exiting, %" PRId64 " MB in use"), inuse_bytes >> 20); } else if ((inuse_bytes >> 10) > 0) { snprintf(buf, sizeof(buf), ("Exiting, %" PRId64 " kB in use"), inuse_bytes >> 10); } else { snprintf(buf, sizeof(buf), ("Exiting, %" PRId64 " bytes in use"), inuse_bytes); } } else { snprintf(buf, sizeof(buf), ("Exiting")); } HeapProfilerDump(buf); } }; // We want to make sure tcmalloc is up and running before starting the profiler static const TCMallocGuard tcmalloc_initializer; REGISTER_MODULE_INITIALIZER(heapprofiler, HeapProfilerInit()); static HeapProfileEndWriter heap_profile_end_writer;
Unknown
3D
mcellteam/mcell
libs/gperftools/src/config_for_unittests.h
.h
3,046
66
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Craig Silverstein // // This file is needed for windows -- unittests are not part of the // perftools dll, but still want to include config.h just like the // dll does, so they can use internal tools and APIs for testing. // // The problem is that config.h declares PERFTOOLS_DLL_DECL to be // for exporting symbols, but the unittest needs to *import* symbols // (since it's not the dll). // // The solution is to have this file, which is just like config.h but // sets PERFTOOLS_DLL_DECL to do a dllimport instead of a dllexport. // // The reason we need this extra PERFTOOLS_DLL_DECL_FOR_UNITTESTS // variable is in case people want to set PERFTOOLS_DLL_DECL explicitly // to something other than __declspec(dllexport). In that case, they // may want to use something other than __declspec(dllimport) for the // unittest case. For that, we allow folks to define both // PERFTOOLS_DLL_DECL and PERFTOOLS_DLL_DECL_FOR_UNITTESTS explicitly. // // NOTE: This file is equivalent to config.h on non-windows systems, // which never defined PERFTOOLS_DLL_DECL_FOR_UNITTESTS and always // define PERFTOOLS_DLL_DECL to the empty string. #include "config.h" #undef PERFTOOLS_DLL_DECL #ifdef PERFTOOLS_DLL_DECL_FOR_UNITTESTS # define PERFTOOLS_DLL_DECL PERFTOOLS_DLL_DECL_FOR_UNITTESTS #else # define PERFTOOLS_DLL_DECL // if DLL_DECL_FOR_UNITTESTS isn't defined, use "" #endif
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_powerpc-inl.h
.h
6,706
177
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein // // Produce stack trace. I'm guessing (hoping!) the code is much like // for x86. For apple machines, at least, it seems to be; see // http://developer.apple.com/documentation/mac/runtimehtml/RTArch-59.html // http://www.linux-foundation.org/spec/ELF/ppc64/PPC-elf64abi-1.9.html#STACK // Linux has similar code: http://patchwork.ozlabs.org/linuxppc/patch?id=8882 #ifndef BASE_STACKTRACE_POWERPC_INL_H_ #define BASE_STACKTRACE_POWERPC_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include <stdint.h> // for uintptr_t #include <stdlib.h> // for NULL #include <gperftools/stacktrace.h> struct layout_ppc { struct layout_ppc *next; #if defined(__APPLE__) || (defined(__linux) && defined(__PPC64__)) long condition_register; #endif void *return_addr; }; // Given a pointer to a stack frame, locate and return the calling // stackframe, or return NULL if no stackframe can be found. Perform sanity // checks (the strictness of which is controlled by the boolean parameter // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. template<bool STRICT_UNWINDING> static layout_ppc *NextStackFrame(layout_ppc *current) { uintptr_t old_sp = (uintptr_t)(current); uintptr_t new_sp = (uintptr_t)(current->next); // Check that the transition from frame pointer old_sp to frame // pointer new_sp isn't clearly bogus if (STRICT_UNWINDING) { // With the stack growing downwards, older stack frame must be // at a greater address that the current one. if (new_sp <= old_sp) return NULL; // Assume stack frames larger than 100,000 bytes are bogus. if (new_sp - old_sp > 100000) return NULL; } else { // In the non-strict mode, allow discontiguous stack frames. // (alternate-signal-stacks for example). if (new_sp == old_sp) return NULL; // And allow frames upto about 1MB. if ((new_sp > old_sp) && (new_sp - old_sp > 1000000)) return NULL; } if (new_sp & (sizeof(void *) - 1)) return NULL; return current->next; } // This ensures that GetStackTrace stes up the Link Register properly. void StacktracePowerPCDummyFunction() __attribute__((noinline)); void StacktracePowerPCDummyFunction() { __asm__ volatile(""); } #endif // BASE_STACKTRACE_POWERPC_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // Load instruction used on top-of-stack get. #if defined(__PPC64__) || defined(__LP64__) # define LOAD "ld" #else # define LOAD "lwz" #endif #if defined(__linux__) && defined(__PPC__) # define TOP_STACK "%0,0(1)" #elif defined(__MACH__) && defined(__APPLE__) // Apple OS X uses an old version of gnu as -- both Darwin 7.9.0 (Panther) // and Darwin 8.8.1 (Tiger) use as 1.38. This means we have to use a // different asm syntax. I don't know quite the best way to discriminate // systems using the old as from the new one; I've gone with __APPLE__. // TODO(csilvers): use autoconf instead, to look for 'as --version' == 1 or 2 # define TOP_STACK "%0,0(r1)" #endif // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) static int GET_STACK_TRACE_OR_FRAMES { layout_ppc *current; int n; // Force GCC to spill LR. asm volatile ("" : "=l"(current)); // Get the address on top-of-stack asm volatile (LOAD " " TOP_STACK : "=r"(current)); StacktracePowerPCDummyFunction(); n = 0; skip_count++; // skip parent's frame due to indirection in // stacktrace.cc while (current && n < max_depth) { // The GetStackFrames routine is called when we are in some // informational context (the failure signal handler for example). // Use the non-strict unwinding rules to produce a stack trace // that is as complete as possible (even if it contains a few // bogus entries in some rare cases). layout_ppc *next = NextStackFrame<!IS_STACK_FRAMES>(current); if (skip_count > 0) { skip_count--; } else { result[n] = current->return_addr; #if IS_STACK_FRAMES if (next > current) { sizes[n] = (uintptr_t)next - (uintptr_t)current; } else { // A frame-size of 0 is used to indicate unknown frame size. sizes[n] = 0; } #endif n++; } current = next; } // It's possible the second-last stack frame can't return // (that is, it's __libc_start_main), in which case // the CRT startup code will have set its LR to 'NULL'. if (n > 0 && result[n-1] == NULL) n--; return n; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/page_heap.h
.h
13,271
359
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #ifndef TCMALLOC_PAGE_HEAP_H_ #define TCMALLOC_PAGE_HEAP_H_ #include <config.h> #include <stddef.h> // for size_t #ifdef HAVE_STDINT_H #include <stdint.h> // for uint64_t, int64_t, uint16_t #endif #include <gperftools/malloc_extension.h> #include "base/basictypes.h" #include "common.h" #include "packed-cache-inl.h" #include "pagemap.h" #include "span.h" // We need to dllexport PageHeap just for the unittest. MSVC complains // that we don't dllexport the PageHeap members, but we don't need to // test those, so I just suppress this warning. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4251) #endif // This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if // you're porting to a system where you really can't get a stacktrace. // Because we control the definition of GetStackTrace, all clients of // GetStackTrace should #include us rather than stacktrace.h. #ifdef NO_TCMALLOC_SAMPLES // We use #define so code compiles even if you #include stacktrace.h somehow. # define GetStackTrace(stack, depth, skip) (0) #else # include <gperftools/stacktrace.h> #endif namespace base { struct MallocRange; } namespace tcmalloc { // ------------------------------------------------------------------------- // Map from page-id to per-page data // ------------------------------------------------------------------------- // We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines. // We also use a simple one-level cache for hot PageID-to-sizeclass mappings, // because sometimes the sizeclass is all the information we need. // Selector class -- general selector uses 3-level map template <int BITS> class MapSelector { public: typedef TCMalloc_PageMap3<BITS-kPageShift> Type; }; #ifndef TCMALLOC_SMALL_BUT_SLOW // x86-64 and arm64 are using 48 bits of address space. So we can use // just two level map, but since initial ram consumption of this mode // is a bit on the higher side, we opt-out of it in // TCMALLOC_SMALL_BUT_SLOW mode. template <> class MapSelector<48> { public: typedef TCMalloc_PageMap2<48-kPageShift> Type; }; #endif // TCMALLOC_SMALL_BUT_SLOW // A two-level map for 32-bit machines template <> class MapSelector<32> { public: typedef TCMalloc_PageMap2<32-kPageShift> Type; }; // ------------------------------------------------------------------------- // Page-level allocator // * Eager coalescing // // Heap for page-level allocation. We allow allocating and freeing a // contiguous runs of pages (called a "span"). // ------------------------------------------------------------------------- class PERFTOOLS_DLL_DECL PageHeap { public: PageHeap(); // Allocate a run of "n" pages. Returns zero if out of memory. // Caller should not pass "n == 0" -- instead, n should have // been rounded up already. Span* New(Length n); // Delete the span "[p, p+n-1]". // REQUIRES: span was returned by earlier call to New() and // has not yet been deleted. void Delete(Span* span); // Mark an allocated span as being used for small objects of the // specified size-class. // REQUIRES: span was returned by an earlier call to New() // and has not yet been deleted. void RegisterSizeClass(Span* span, uint32 sc); // Split an allocated span into two spans: one of length "n" pages // followed by another span of length "span->length - n" pages. // Modifies "*span" to point to the first span of length "n" pages. // Returns a pointer to the second span. // // REQUIRES: "0 < n < span->length" // REQUIRES: span->location == IN_USE // REQUIRES: span->sizeclass == 0 Span* Split(Span* span, Length n); // Return the descriptor for the specified page. Returns NULL if // this PageID was not allocated previously. inline ATTRIBUTE_ALWAYS_INLINE Span* GetDescriptor(PageID p) const { return reinterpret_cast<Span*>(pagemap_.get(p)); } // If this page heap is managing a range with starting page # >= start, // store info about the range in *r and return true. Else return false. bool GetNextRange(PageID start, base::MallocRange* r); // Page heap statistics struct Stats { Stats() : system_bytes(0), free_bytes(0), unmapped_bytes(0), committed_bytes(0), scavenge_count(0), commit_count(0), total_commit_bytes(0), decommit_count(0), total_decommit_bytes(0), reserve_count(0), total_reserve_bytes(0) {} uint64_t system_bytes; // Total bytes allocated from system uint64_t free_bytes; // Total bytes on normal freelists uint64_t unmapped_bytes; // Total bytes on returned freelists uint64_t committed_bytes; // Bytes committed, always <= system_bytes_. uint64_t scavenge_count; // Number of times scavagened flush pages uint64_t commit_count; // Number of virtual memory commits uint64_t total_commit_bytes; // Bytes committed in lifetime of process uint64_t decommit_count; // Number of virtual memory decommits uint64_t total_decommit_bytes; // Bytes decommitted in lifetime of process uint64_t reserve_count; // Number of virtual memory reserves uint64_t total_reserve_bytes; // Bytes reserved in lifetime of process }; inline Stats stats() const { return stats_; } struct SmallSpanStats { // For each free list of small spans, the length (in spans) of the // normal and returned free lists for that size. // // NOTE: index 'i' accounts the number of spans of length 'i + 1'. int64 normal_length[kMaxPages]; int64 returned_length[kMaxPages]; }; void GetSmallSpanStats(SmallSpanStats* result); // Stats for free large spans (i.e., spans with more than kMaxPages pages). struct LargeSpanStats { int64 spans; // Number of such spans int64 normal_pages; // Combined page length of normal large spans int64 returned_pages; // Combined page length of unmapped spans }; void GetLargeSpanStats(LargeSpanStats* result); bool Check(); // Like Check() but does some more comprehensive checking. bool CheckExpensive(); bool CheckList(Span* list, Length min_pages, Length max_pages, int freelist); // ON_NORMAL_FREELIST or ON_RETURNED_FREELIST bool CheckSet(SpanSet *s, Length min_pages, int freelist); // Try to release at least num_pages for reuse by the OS. Returns // the actual number of pages released, which may be less than // num_pages if there weren't enough pages to release. The result // may also be larger than num_pages since page_heap might decide to // release one large range instead of fragmenting it into two // smaller released and unreleased ranges. Length ReleaseAtLeastNPages(Length num_pages); // Reads and writes to pagemap_cache_ do not require locking. bool TryGetSizeClass(PageID p, uint32* out) const { return pagemap_cache_.TryGet(p, out); } void SetCachedSizeClass(PageID p, uint32 cl) { ASSERT(cl != 0); pagemap_cache_.Put(p, cl); } void InvalidateCachedSizeClass(PageID p) { pagemap_cache_.Invalidate(p); } uint32 GetSizeClassOrZero(PageID p) const { uint32 cached_value; if (!TryGetSizeClass(p, &cached_value)) { cached_value = 0; } return cached_value; } bool GetAggressiveDecommit(void) {return aggressive_decommit_;} void SetAggressiveDecommit(bool aggressive_decommit) { aggressive_decommit_ = aggressive_decommit; } private: // Allocates a big block of memory for the pagemap once we reach more than // 128MB static const size_t kPageMapBigAllocationThreshold = 128 << 20; // Minimum number of pages to fetch from system at a time. Must be // significantly bigger than kBlockSize to amortize system-call // overhead, and also to reduce external fragementation. Also, we // should keep this value big because various incarnations of Linux // have small limits on the number of mmap() regions per // address-space. // REQUIRED: kMinSystemAlloc <= kMaxPages; static const int kMinSystemAlloc = kMaxPages; // Never delay scavenging for more than the following number of // deallocated pages. With 4K pages, this comes to 4GB of // deallocation. static const int kMaxReleaseDelay = 1 << 20; // If there is nothing to release, wait for so many pages before // scavenging again. With 4K pages, this comes to 1GB of memory. static const int kDefaultReleaseDelay = 1 << 18; // Pick the appropriate map and cache types based on pointer size typedef MapSelector<kAddressBits>::Type PageMap; typedef PackedCache<kAddressBits - kPageShift> PageMapCache; mutable PageMapCache pagemap_cache_; PageMap pagemap_; // We segregate spans of a given size into two circular linked // lists: one for normal spans, and one for spans whose memory // has been returned to the system. struct SpanList { Span normal; Span returned; }; // Sets of spans with length > kMaxPages. // // Rather than using a linked list, we use sets here for efficient // best-fit search. SpanSet large_normal_; SpanSet large_returned_; // Array mapping from span length to a doubly linked list of free spans // // NOTE: index 'i' stores spans of length 'i + 1'. SpanList free_[kMaxPages]; // Statistics on system, free, and unmapped bytes Stats stats_; Span* SearchFreeAndLargeLists(Length n); bool GrowHeap(Length n); // REQUIRES: span->length >= n // REQUIRES: span->location != IN_USE // Remove span from its free list, and move any leftover part of // span into appropriate free lists. Also update "span" to have // length exactly "n" and mark it as non-free so it can be returned // to the client. After all that, decrease free_pages_ by n and // return span. Span* Carve(Span* span, Length n); void RecordSpan(Span* span) { pagemap_.set(span->start, span); if (span->length > 1) { pagemap_.set(span->start + span->length - 1, span); } } // Allocate a large span of length == n. If successful, returns a // span of exactly the specified length. Else, returns NULL. Span* AllocLarge(Length n); // Coalesce span with neighboring spans if possible, prepend to // appropriate free list, and adjust stats. void MergeIntoFreeList(Span* span); // Commit the span. void CommitSpan(Span* span); // Decommit the span. bool DecommitSpan(Span* span); // Prepends span to appropriate free list, and adjusts stats. void PrependToFreeList(Span* span); // Removes span from its free list, and adjust stats. void RemoveFromFreeList(Span* span); // Incrementally release some memory to the system. // IncrementalScavenge(n) is called whenever n pages are freed. void IncrementalScavenge(Length n); // Attempts to decommit 's' and move it to the returned freelist. // // Returns the length of the Span or zero if release failed. // // REQUIRES: 's' must be on the NORMAL freelist. Length ReleaseSpan(Span *s); // Checks if we are allowed to take more memory from the system. // If limit is reached and allowRelease is true, tries to release // some unused spans. bool EnsureLimit(Length n, bool allowRelease = true); Span* CheckAndHandlePreMerge(Span *span, Span *other); // Number of pages to deallocate before doing more scavenging int64_t scavenge_counter_; // Index of last free list where we released memory to the OS. int release_index_; bool aggressive_decommit_; }; } // namespace tcmalloc #ifdef _MSC_VER #pragma warning(pop) #endif #endif // TCMALLOC_PAGE_HEAP_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_x86-inl.h
.h
14,035
355
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // // Produce stack trace #ifndef BASE_STACKTRACE_X86_INL_H_ #define BASE_STACKTRACE_X86_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include "config.h" #include <stdlib.h> // for NULL #include <assert.h> #if defined(HAVE_SYS_UCONTEXT_H) #include <sys/ucontext.h> #elif defined(HAVE_UCONTEXT_H) #include <ucontext.h> // for ucontext_t #elif defined(HAVE_CYGWIN_SIGNAL_H) // cygwin/signal.h has a buglet where it uses pthread_attr_t without // #including <pthread.h> itself. So we have to do it. # ifdef HAVE_PTHREAD # include <pthread.h> # endif #include <cygwin/signal.h> typedef ucontext ucontext_t; #endif #ifdef HAVE_STDINT_H #include <stdint.h> // for uintptr_t #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_MMAP #include <sys/mman.h> // for msync #include "base/vdso_support.h" #endif #include "gperftools/stacktrace.h" #if defined(__linux__) && defined(__i386__) && defined(__ELF__) && defined(HAVE_MMAP) // Count "push %reg" instructions in VDSO __kernel_vsyscall(), // preceding "syscall" or "sysenter". // If __kernel_vsyscall uses frame pointer, answer 0. // // kMaxBytes tells how many instruction bytes of __kernel_vsyscall // to analyze before giving up. Up to kMaxBytes+1 bytes of // instructions could be accessed. // // Here are known __kernel_vsyscall instruction sequences: // // SYSENTER (linux-2.6.26/arch/x86/vdso/vdso32/sysenter.S). // Used on Intel. // 0xffffe400 <__kernel_vsyscall+0>: push %ecx // 0xffffe401 <__kernel_vsyscall+1>: push %edx // 0xffffe402 <__kernel_vsyscall+2>: push %ebp // 0xffffe403 <__kernel_vsyscall+3>: mov %esp,%ebp // 0xffffe405 <__kernel_vsyscall+5>: sysenter // // SYSCALL (see linux-2.6.26/arch/x86/vdso/vdso32/syscall.S). // Used on AMD. // 0xffffe400 <__kernel_vsyscall+0>: push %ebp // 0xffffe401 <__kernel_vsyscall+1>: mov %ecx,%ebp // 0xffffe403 <__kernel_vsyscall+3>: syscall // // i386 (see linux-2.6.26/arch/x86/vdso/vdso32/int80.S) // 0xffffe400 <__kernel_vsyscall+0>: int $0x80 // 0xffffe401 <__kernel_vsyscall+1>: ret // static const int kMaxBytes = 10; // We use assert()s instead of DCHECK()s -- this is too low level // for DCHECK(). static int CountPushInstructions(const unsigned char *const addr) { int result = 0; for (int i = 0; i < kMaxBytes; ++i) { if (addr[i] == 0x89) { // "mov reg,reg" if (addr[i + 1] == 0xE5) { // Found "mov %esp,%ebp". return 0; } ++i; // Skip register encoding byte. } else if (addr[i] == 0x0F && (addr[i + 1] == 0x34 || addr[i + 1] == 0x05)) { // Found "sysenter" or "syscall". return result; } else if ((addr[i] & 0xF0) == 0x50) { // Found "push %reg". ++result; } else if (addr[i] == 0xCD && addr[i + 1] == 0x80) { // Found "int $0x80" assert(result == 0); return 0; } else { // Unexpected instruction. assert(0 == "unexpected instruction in __kernel_vsyscall"); return 0; } } // Unexpected: didn't find SYSENTER or SYSCALL in // [__kernel_vsyscall, __kernel_vsyscall + kMaxBytes) interval. assert(0 == "did not find SYSENTER or SYSCALL in __kernel_vsyscall"); return 0; } #endif // Given a pointer to a stack frame, locate and return the calling // stackframe, or return NULL if no stackframe can be found. Perform sanity // checks (the strictness of which is controlled by the boolean parameter // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. template<bool STRICT_UNWINDING, bool WITH_CONTEXT> static void **NextStackFrame(void **old_sp, const void *uc) { void **new_sp = (void **) *old_sp; #if defined(__linux__) && defined(__i386__) && defined(HAVE_VDSO_SUPPORT) if (WITH_CONTEXT && uc != NULL) { // How many "push %reg" instructions are there at __kernel_vsyscall? // This is constant for a given kernel and processor, so compute // it only once. static int num_push_instructions = -1; // Sentinel: not computed yet. // Initialize with sentinel value: __kernel_rt_sigreturn can not possibly // be there. static const unsigned char *kernel_rt_sigreturn_address = NULL; static const unsigned char *kernel_vsyscall_address = NULL; if (num_push_instructions == -1) { base::VDSOSupport vdso; if (vdso.IsPresent()) { base::VDSOSupport::SymbolInfo rt_sigreturn_symbol_info; base::VDSOSupport::SymbolInfo vsyscall_symbol_info; if (!vdso.LookupSymbol("__kernel_rt_sigreturn", "LINUX_2.5", STT_FUNC, &rt_sigreturn_symbol_info) || !vdso.LookupSymbol("__kernel_vsyscall", "LINUX_2.5", STT_FUNC, &vsyscall_symbol_info) || rt_sigreturn_symbol_info.address == NULL || vsyscall_symbol_info.address == NULL) { // Unexpected: 32-bit VDSO is present, yet one of the expected // symbols is missing or NULL. assert(0 == "VDSO is present, but doesn't have expected symbols"); num_push_instructions = 0; } else { kernel_rt_sigreturn_address = reinterpret_cast<const unsigned char *>( rt_sigreturn_symbol_info.address); kernel_vsyscall_address = reinterpret_cast<const unsigned char *>( vsyscall_symbol_info.address); num_push_instructions = CountPushInstructions(kernel_vsyscall_address); } } else { num_push_instructions = 0; } } if (num_push_instructions != 0 && kernel_rt_sigreturn_address != NULL && old_sp[1] == kernel_rt_sigreturn_address) { const ucontext_t *ucv = static_cast<const ucontext_t *>(uc); // This kernel does not use frame pointer in its VDSO code, // and so %ebp is not suitable for unwinding. void **const reg_ebp = reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_EBP]); const unsigned char *const reg_eip = reinterpret_cast<unsigned char *>(ucv->uc_mcontext.gregs[REG_EIP]); if (new_sp == reg_ebp && kernel_vsyscall_address <= reg_eip && reg_eip - kernel_vsyscall_address < kMaxBytes) { // We "stepped up" to __kernel_vsyscall, but %ebp is not usable. // Restore from 'ucv' instead. void **const reg_esp = reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_ESP]); // Check that alleged %esp is not NULL and is reasonably aligned. if (reg_esp && ((uintptr_t)reg_esp & (sizeof(reg_esp) - 1)) == 0) { // Check that alleged %esp is actually readable. This is to prevent // "double fault" in case we hit the first fault due to e.g. stack // corruption. // // page_size is linker-initalized to avoid async-unsafe locking // that GCC would otherwise insert (__cxa_guard_acquire etc). static int page_size; if (page_size == 0) { // First time through. page_size = getpagesize(); } void *const reg_esp_aligned = reinterpret_cast<void *>( (uintptr_t)(reg_esp + num_push_instructions - 1) & ~(page_size - 1)); if (msync(reg_esp_aligned, page_size, MS_ASYNC) == 0) { // Alleged %esp is readable, use it for further unwinding. new_sp = reinterpret_cast<void **>( reg_esp[num_push_instructions - 1]); } } } } } #endif // Check that the transition from frame pointer old_sp to frame // pointer new_sp isn't clearly bogus if (STRICT_UNWINDING) { // With the stack growing downwards, older stack frame must be // at a greater address that the current one. if (new_sp <= old_sp) return NULL; // Assume stack frames larger than 100,000 bytes are bogus. if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return NULL; } else { // In the non-strict mode, allow discontiguous stack frames. // (alternate-signal-stacks for example). if (new_sp == old_sp) return NULL; if (new_sp > old_sp) { // And allow frames upto about 1MB. const uintptr_t delta = (uintptr_t)new_sp - (uintptr_t)old_sp; const uintptr_t acceptable_delta = 1000000; if (delta > acceptable_delta) { return NULL; } } } if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return NULL; #ifdef __i386__ // On 64-bit machines, the stack pointer can be very close to // 0xffffffff, so we explicitly check for a pointer into the // last two pages in the address space if ((uintptr_t)new_sp >= 0xffffe000) return NULL; #endif #ifdef HAVE_MMAP if (!STRICT_UNWINDING) { // Lax sanity checks cause a crash on AMD-based machines with // VDSO-enabled kernels. // Make an extra sanity check to insure new_sp is readable. // Note: NextStackFrame<false>() is only called while the program // is already on its last leg, so it's ok to be slow here. static int page_size = getpagesize(); void *new_sp_aligned = (void *)((uintptr_t)new_sp & ~(page_size - 1)); if (msync(new_sp_aligned, page_size, MS_ASYNC) == -1) return NULL; } #endif return new_sp; } #endif // BASE_STACKTRACE_X86_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) static int GET_STACK_TRACE_OR_FRAMES { void **sp; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2) || __llvm__ // __builtin_frame_address(0) can return the wrong address on gcc-4.1.0-k8. // It's always correct on llvm, and the techniques below aren't (in // particular, llvm-gcc will make a copy of pcs, so it's not in sp[2]), // so we also prefer __builtin_frame_address when running under llvm. sp = reinterpret_cast<void**>(__builtin_frame_address(0)); #elif defined(__i386__) // Stack frame format: // sp[0] pointer to previous frame // sp[1] caller address // sp[2] first argument // ... // NOTE: This will break under llvm, since result is a copy and not in sp[2] sp = (void **)&result - 2; #elif defined(__x86_64__) unsigned long rbp; // Move the value of the register %rbp into the local variable rbp. // We need 'volatile' to prevent this instruction from getting moved // around during optimization to before function prologue is done. // An alternative way to achieve this // would be (before this __asm__ instruction) to call Noop() defined as // static void Noop() __attribute__ ((noinline)); // prevent inlining // static void Noop() { asm(""); } // prevent optimizing-away __asm__ volatile ("mov %%rbp, %0" : "=r" (rbp)); // Arguments are passed in registers on x86-64, so we can't just // offset from &result sp = (void **) rbp; #else # error Using stacktrace_x86-inl.h on a non x86 architecture! #endif skip_count++; // skip parent's frame due to indirection in stacktrace.cc int n = 0; while (sp && n < max_depth) { if (*(sp+1) == reinterpret_cast<void *>(0)) { // In 64-bit code, we often see a frame that // points to itself and has a return address of 0. break; } #if !IS_WITH_CONTEXT const void *const ucp = NULL; #endif void **next_sp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(sp, ucp); if (skip_count > 0) { skip_count--; } else { result[n] = *(sp+1); #if IS_STACK_FRAMES if (next_sp > sp) { sizes[n] = (uintptr_t)next_sp - (uintptr_t)sp; } else { // A frame-size of 0 is used to indicate unknown frame size. sizes[n] = 0; } #endif n++; } sp = next_sp; } return n; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/page_heap_allocator.h
.h
6,216
180
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #ifndef TCMALLOC_PAGE_HEAP_ALLOCATOR_H_ #define TCMALLOC_PAGE_HEAP_ALLOCATOR_H_ #include <stddef.h> // for NULL, size_t #include "common.h" // for MetaDataAlloc #include "internal_logging.h" // for ASSERT namespace tcmalloc { // Simple allocator for objects of a specified type. External locking // is required before accessing one of these objects. template <class T> class PageHeapAllocator { public: // We use an explicit Init function because these variables are statically // allocated and their constructors might not have run by the time some // other static variable tries to allocate memory. void Init() { ASSERT(sizeof(T) <= kAllocIncrement); inuse_ = 0; free_area_ = NULL; free_avail_ = 0; free_list_ = NULL; // Reserve some space at the beginning to avoid fragmentation. Delete(New()); } T* New() { // Consult free list void* result; if (free_list_ != NULL) { result = free_list_; free_list_ = *(reinterpret_cast<void**>(result)); } else { if (free_avail_ < sizeof(T)) { // Need more room. We assume that MetaDataAlloc returns // suitably aligned memory. free_area_ = reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement)); if (free_area_ == NULL) { Log(kCrash, __FILE__, __LINE__, "FATAL ERROR: Out of memory trying to allocate internal " "tcmalloc data (bytes, object-size)", kAllocIncrement, sizeof(T)); } free_avail_ = kAllocIncrement; } result = free_area_; free_area_ += sizeof(T); free_avail_ -= sizeof(T); } inuse_++; return reinterpret_cast<T*>(result); } void Delete(T* p) { *(reinterpret_cast<void**>(p)) = free_list_; free_list_ = p; inuse_--; } int inuse() const { return inuse_; } private: // How much to allocate from system at a time static const int kAllocIncrement = 128 << 10; // Free area from which to carve new objects char* free_area_; size_t free_avail_; // Free list of already carved objects void* free_list_; // Number of allocated but unfreed objects int inuse_; }; // STL-compatible allocator which forwards allocations to a PageHeapAllocator. // // Like PageHeapAllocator, this requires external synchronization. To avoid multiple // separate STLPageHeapAllocator<T> from sharing the same underlying PageHeapAllocator<T>, // the |LockingTag| template argument should be used. Template instantiations with // different locking tags can safely be used concurrently. template <typename T, class LockingTag> class STLPageHeapAllocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template <class T1> struct rebind { typedef STLPageHeapAllocator<T1, LockingTag> other; }; STLPageHeapAllocator() { } STLPageHeapAllocator(const STLPageHeapAllocator&) { } template <class T1> STLPageHeapAllocator(const STLPageHeapAllocator<T1, LockingTag>&) { } ~STLPageHeapAllocator() { } pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } size_type max_size() const { return size_t(-1) / sizeof(T); } void construct(pointer p, const T& val) { ::new(p) T(val); } void construct(pointer p) { ::new(p) T(); } void destroy(pointer p) { p->~T(); } // There's no state, so these allocators are always equal bool operator==(const STLPageHeapAllocator&) const { return true; } bool operator!=(const STLPageHeapAllocator&) const { return false; } pointer allocate(size_type n, const void* = 0) { if (!underlying_.initialized) { underlying_.allocator.Init(); underlying_.initialized = true; } CHECK_CONDITION(n == 1); return underlying_.allocator.New(); } void deallocate(pointer p, size_type n) { CHECK_CONDITION(n == 1); underlying_.allocator.Delete(p); } private: struct Storage { explicit Storage(base::LinkerInitialized x) {} PageHeapAllocator<T> allocator; bool initialized; }; static Storage underlying_; }; template<typename T, class LockingTag> typename STLPageHeapAllocator<T, LockingTag>::Storage STLPageHeapAllocator<T, LockingTag>::underlying_(base::LINKER_INITIALIZED); } // namespace tcmalloc #endif // TCMALLOC_PAGE_HEAP_ALLOCATOR_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/pagemap.h
.h
10,147
329
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> // // A data structure used by the caching malloc. It maps from page# to // a pointer that contains info about that page. We use two // representations: one for 32-bit addresses, and another for 64 bit // addresses. Both representations provide the same interface. The // first representation is implemented as a flat array, the seconds as // a three-level radix tree that strips away approximately 1/3rd of // the bits every time. // // The BITS parameter should be the number of bits required to hold // a page number. E.g., with 32 bit pointers and 4K pages (i.e., // page offset fits in lower 12 bits), BITS == 20. #ifndef TCMALLOC_PAGEMAP_H_ #define TCMALLOC_PAGEMAP_H_ #include "config.h" #include <stddef.h> // for NULL, size_t #include <string.h> // for memset #if defined HAVE_STDINT_H #include <stdint.h> #elif defined HAVE_INTTYPES_H #include <inttypes.h> #else #include <sys/types.h> #endif #include "internal_logging.h" // for ASSERT // Single-level array template <int BITS> class TCMalloc_PageMap1 { private: static const int LENGTH = 1 << BITS; void** array_; public: typedef uintptr_t Number; explicit TCMalloc_PageMap1(void* (*allocator)(size_t)) { array_ = reinterpret_cast<void**>((*allocator)(sizeof(void*) << BITS)); memset(array_, 0, sizeof(void*) << BITS); } // Ensure that the map contains initialized entries "x .. x+n-1". // Returns true if successful, false if we could not allocate memory. bool Ensure(Number x, size_t n) { // Nothing to do since flat array was allocated at start. All // that's left is to check for overflow (that is, we don't want to // ensure a number y where array_[y] would be an out-of-bounds // access). return n <= LENGTH - x; // an overflow-free way to do "x + n <= LENGTH" } void PreallocateMoreMemory() {} // Return the current value for KEY. Returns NULL if not yet set, // or if k is out of range. ATTRIBUTE_ALWAYS_INLINE void* get(Number k) const { if ((k >> BITS) > 0) { return NULL; } return array_[k]; } // REQUIRES "k" is in range "[0,2^BITS-1]". // REQUIRES "k" has been ensured before. // // Sets the value 'v' for key 'k'. void set(Number k, void* v) { array_[k] = v; } // Return the first non-NULL pointer found in this map for // a page number >= k. Returns NULL if no such number is found. void* Next(Number k) const { while (k < (1 << BITS)) { if (array_[k] != NULL) return array_[k]; k++; } return NULL; } }; // Two-level radix tree template <int BITS> class TCMalloc_PageMap2 { private: static const int LEAF_BITS = (BITS + 1) / 2; static const int LEAF_LENGTH = 1 << LEAF_BITS; static const int ROOT_BITS = BITS - LEAF_BITS; static const int ROOT_LENGTH = 1 << ROOT_BITS; // Leaf node struct Leaf { void* values[LEAF_LENGTH]; }; Leaf* root_[ROOT_LENGTH]; // Pointers to child nodes void* (*allocator_)(size_t); // Memory allocator public: typedef uintptr_t Number; explicit TCMalloc_PageMap2(void* (*allocator)(size_t)) { allocator_ = allocator; memset(root_, 0, sizeof(root_)); } ATTRIBUTE_ALWAYS_INLINE void* get(Number k) const { const Number i1 = k >> LEAF_BITS; const Number i2 = k & (LEAF_LENGTH-1); if ((k >> BITS) > 0 || root_[i1] == NULL) { return NULL; } return root_[i1]->values[i2]; } void set(Number k, void* v) { const Number i1 = k >> LEAF_BITS; const Number i2 = k & (LEAF_LENGTH-1); ASSERT(i1 < ROOT_LENGTH); root_[i1]->values[i2] = v; } bool Ensure(Number start, size_t n) { for (Number key = start; key <= start + n - 1; ) { const Number i1 = key >> LEAF_BITS; // Check for overflow if (i1 >= ROOT_LENGTH) return false; // Make 2nd level node if necessary if (root_[i1] == NULL) { Leaf* leaf = reinterpret_cast<Leaf*>((*allocator_)(sizeof(Leaf))); if (leaf == NULL) return false; memset(leaf, 0, sizeof(*leaf)); root_[i1] = leaf; } // Advance key past whatever is covered by this leaf node key = ((key >> LEAF_BITS) + 1) << LEAF_BITS; } return true; } void PreallocateMoreMemory() { // Allocate enough to keep track of all possible pages if (BITS < 20) { Ensure(0, Number(1) << BITS); } } void* Next(Number k) const { while (k < (Number(1) << BITS)) { const Number i1 = k >> LEAF_BITS; Leaf* leaf = root_[i1]; if (leaf != NULL) { // Scan forward in leaf for (Number i2 = k & (LEAF_LENGTH - 1); i2 < LEAF_LENGTH; i2++) { if (leaf->values[i2] != NULL) { return leaf->values[i2]; } } } // Skip to next top-level entry k = (i1 + 1) << LEAF_BITS; } return NULL; } }; // Three-level radix tree template <int BITS> class TCMalloc_PageMap3 { private: // How many bits should we consume at each interior level static const int INTERIOR_BITS = (BITS + 2) / 3; // Round-up static const int INTERIOR_LENGTH = 1 << INTERIOR_BITS; // How many bits should we consume at leaf level static const int LEAF_BITS = BITS - 2*INTERIOR_BITS; static const int LEAF_LENGTH = 1 << LEAF_BITS; // Interior node struct Node { Node* ptrs[INTERIOR_LENGTH]; }; // Leaf node struct Leaf { void* values[LEAF_LENGTH]; }; Node root_; // Root of radix tree void* (*allocator_)(size_t); // Memory allocator Node* NewNode() { Node* result = reinterpret_cast<Node*>((*allocator_)(sizeof(Node))); if (result != NULL) { memset(result, 0, sizeof(*result)); } return result; } public: typedef uintptr_t Number; explicit TCMalloc_PageMap3(void* (*allocator)(size_t)) { allocator_ = allocator; memset(&root_, 0, sizeof(root_)); } ATTRIBUTE_ALWAYS_INLINE void* get(Number k) const { const Number i1 = k >> (LEAF_BITS + INTERIOR_BITS); const Number i2 = (k >> LEAF_BITS) & (INTERIOR_LENGTH-1); const Number i3 = k & (LEAF_LENGTH-1); if ((k >> BITS) > 0 || root_.ptrs[i1] == NULL || root_.ptrs[i1]->ptrs[i2] == NULL) { return NULL; } return reinterpret_cast<Leaf*>(root_.ptrs[i1]->ptrs[i2])->values[i3]; } void set(Number k, void* v) { ASSERT(k >> BITS == 0); const Number i1 = k >> (LEAF_BITS + INTERIOR_BITS); const Number i2 = (k >> LEAF_BITS) & (INTERIOR_LENGTH-1); const Number i3 = k & (LEAF_LENGTH-1); reinterpret_cast<Leaf*>(root_.ptrs[i1]->ptrs[i2])->values[i3] = v; } bool Ensure(Number start, size_t n) { for (Number key = start; key <= start + n - 1; ) { const Number i1 = key >> (LEAF_BITS + INTERIOR_BITS); const Number i2 = (key >> LEAF_BITS) & (INTERIOR_LENGTH-1); // Check for overflow if (i1 >= INTERIOR_LENGTH || i2 >= INTERIOR_LENGTH) return false; // Make 2nd level node if necessary if (root_.ptrs[i1] == NULL) { Node* n = NewNode(); if (n == NULL) return false; root_.ptrs[i1] = n; } // Make leaf node if necessary if (root_.ptrs[i1]->ptrs[i2] == NULL) { Leaf* leaf = reinterpret_cast<Leaf*>((*allocator_)(sizeof(Leaf))); if (leaf == NULL) return false; memset(leaf, 0, sizeof(*leaf)); root_.ptrs[i1]->ptrs[i2] = reinterpret_cast<Node*>(leaf); } // Advance key past whatever is covered by this leaf node key = ((key >> LEAF_BITS) + 1) << LEAF_BITS; } return true; } void PreallocateMoreMemory() { } void* Next(Number k) const { while (k < (Number(1) << BITS)) { const Number i1 = k >> (LEAF_BITS + INTERIOR_BITS); const Number i2 = (k >> LEAF_BITS) & (INTERIOR_LENGTH-1); if (root_.ptrs[i1] == NULL) { // Advance to next top-level entry k = (i1 + 1) << (LEAF_BITS + INTERIOR_BITS); } else { Leaf* leaf = reinterpret_cast<Leaf*>(root_.ptrs[i1]->ptrs[i2]); if (leaf != NULL) { for (Number i3 = (k & (LEAF_LENGTH-1)); i3 < LEAF_LENGTH; i3++) { if (leaf->values[i3] != NULL) { return leaf->values[i3]; } } } // Advance to next interior entry k = ((k >> LEAF_BITS) + 1) << LEAF_BITS; } } return NULL; } }; #endif // TCMALLOC_PAGEMAP_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/sampler.cc
.cc
5,116
134
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Daniel Ford #include "sampler.h" #include <algorithm> // For min() #include <math.h> #include "base/commandlineflags.h" using std::min; // The approximate gap in bytes between sampling actions. // I.e., we take one sample approximately once every // tcmalloc_sample_parameter bytes of allocation // i.e. about once every 512KB if value is 1<<19. #ifdef NO_TCMALLOC_SAMPLES DEFINE_int64(tcmalloc_sample_parameter, 0, "Unused: code is compiled with NO_TCMALLOC_SAMPLES"); #else DEFINE_int64(tcmalloc_sample_parameter, EnvToInt64("TCMALLOC_SAMPLE_PARAMETER", 0), "The approximate gap in bytes between sampling actions. " "This must be between 1 and 2^58."); #endif namespace tcmalloc { int Sampler::GetSamplePeriod() { return FLAGS_tcmalloc_sample_parameter; } // Run this before using your sampler void Sampler::Init(uint64_t seed) { ASSERT(seed != 0); // Initialize PRNG rnd_ = seed; // Step it forward 20 times for good measure for (int i = 0; i < 20; i++) { rnd_ = NextRandom(rnd_); } // Initialize counter bytes_until_sample_ = PickNextSamplingPoint(); } #define MAX_SSIZE (static_cast<ssize_t>(static_cast<size_t>(static_cast<ssize_t>(-1)) >> 1)) // Generates a geometric variable with the specified mean (512K by default). // This is done by generating a random number between 0 and 1 and applying // the inverse cumulative distribution function for an exponential. // Specifically: Let m be the inverse of the sample period, then // the probability distribution function is m*exp(-mx) so the CDF is // p = 1 - exp(-mx), so // q = 1 - p = exp(-mx) // log_e(q) = -mx // -log_e(q)/m = x // log_2(q) * (-log_e(2) * 1/m) = x // In the code, q is actually in the range 1 to 2**26, hence the -26 below ssize_t Sampler::PickNextSamplingPoint() { if (FLAGS_tcmalloc_sample_parameter <= 0) { // In this case, we don't want to sample ever, and the larger a // value we put here, the longer until we hit the slow path // again. However, we have to support the flag changing at // runtime, so pick something reasonably large (to keep overhead // low) but small enough that we'll eventually start to sample // again. return 16 << 20; } rnd_ = NextRandom(rnd_); // Take the top 26 bits as the random number // (This plus the 1<<58 sampling bound give a max possible step of // 5194297183973780480 bytes.) const uint64_t prng_mod_power = 48; // Number of bits in prng // The uint32_t cast is to prevent a (hard-to-reproduce) NAN // under piii debug for some binaries. double q = static_cast<uint32_t>(rnd_ >> (prng_mod_power - 26)) + 1.0; // Put the computed p-value through the CDF of a geometric. double interval = (log2(q) - 26) * (-log(2.0) * FLAGS_tcmalloc_sample_parameter); // Very large values of interval overflow ssize_t. If we happen to // hit such improbable condition, we simply cheat and clamp interval // to largest supported value. return static_cast<ssize_t>(std::min<double>(interval, MAX_SSIZE)); } bool Sampler::RecordAllocationSlow(size_t k) { if (!initialized_) { initialized_ = true; Init(reinterpret_cast<uintptr_t>(this)); if (static_cast<size_t>(bytes_until_sample_) >= k) { bytes_until_sample_ -= k; return true; } } bytes_until_sample_ = PickNextSamplingPoint(); return FLAGS_tcmalloc_sample_parameter <= 0; } } // namespace tcmalloc
Unknown
3D
mcellteam/mcell
libs/gperftools/src/thread_cache.h
.h
16,408
511
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #ifndef TCMALLOC_THREAD_CACHE_H_ #define TCMALLOC_THREAD_CACHE_H_ #include <config.h> #ifdef HAVE_PTHREAD #include <pthread.h> // for pthread_t, pthread_key_t #endif #include <stddef.h> // for size_t, NULL #ifdef HAVE_STDINT_H #include <stdint.h> // for uint32_t, uint64_t #endif #include <sys/types.h> // for ssize_t #include "base/commandlineflags.h" #include "common.h" #include "linked_list.h" #include "maybe_threads.h" #include "page_heap_allocator.h" #include "sampler.h" #include "static_vars.h" #include "common.h" // for SizeMap, kMaxSize, etc #include "internal_logging.h" // for ASSERT, etc #include "linked_list.h" // for SLL_Pop, SLL_PopRange, etc #include "page_heap_allocator.h" // for PageHeapAllocator #include "sampler.h" // for Sampler #include "static_vars.h" // for Static DECLARE_int64(tcmalloc_sample_parameter); namespace tcmalloc { //------------------------------------------------------------------- // Data kept per thread //------------------------------------------------------------------- class ThreadCache { public: #ifdef HAVE_TLS enum { have_tls = true }; #else enum { have_tls = false }; #endif void Init(pthread_t tid); void Cleanup(); // Accessors (mostly just for printing stats) int freelist_length(uint32 cl) const { return list_[cl].length(); } // Total byte size in cache size_t Size() const { return size_; } // Allocate an object of the given size and class. The size given // must be the same as the size of the class in the size map. void* Allocate(size_t size, uint32 cl, void *(*oom_handler)(size_t size)); void Deallocate(void* ptr, uint32 size_class); void Scavenge(); int GetSamplePeriod(); // Record allocation of "k" bytes. Return true iff allocation // should be sampled bool SampleAllocation(size_t k); bool TryRecordAllocationFast(size_t k); static void InitModule(); static void InitTSD(); static ThreadCache* GetThreadHeap(); static ThreadCache* GetCache(); static ThreadCache* GetCacheIfPresent(); static ThreadCache* GetFastPathCache(); static ThreadCache* GetCacheWhichMustBePresent(); static ThreadCache* CreateCacheIfNecessary(); static void BecomeIdle(); static void BecomeTemporarilyIdle(); static void SetUseEmergencyMalloc(); static void ResetUseEmergencyMalloc(); static bool IsUseEmergencyMalloc(); // Return the number of thread heaps in use. static inline int HeapsInUse(); // Adds to *total_bytes the total number of bytes used by all thread heaps. // Also, if class_count is not NULL, it must be an array of size kNumClasses, // and this function will increment each element of class_count by the number // of items in all thread-local freelists of the corresponding size class. // REQUIRES: Static::pageheap_lock is held. static void GetThreadStats(uint64_t* total_bytes, uint64_t* class_count); // Sets the total thread cache size to new_size, recomputing the // individual thread cache sizes as necessary. // REQUIRES: Static::pageheap lock is held. static void set_overall_thread_cache_size(size_t new_size); static size_t overall_thread_cache_size() { return overall_thread_cache_size_; } private: class FreeList { private: void* list_; // Linked list of nodes #ifdef _LP64 // On 64-bit hardware, manipulating 16-bit values may be slightly slow. uint32_t length_; // Current length. uint32_t lowater_; // Low water mark for list length. uint32_t max_length_; // Dynamic max list length based on usage. // Tracks the number of times a deallocation has caused // length_ > max_length_. After the kMaxOverages'th time, max_length_ // shrinks and length_overages_ is reset to zero. uint32_t length_overages_; #else // If we aren't using 64-bit pointers then pack these into less space. uint16_t length_; uint16_t lowater_; uint16_t max_length_; uint16_t length_overages_; #endif int32_t size_; public: void Init(size_t size) { list_ = NULL; length_ = 0; lowater_ = 0; max_length_ = 1; length_overages_ = 0; size_ = size; } // Return current length of list size_t length() const { return length_; } int32_t object_size() const { return size_; } // Return the maximum length of the list. size_t max_length() const { return max_length_; } // Set the maximum length of the list. If 'new_max' > length(), the // client is responsible for removing objects from the list. void set_max_length(size_t new_max) { max_length_ = new_max; } // Return the number of times that length() has gone over max_length(). size_t length_overages() const { return length_overages_; } void set_length_overages(size_t new_count) { length_overages_ = new_count; } // Is list empty? bool empty() const { return list_ == NULL; } // Low-water mark management int lowwatermark() const { return lowater_; } void clear_lowwatermark() { lowater_ = length_; } uint32_t Push(void* ptr) { uint32_t length = length_ + 1; SLL_Push(&list_, ptr); length_ = length; return length; } void* Pop() { ASSERT(list_ != NULL); length_--; if (length_ < lowater_) lowater_ = length_; return SLL_Pop(&list_); } bool TryPop(void **rv) { if (SLL_TryPop(&list_, rv)) { length_--; if (PREDICT_FALSE(length_ < lowater_)) lowater_ = length_; return true; } return false; } void* Next() { return SLL_Next(&list_); } void PushRange(int N, void *start, void *end) { SLL_PushRange(&list_, start, end); length_ += N; } void PopRange(int N, void **start, void **end) { SLL_PopRange(&list_, N, start, end); ASSERT(length_ >= N); length_ -= N; if (length_ < lowater_) lowater_ = length_; } }; // Gets and returns an object from the central cache, and, if possible, // also adds some objects of that size class to this thread cache. void* FetchFromCentralCache(uint32 cl, int32_t byte_size, void *(*oom_handler)(size_t size)); void ListTooLong(void* ptr, uint32 cl); // Releases some number of items from src. Adjusts the list's max_length // to eventually converge on num_objects_to_move(cl). void ListTooLong(FreeList* src, uint32 cl); // Releases N items from this thread cache. void ReleaseToCentralCache(FreeList* src, uint32 cl, int N); void SetMaxSize(int32 new_max_size); // Increase max_size_ by reducing unclaimed_cache_space_ or by // reducing the max_size_ of some other thread. In both cases, // the delta is kStealAmount. void IncreaseCacheLimit(); // Same as above but requires Static::pageheap_lock() is held. void IncreaseCacheLimitLocked(); // If TLS is available, we also store a copy of the per-thread object // in a __thread variable since __thread variables are faster to read // than pthread_getspecific(). We still need pthread_setspecific() // because __thread variables provide no way to run cleanup code when // a thread is destroyed. // We also give a hint to the compiler to use the "initial exec" TLS // model. This is faster than the default TLS model, at the cost that // you cannot dlopen this library. (To see the difference, look at // the CPU use of __tls_get_addr with and without this attribute.) // Since we don't really use dlopen in google code -- and using dlopen // on a malloc replacement is asking for trouble in any case -- that's // a good tradeoff for us. #ifdef HAVE_TLS struct ThreadLocalData { ThreadCache* fast_path_heap; ThreadCache* heap; bool use_emergency_malloc; }; static __thread ThreadLocalData threadlocal_data_ CACHELINE_ALIGNED ATTR_INITIAL_EXEC; #endif // Thread-specific key. Initialization here is somewhat tricky // because some Linux startup code invokes malloc() before it // is in a good enough state to handle pthread_keycreate(). // Therefore, we use TSD keys only after tsd_inited is set to true. // Until then, we use a slow path to get the heap object. static ATTRIBUTE_HIDDEN bool tsd_inited_; static pthread_key_t heap_key_; // Linked list of heap objects. Protected by Static::pageheap_lock. static ThreadCache* thread_heaps_; static int thread_heap_count_; // A pointer to one of the objects in thread_heaps_. Represents // the next ThreadCache from which a thread over its max_size_ should // steal memory limit. Round-robin through all of the objects in // thread_heaps_. Protected by Static::pageheap_lock. static ThreadCache* next_memory_steal_; // Overall thread cache size. Protected by Static::pageheap_lock. static size_t overall_thread_cache_size_; // Global per-thread cache size. Writes are protected by // Static::pageheap_lock. Reads are done without any locking, which should be // fine as long as size_t can be written atomically and we don't place // invariants between this variable and other pieces of state. static volatile size_t per_thread_cache_size_; // Represents overall_thread_cache_size_ minus the sum of max_size_ // across all ThreadCaches. Protected by Static::pageheap_lock. static ssize_t unclaimed_cache_space_; // This class is laid out with the most frequently used fields // first so that hot elements are placed on the same cache line. FreeList list_[kClassSizesMax]; // Array indexed by size-class int32 size_; // Combined size of data int32 max_size_; // size_ > max_size_ --> Scavenge() // We sample allocations, biased by the size of the allocation Sampler sampler_; // A sampler pthread_t tid_; // Which thread owns it bool in_setspecific_; // In call to pthread_setspecific? // Allocate a new heap. REQUIRES: Static::pageheap_lock is held. static ThreadCache* NewHeap(pthread_t tid); // Use only as pthread thread-specific destructor function. static void DestroyThreadCache(void* ptr); static void DeleteCache(ThreadCache* heap); static void RecomputePerThreadCacheSize(); public: // All ThreadCache objects are kept in a linked list (for stats collection) ThreadCache* next_; ThreadCache* prev_; // Ensure that this class is cacheline-aligned. This is critical for // performance, as false sharing would negate many of the benefits // of a per-thread cache. } CACHELINE_ALIGNED; // Allocator for thread heaps // This is logically part of the ThreadCache class, but MSVC, at // least, does not like using ThreadCache as a template argument // before the class is fully defined. So we put it outside the class. extern PageHeapAllocator<ThreadCache> threadcache_allocator; inline int ThreadCache::HeapsInUse() { return threadcache_allocator.inuse(); } inline ATTRIBUTE_ALWAYS_INLINE void* ThreadCache::Allocate( size_t size, uint32 cl, void *(*oom_handler)(size_t size)) { FreeList* list = &list_[cl]; #ifdef NO_TCMALLOC_SAMPLES size = list->object_size(); #endif ASSERT(size <= kMaxSize); ASSERT(size != 0); ASSERT(size == 0 || size == Static::sizemap()->ByteSizeForClass(cl)); void* rv; if (!list->TryPop(&rv)) { return FetchFromCentralCache(cl, size, oom_handler); } size_ -= size; return rv; } inline ATTRIBUTE_ALWAYS_INLINE void ThreadCache::Deallocate(void* ptr, uint32 cl) { ASSERT(list_[cl].max_length() > 0); FreeList* list = &list_[cl]; // This catches back-to-back frees of allocs in the same size // class. A more comprehensive (and expensive) test would be to walk // the entire freelist. But this might be enough to find some bugs. ASSERT(ptr != list->Next()); uint32_t length = list->Push(ptr); if (PREDICT_FALSE(length > list->max_length())) { ListTooLong(list, cl); return; } size_ += list->object_size(); if (PREDICT_FALSE(size_ > max_size_)){ Scavenge(); } } inline ThreadCache* ThreadCache::GetThreadHeap() { #ifdef HAVE_TLS return threadlocal_data_.heap; #else return reinterpret_cast<ThreadCache *>( perftools_pthread_getspecific(heap_key_)); #endif } inline ThreadCache* ThreadCache::GetCacheWhichMustBePresent() { #ifdef HAVE_TLS ASSERT(threadlocal_data_.heap); return threadlocal_data_.heap; #else ASSERT(perftools_pthread_getspecific(heap_key_)); return reinterpret_cast<ThreadCache *>( perftools_pthread_getspecific(heap_key_)); #endif } inline ThreadCache* ThreadCache::GetCache() { #ifdef HAVE_TLS ThreadCache* ptr = GetThreadHeap(); #else ThreadCache* ptr = NULL; if (PREDICT_TRUE(tsd_inited_)) { ptr = GetThreadHeap(); } #endif if (ptr == NULL) ptr = CreateCacheIfNecessary(); return ptr; } // In deletion paths, we do not try to create a thread-cache. This is // because we may be in the thread destruction code and may have // already cleaned up the cache for this thread. inline ThreadCache* ThreadCache::GetCacheIfPresent() { #ifndef HAVE_TLS if (PREDICT_FALSE(!tsd_inited_)) return NULL; #endif return GetThreadHeap(); } inline ThreadCache* ThreadCache::GetFastPathCache() { #ifndef HAVE_TLS return GetCacheIfPresent(); #else return threadlocal_data_.fast_path_heap; #endif } inline void ThreadCache::SetUseEmergencyMalloc() { #ifdef HAVE_TLS threadlocal_data_.fast_path_heap = NULL; threadlocal_data_.use_emergency_malloc = true; #endif } inline void ThreadCache::ResetUseEmergencyMalloc() { #ifdef HAVE_TLS ThreadCache *heap = threadlocal_data_.heap; threadlocal_data_.fast_path_heap = heap; threadlocal_data_.use_emergency_malloc = false; #endif } inline bool ThreadCache::IsUseEmergencyMalloc() { #if defined(HAVE_TLS) && defined(ENABLE_EMERGENCY_MALLOC) return PREDICT_FALSE(threadlocal_data_.use_emergency_malloc); #else return false; #endif } inline void ThreadCache::SetMaxSize(int32 new_max_size) { max_size_ = new_max_size; } #ifndef NO_TCMALLOC_SAMPLES inline bool ThreadCache::SampleAllocation(size_t k) { return !sampler_.RecordAllocation(k); } inline bool ThreadCache::TryRecordAllocationFast(size_t k) { return sampler_.TryRecordAllocationFast(k); } #else inline bool ThreadCache::SampleAllocation(size_t k) { return false; } inline bool ThreadCache::TryRecordAllocationFast(size_t k) { return true; } #endif } // namespace tcmalloc #endif // TCMALLOC_THREAD_CACHE_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/internal_logging.cc
.cc
5,828
193
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Sanjay Ghemawat <opensource@google.com> #include <config.h> #include "internal_logging.h" #include <stdarg.h> // for va_end, va_start #include <stdio.h> // for vsnprintf, va_list, etc #include <stdlib.h> // for abort #include <string.h> // for strlen, memcpy #ifdef HAVE_UNISTD_H #include <unistd.h> // for write() #endif #include <gperftools/malloc_extension.h> #include "base/logging.h" // for perftools_vsnprintf #include "base/spinlock.h" // for SpinLockHolder, SpinLock // Variables for storing crash output. Allocated statically since we // may not be able to heap-allocate while crashing. static SpinLock crash_lock(base::LINKER_INITIALIZED); static bool crashed = false; static const int kStatsBufferSize = 16 << 10; static char stats_buffer[kStatsBufferSize] = { 0 }; namespace tcmalloc { static void WriteMessage(const char* msg, int length) { write(STDERR_FILENO, msg, length); } void (*log_message_writer)(const char* msg, int length) = WriteMessage; class Logger { public: bool Add(const LogItem& item); bool AddStr(const char* str, int n); bool AddNum(uint64_t num, int base); // base must be 10 or 16. static const int kBufSize = 200; char* p_; char* end_; char buf_[kBufSize]; }; void Log(LogMode mode, const char* filename, int line, LogItem a, LogItem b, LogItem c, LogItem d) { Logger state; state.p_ = state.buf_; state.end_ = state.buf_ + sizeof(state.buf_); state.AddStr(filename, strlen(filename)) && state.AddStr(":", 1) && state.AddNum(line, 10) && state.AddStr("]", 1) && state.Add(a) && state.Add(b) && state.Add(c) && state.Add(d); // Teminate with newline if (state.p_ >= state.end_) { state.p_ = state.end_ - 1; } *state.p_ = '\n'; state.p_++; int msglen = state.p_ - state.buf_; if (mode == kLog) { (*log_message_writer)(state.buf_, msglen); return; } bool first_crash = false; { SpinLockHolder l(&crash_lock); if (!crashed) { crashed = true; first_crash = true; } } (*log_message_writer)(state.buf_, msglen); if (first_crash && mode == kCrashWithStats) { MallocExtension::instance()->GetStats(stats_buffer, kStatsBufferSize); (*log_message_writer)(stats_buffer, strlen(stats_buffer)); } abort(); } bool Logger::Add(const LogItem& item) { // Separate items with spaces if (p_ < end_) { *p_ = ' '; p_++; } switch (item.tag_) { case LogItem::kStr: return AddStr(item.u_.str, strlen(item.u_.str)); case LogItem::kUnsigned: return AddNum(item.u_.unum, 10); case LogItem::kSigned: if (item.u_.snum < 0) { // The cast to uint64_t is intentionally before the negation // so that we do not attempt to negate -2^63. return AddStr("-", 1) && AddNum(- static_cast<uint64_t>(item.u_.snum), 10); } else { return AddNum(static_cast<uint64_t>(item.u_.snum), 10); } case LogItem::kPtr: return AddStr("0x", 2) && AddNum(reinterpret_cast<uintptr_t>(item.u_.ptr), 16); default: return false; } } bool Logger::AddStr(const char* str, int n) { if (end_ - p_ < n) { return false; } else { memcpy(p_, str, n); p_ += n; return true; } } bool Logger::AddNum(uint64_t num, int base) { static const char kDigits[] = "0123456789abcdef"; char space[22]; // more than enough for 2^64 in smallest supported base (10) char* end = space + sizeof(space); char* pos = end; do { pos--; *pos = kDigits[num % base]; num /= base; } while (num > 0 && pos > space); return AddStr(pos, end - pos); } } // end tcmalloc namespace void TCMalloc_Printer::printf(const char* format, ...) { if (left_ > 0) { va_list ap; va_start(ap, format); const int r = perftools_vsnprintf(buf_, left_, format, ap); va_end(ap); if (r < 0) { // Perhaps an old glibc that returns -1 on truncation? left_ = 0; } else if (r > left_) { // Truncation left_ = 0; } else { left_ -= r; buf_ += r; } } }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/libc_override_osx.h
.h
12,064
309
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein <opensource@google.com> // // Used to override malloc routines on OS X systems. We use the // malloc-zone functionality built into OS X to register our malloc // routine. // // 1) We used to use the normal 'override weak libc malloc/etc' // technique for OS X. This is not optimal because mach does not // support the 'alias' attribute, so we had to have forwarding // functions. It also does not work very well with OS X shared // libraries (dylibs) -- in general, the shared libs don't use // tcmalloc unless run with the DYLD_FORCE_FLAT_NAMESPACE envvar. // // 2) Another approach would be to use an interposition array: // static const interpose_t interposers[] __attribute__((section("__DATA, __interpose"))) = { // { (void *)tc_malloc, (void *)malloc }, // { (void *)tc_free, (void *)free }, // }; // This requires the user to set the DYLD_INSERT_LIBRARIES envvar, so // is not much better. // // 3) Registering a new malloc zone avoids all these issues: // http://www.opensource.apple.com/source/Libc/Libc-583/include/malloc/malloc.h // http://www.opensource.apple.com/source/Libc/Libc-583/gen/malloc.c // If we make tcmalloc the default malloc zone (undocumented but // possible) then all new allocs use it, even those in shared // libraries. Allocs done before tcmalloc was installed, or in libs // that aren't using tcmalloc for some reason, will correctly go // through the malloc-zone interface when free-ing, and will pick up // the libc free rather than tcmalloc free. So it should "never" // cause a crash (famous last words). // // 4) The routines one must define for one's own malloc have changed // between OS X versions. This requires some hoops on our part, but // is only really annoying when it comes to posix_memalign. The right // behavior there depends on what OS version tcmalloc was compiled on, // but also what OS version the program is running on. For now, we // punt and don't implement our own posix_memalign. Apps that really // care can use tc_posix_memalign directly. #ifndef TCMALLOC_LIBC_OVERRIDE_OSX_INL_H_ #define TCMALLOC_LIBC_OVERRIDE_OSX_INL_H_ #include <config.h> #ifdef HAVE_FEATURES_H #include <features.h> #endif #include <gperftools/tcmalloc.h> #if !defined(__APPLE__) # error libc_override_glibc-osx.h is for OS X distributions only. #endif #include <AvailabilityMacros.h> #include <malloc/malloc.h> namespace tcmalloc { void CentralCacheLockAll(); void CentralCacheUnlockAll(); } // from AvailabilityMacros.h #if defined(MAC_OS_X_VERSION_10_6) && \ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 extern "C" { // This function is only available on 10.6 (and later) but the // LibSystem headers do not use AvailabilityMacros.h to handle weak // importing automatically. This prototype is a copy of the one in // <malloc/malloc.h> with the WEAK_IMPORT_ATTRBIUTE added. extern malloc_zone_t *malloc_default_purgeable_zone(void) WEAK_IMPORT_ATTRIBUTE; } #endif // We need to provide wrappers around all the libc functions. namespace { size_t mz_size(malloc_zone_t* zone, const void* ptr) { if (MallocExtension::instance()->GetOwnership(ptr) != MallocExtension::kOwned) return 0; // malloc_zone semantics: return 0 if we don't own the memory // TODO(csilvers): change this method to take a const void*, one day. return MallocExtension::instance()->GetAllocatedSize(const_cast<void*>(ptr)); } void* mz_malloc(malloc_zone_t* zone, size_t size) { return tc_malloc(size); } void* mz_calloc(malloc_zone_t* zone, size_t num_items, size_t size) { return tc_calloc(num_items, size); } void* mz_valloc(malloc_zone_t* zone, size_t size) { return tc_valloc(size); } void mz_free(malloc_zone_t* zone, void* ptr) { return tc_free(ptr); } void* mz_realloc(malloc_zone_t* zone, void* ptr, size_t size) { return tc_realloc(ptr, size); } void* mz_memalign(malloc_zone_t* zone, size_t align, size_t size) { return tc_memalign(align, size); } void mz_destroy(malloc_zone_t* zone) { // A no-op -- we will not be destroyed! } // malloc_introspection callbacks. I'm not clear on what all of these do. kern_return_t mi_enumerator(task_t task, void *, unsigned type_mask, vm_address_t zone_address, memory_reader_t reader, vm_range_recorder_t recorder) { // Should enumerate all the pointers we have. Seems like a lot of work. return KERN_FAILURE; } size_t mi_good_size(malloc_zone_t *zone, size_t size) { // I think it's always safe to return size, but we maybe could do better. return size; } boolean_t mi_check(malloc_zone_t *zone) { return MallocExtension::instance()->VerifyAllMemory(); } void mi_print(malloc_zone_t *zone, boolean_t verbose) { int bufsize = 8192; if (verbose) bufsize = 102400; // I picked this size arbitrarily char* buffer = new char[bufsize]; MallocExtension::instance()->GetStats(buffer, bufsize); fprintf(stdout, "%s", buffer); delete[] buffer; } void mi_log(malloc_zone_t *zone, void *address) { // I don't think we support anything like this } void mi_force_lock(malloc_zone_t *zone) { tcmalloc::CentralCacheLockAll(); } void mi_force_unlock(malloc_zone_t *zone) { tcmalloc::CentralCacheUnlockAll(); } void mi_statistics(malloc_zone_t *zone, malloc_statistics_t *stats) { // TODO(csilvers): figure out how to fill these out stats->blocks_in_use = 0; stats->size_in_use = 0; stats->max_size_in_use = 0; stats->size_allocated = 0; } boolean_t mi_zone_locked(malloc_zone_t *zone) { return false; // Hopefully unneeded by us! } } // unnamed namespace // OS X doesn't have pvalloc, cfree, malloc_statc, etc, so we can just // define our own. :-) OS X supplies posix_memalign in some versions // but not others, either strongly or weakly linked, in a way that's // difficult enough to code to correctly, that I just don't try to // support either memalign() or posix_memalign(). If you need them // and are willing to code to tcmalloc, you can use tc_posix_memalign(). extern "C" { void cfree(void* p) { tc_cfree(p); } void* pvalloc(size_t s) { return tc_pvalloc(s); } void malloc_stats(void) { tc_malloc_stats(); } int mallopt(int cmd, int v) { return tc_mallopt(cmd, v); } // No struct mallinfo on OS X, so don't define mallinfo(). // An alias for malloc_size(), which OS X defines. size_t malloc_usable_size(void* p) { return tc_malloc_size(p); } } // extern "C" static malloc_zone_t *get_default_zone() { malloc_zone_t **zones = NULL; unsigned int num_zones = 0; /* * On OSX 10.12, malloc_default_zone returns a special zone that is not * present in the list of registered zones. That zone uses a "lite zone" * if one is present (apparently enabled when malloc stack logging is * enabled), or the first registered zone otherwise. In practice this * means unless malloc stack logging is enabled, the first registered * zone is the default. * So get the list of zones to get the first one, instead of relying on * malloc_default_zone. */ if (KERN_SUCCESS != malloc_get_all_zones(0, NULL, (vm_address_t**) &zones, &num_zones)) { /* Reset the value in case the failure happened after it was set. */ num_zones = 0; } if (num_zones) return zones[0]; return malloc_default_zone(); } static void ReplaceSystemAlloc() { static malloc_introspection_t tcmalloc_introspection; memset(&tcmalloc_introspection, 0, sizeof(tcmalloc_introspection)); tcmalloc_introspection.enumerator = &mi_enumerator; tcmalloc_introspection.good_size = &mi_good_size; tcmalloc_introspection.check = &mi_check; tcmalloc_introspection.print = &mi_print; tcmalloc_introspection.log = &mi_log; tcmalloc_introspection.force_lock = &mi_force_lock; tcmalloc_introspection.force_unlock = &mi_force_unlock; static malloc_zone_t tcmalloc_zone; memset(&tcmalloc_zone, 0, sizeof(malloc_zone_t)); // Start with a version 4 zone which is used for OS X 10.4 and 10.5. tcmalloc_zone.version = 4; tcmalloc_zone.zone_name = "tcmalloc"; tcmalloc_zone.size = &mz_size; tcmalloc_zone.malloc = &mz_malloc; tcmalloc_zone.calloc = &mz_calloc; tcmalloc_zone.valloc = &mz_valloc; tcmalloc_zone.free = &mz_free; tcmalloc_zone.realloc = &mz_realloc; tcmalloc_zone.destroy = &mz_destroy; tcmalloc_zone.batch_malloc = NULL; tcmalloc_zone.batch_free = NULL; tcmalloc_zone.introspect = &tcmalloc_introspection; // from AvailabilityMacros.h #if defined(MAC_OS_X_VERSION_10_6) && \ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 // Switch to version 6 on OSX 10.6 to support memalign. tcmalloc_zone.version = 6; tcmalloc_zone.free_definite_size = NULL; tcmalloc_zone.memalign = &mz_memalign; tcmalloc_introspection.zone_locked = &mi_zone_locked; // Request the default purgable zone to force its creation. The // current default zone is registered with the purgable zone for // doing tiny and small allocs. Sadly, it assumes that the default // zone is the szone implementation from OS X and will crash if it // isn't. By creating the zone now, this will be true and changing // the default zone won't cause a problem. This only needs to // happen when actually running on OS X 10.6 and higher (note the // ifdef above only checks if we were *compiled* with 10.6 or // higher; at runtime we have to check if this symbol is defined.) if (malloc_default_purgeable_zone) { malloc_default_purgeable_zone(); } #endif // Register the tcmalloc zone. At this point, it will not be the // default zone. malloc_zone_register(&tcmalloc_zone); // Unregister and reregister the default zone. Unregistering swaps // the specified zone with the last one registered which for the // default zone makes the more recently registered zone the default // zone. The default zone is then re-registered to ensure that // allocations made from it earlier will be handled correctly. // Things are not guaranteed to work that way, but it's how they work now. malloc_zone_t *default_zone = get_default_zone(); malloc_zone_unregister(default_zone); malloc_zone_register(default_zone); } #endif // TCMALLOC_LIBC_OVERRIDE_OSX_INL_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_powerpc-linux-inl.h
.h
8,803
232
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein // // Produce stack trace. ABI documentation reference can be found at: // * PowerPC32 ABI: https://www.power.org/documentation/ // power-architecture-32-bit-abi-supplement-1-0-embeddedlinuxunified/ // * PowerPC64 ABI: // http://www.linux-foundation.org/spec/ELF/ppc64/PPC-elf64abi-1.9.html#STACK #ifndef BASE_STACKTRACE_POWERPC_INL_H_ #define BASE_STACKTRACE_POWERPC_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include <stdint.h> // for uintptr_t #include <stdlib.h> // for NULL #include <signal.h> // for siginfo_t #include <gperftools/stacktrace.h> #include <base/vdso_support.h> #if defined(HAVE_SYS_UCONTEXT_H) #include <sys/ucontext.h> #elif defined(HAVE_UCONTEXT_H) #include <ucontext.h> // for ucontext_t #endif // PowerPC64 Little Endian follows BE wrt. backchain, condition register, // and LR save area, so no need to adjust the reading struct. struct layout_ppc { struct layout_ppc *next; #ifdef __PPC64__ long condition_register; #endif void *return_addr; }; // Signal callbacks are handled by the vDSO symbol: // // * PowerPC64 Linux (arch/powerpc/kernel/vdso64/sigtramp.S): // __kernel_sigtramp_rt64 // * PowerPC32 Linux (arch/powerpc/kernel/vdso32/sigtramp.S): // __kernel_sigtramp32 // __kernel_sigtramp_rt32 // // So a backtrace may need to specially handling if the symbol readed is // the signal trampoline. // Given a pointer to a stack frame, locate and return the calling // stackframe, or return NULL if no stackframe can be found. Perform sanity // checks (the strictness of which is controlled by the boolean parameter // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. template<bool STRICT_UNWINDING> static layout_ppc *NextStackFrame(layout_ppc *current) { uintptr_t old_sp = (uintptr_t)(current); uintptr_t new_sp = (uintptr_t)(current->next); // Check that the transition from frame pointer old_sp to frame // pointer new_sp isn't clearly bogus if (STRICT_UNWINDING) { // With the stack growing downwards, older stack frame must be // at a greater address that the current one. if (new_sp <= old_sp) return NULL; // Assume stack frames larger than 100,000 bytes are bogus. if (new_sp - old_sp > 100000) return NULL; } else { // In the non-strict mode, allow discontiguous stack frames. // (alternate-signal-stacks for example). if (new_sp == old_sp) return NULL; // And allow frames upto about 1MB. if ((new_sp > old_sp) && (new_sp - old_sp > 1000000)) return NULL; } if (new_sp & (sizeof(void *) - 1)) return NULL; return current->next; } // This ensures that GetStackTrace stes up the Link Register properly. void StacktracePowerPCDummyFunction() __attribute__((noinline)); void StacktracePowerPCDummyFunction() { __asm__ volatile(""); } #endif // BASE_STACKTRACE_POWERPC_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // Load instruction used on top-of-stack get. #if defined(__PPC64__) || defined(__LP64__) # define LOAD "ld" #else # define LOAD "lwz" #endif // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) static int GET_STACK_TRACE_OR_FRAMES { layout_ppc *current; int n; // Get the address on top-of-stack current = reinterpret_cast<layout_ppc*> (__builtin_frame_address (0)); // And ignore the current symbol current = current->next; StacktracePowerPCDummyFunction(); n = 0; skip_count++; // skip parent's frame due to indirection in // stacktrace.cc base::VDSOSupport vdso; base::ElfMemImage::SymbolInfo rt_sigreturn_symbol_info; #ifdef __PPC64__ const void *sigtramp64_vdso = 0; if (vdso.LookupSymbol("__kernel_sigtramp_rt64", "LINUX_2.6.15", STT_NOTYPE, &rt_sigreturn_symbol_info)) sigtramp64_vdso = rt_sigreturn_symbol_info.address; #else const void *sigtramp32_vdso = 0; if (vdso.LookupSymbol("__kernel_sigtramp32", "LINUX_2.6.15", STT_NOTYPE, &rt_sigreturn_symbol_info)) sigtramp32_vdso = rt_sigreturn_symbol_info.address; const void *sigtramp32_rt_vdso = 0; if (vdso.LookupSymbol("__kernel_sigtramp_rt32", "LINUX_2.6.15", STT_NOTYPE, &rt_sigreturn_symbol_info)) sigtramp32_rt_vdso = rt_sigreturn_symbol_info.address; #endif while (current && n < max_depth) { // The GetStackFrames routine is called when we are in some // informational context (the failure signal handler for example). // Use the non-strict unwinding rules to produce a stack trace // that is as complete as possible (even if it contains a few // bogus entries in some rare cases). layout_ppc *next = NextStackFrame<!IS_STACK_FRAMES>(current); if (skip_count > 0) { skip_count--; } else { result[n] = current->return_addr; #ifdef __PPC64__ if (sigtramp64_vdso && (sigtramp64_vdso == current->return_addr)) { struct signal_frame_64 { char dummy[128]; ucontext_t uc; // We don't care about the rest, since the IP value is at 'uc' field. } *sigframe = reinterpret_cast<signal_frame_64*>(current); result[n] = (void*) sigframe->uc.uc_mcontext.gp_regs[PT_NIP]; } #else if (sigtramp32_vdso && (sigtramp32_vdso == current->return_addr)) { struct signal_frame_32 { char dummy[64]; struct sigcontext sctx; mcontext_t mctx; // We don't care about the rest, since IP value is at 'mctx' field. } *sigframe = reinterpret_cast<signal_frame_32*>(current); result[n] = (void*) sigframe->mctx.gregs[PT_NIP]; } else if (sigtramp32_rt_vdso && (sigtramp32_rt_vdso == current->return_addr)) { struct rt_signal_frame_32 { char dummy[64 + 16]; siginfo_t info; ucontext_t uc; // We don't care about the rest, since IP value is at 'uc' field.A } *sigframe = reinterpret_cast<rt_signal_frame_32*>(current); result[n] = (void*) sigframe->uc.uc_mcontext.uc_regs->gregs[PT_NIP]; } #endif #if IS_STACK_FRAMES if (next > current) { sizes[n] = (uintptr_t)next - (uintptr_t)current; } else { // A frame-size of 0 is used to indicate unknown frame size. sizes[n] = 0; } #endif n++; } current = next; } // It's possible the second-last stack frame can't return // (that is, it's __libc_start_main), in which case // the CRT startup code will have set its LR to 'NULL'. if (n > 0 && result[n-1] == NULL) n--; return n; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/malloc_hook-inl.h
.h
9,799
250
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // // This has the implementation details of malloc_hook that are needed // to use malloc-hook inside the tcmalloc system. It does not hold // any of the client-facing calls that are used to add new hooks. #ifndef _MALLOC_HOOK_INL_H_ #define _MALLOC_HOOK_INL_H_ #include <stddef.h> #include <sys/types.h> #include "base/atomicops.h" #include "base/basictypes.h" #include <gperftools/malloc_hook.h> #include "common.h" // for UNLIKELY namespace base { namespace internal { // Capacity of 8 means that HookList is 9 words. static const int kHookListCapacity = 8; // last entry is reserved for deprecated "singular" hooks. So we have // 7 "normal" hooks per list static const int kHookListMaxValues = 7; static const int kHookListSingularIdx = 7; // HookList: a class that provides synchronized insertions and removals and // lockless traversal. Most of the implementation is in malloc_hook.cc. template <typename T> struct PERFTOOLS_DLL_DECL HookList { COMPILE_ASSERT(sizeof(T) <= sizeof(AtomicWord), T_should_fit_in_AtomicWord); // Adds value to the list. Note that duplicates are allowed. Thread-safe and // blocking (acquires hooklist_spinlock). Returns true on success; false // otherwise (failures include invalid value and no space left). bool Add(T value); void FixupPrivEndLocked(); // Removes the first entry matching value from the list. Thread-safe and // blocking (acquires hooklist_spinlock). Returns true on success; false // otherwise (failures include invalid value and no value found). bool Remove(T value); // Store up to n values of the list in output_array, and return the number of // elements stored. Thread-safe and non-blocking. This is fast (one memory // access) if the list is empty. int Traverse(T* output_array, int n) const; // Fast inline implementation for fast path of Invoke*Hook. bool empty() const { return base::subtle::NoBarrier_Load(&priv_end) == 0; } // Used purely to handle deprecated singular hooks T GetSingular() const { const AtomicWord *place = &priv_data[kHookListSingularIdx]; return bit_cast<T>(base::subtle::NoBarrier_Load(place)); } T ExchangeSingular(T new_val); // This internal data is not private so that the class is an aggregate and can // be initialized by the linker. Don't access this directly. Use the // INIT_HOOK_LIST macro in malloc_hook.cc. // One more than the index of the last valid element in priv_data. During // 'Remove' this may be past the last valid element in priv_data, but // subsequent values will be 0. // // Index kHookListCapacity-1 is reserved as 'deprecated' single hook pointer AtomicWord priv_end; AtomicWord priv_data[kHookListCapacity]; }; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::NewHook> new_hooks_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::DeleteHook> delete_hooks_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::PreMmapHook> premmap_hooks_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::MmapHook> mmap_hooks_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::MmapReplacement> mmap_replacement_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::MunmapHook> munmap_hooks_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::MunmapReplacement> munmap_replacement_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::MremapHook> mremap_hooks_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::PreSbrkHook> presbrk_hooks_; ATTRIBUTE_VISIBILITY_HIDDEN extern HookList<MallocHook::SbrkHook> sbrk_hooks_; } } // namespace base::internal // The following method is DEPRECATED inline MallocHook::NewHook MallocHook::GetNewHook() { return base::internal::new_hooks_.GetSingular(); } inline void MallocHook::InvokeNewHook(const void* p, size_t s) { if (PREDICT_FALSE(!base::internal::new_hooks_.empty())) { InvokeNewHookSlow(p, s); } } // The following method is DEPRECATED inline MallocHook::DeleteHook MallocHook::GetDeleteHook() { return base::internal::delete_hooks_.GetSingular(); } inline void MallocHook::InvokeDeleteHook(const void* p) { if (PREDICT_FALSE(!base::internal::delete_hooks_.empty())) { InvokeDeleteHookSlow(p); } } // The following method is DEPRECATED inline MallocHook::PreMmapHook MallocHook::GetPreMmapHook() { return base::internal::premmap_hooks_.GetSingular(); } inline void MallocHook::InvokePreMmapHook(const void* start, size_t size, int protection, int flags, int fd, off_t offset) { if (!base::internal::premmap_hooks_.empty()) { InvokePreMmapHookSlow(start, size, protection, flags, fd, offset); } } // The following method is DEPRECATED inline MallocHook::MmapHook MallocHook::GetMmapHook() { return base::internal::mmap_hooks_.GetSingular(); } inline void MallocHook::InvokeMmapHook(const void* result, const void* start, size_t size, int protection, int flags, int fd, off_t offset) { if (!base::internal::mmap_hooks_.empty()) { InvokeMmapHookSlow(result, start, size, protection, flags, fd, offset); } } inline bool MallocHook::InvokeMmapReplacement(const void* start, size_t size, int protection, int flags, int fd, off_t offset, void** result) { if (!base::internal::mmap_replacement_.empty()) { return InvokeMmapReplacementSlow(start, size, protection, flags, fd, offset, result); } return false; } // The following method is DEPRECATED inline MallocHook::MunmapHook MallocHook::GetMunmapHook() { return base::internal::munmap_hooks_.GetSingular(); } inline void MallocHook::InvokeMunmapHook(const void* p, size_t size) { if (!base::internal::munmap_hooks_.empty()) { InvokeMunmapHookSlow(p, size); } } inline bool MallocHook::InvokeMunmapReplacement( const void* p, size_t size, int* result) { if (!base::internal::mmap_replacement_.empty()) { return InvokeMunmapReplacementSlow(p, size, result); } return false; } // The following method is DEPRECATED inline MallocHook::MremapHook MallocHook::GetMremapHook() { return base::internal::mremap_hooks_.GetSingular(); } inline void MallocHook::InvokeMremapHook(const void* result, const void* old_addr, size_t old_size, size_t new_size, int flags, const void* new_addr) { if (!base::internal::mremap_hooks_.empty()) { InvokeMremapHookSlow(result, old_addr, old_size, new_size, flags, new_addr); } } // The following method is DEPRECATED inline MallocHook::PreSbrkHook MallocHook::GetPreSbrkHook() { return base::internal::presbrk_hooks_.GetSingular(); } inline void MallocHook::InvokePreSbrkHook(ptrdiff_t increment) { if (!base::internal::presbrk_hooks_.empty() && increment != 0) { InvokePreSbrkHookSlow(increment); } } // The following method is DEPRECATED inline MallocHook::SbrkHook MallocHook::GetSbrkHook() { return base::internal::sbrk_hooks_.GetSingular(); } inline void MallocHook::InvokeSbrkHook(const void* result, ptrdiff_t increment) { if (!base::internal::sbrk_hooks_.empty() && increment != 0) { InvokeSbrkHookSlow(result, increment); } } #endif /* _MALLOC_HOOK_INL_H_ */
Unknown
3D
mcellteam/mcell
libs/gperftools/src/packed-cache-inl.h
.h
8,764
217
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Geoff Pike // // This file provides a minimal cache that can hold a <key, value> pair // with little if any wasted space. The types of the key and value // must be unsigned integral types or at least have unsigned semantics // for >>, casting, and similar operations. // // Synchronization is not provided. However, the cache is implemented // as an array of cache entries whose type is chosen at compile time. // If a[i] is atomic on your hardware for the chosen array type then // raciness will not necessarily lead to bugginess. The cache entries // must be large enough to hold a partial key and a value packed // together. The partial keys are bit strings of length // kKeybits - kHashbits, and the values are bit strings of length kValuebits. // // In an effort to use minimal space, every cache entry represents // some <key, value> pair; the class provides no way to mark a cache // entry as empty or uninitialized. In practice, you may want to have // reserved keys or values to get around this limitation. For example, in // tcmalloc's PageID-to-sizeclass cache, a value of 0 is used as // "unknown sizeclass." // // Usage Considerations // -------------------- // // kHashbits controls the size of the cache. The best value for // kHashbits will of course depend on the application. Perhaps try // tuning the value of kHashbits by measuring different values on your // favorite benchmark. Also remember not to be a pig; other // programs that need resources may suffer if you are. // // The main uses for this class will be when performance is // critical and there's a convenient type to hold the cache's // entries. As described above, the number of bits required // for a cache entry is (kKeybits - kHashbits) + kValuebits. Suppose // kKeybits + kValuebits is 43. Then it probably makes sense to // chose kHashbits >= 11 so that cache entries fit in a uint32. // // On the other hand, suppose kKeybits = kValuebits = 64. Then // using this class may be less worthwhile. You'll probably // be using 128 bits for each entry anyway, so maybe just pick // a hash function, H, and use an array indexed by H(key): // void Put(K key, V value) { a_[H(key)] = pair<K, V>(key, value); } // V GetOrDefault(K key, V default) { const pair<K, V> &p = a_[H(key)]; ... } // etc. // // Further Details // --------------- // // For caches used only by one thread, the following is true: // 1. For a cache c, // (c.Put(key, value), c.GetOrDefault(key, 0)) == value // and // (c.Put(key, value), <...>, c.GetOrDefault(key, 0)) == value // if the elided code contains no c.Put calls. // // 2. Has(key) will return false if no <key, value> pair with that key // has ever been Put. However, a newly initialized cache will have // some <key, value> pairs already present. When you create a new // cache, you must specify an "initial value." The initialization // procedure is equivalent to Clear(initial_value), which is // equivalent to Put(k, initial_value) for all keys k from 0 to // 2^kHashbits - 1. // // 3. If key and key' differ then the only way Put(key, value) may // cause Has(key') to change is that Has(key') may change from true to // false. Furthermore, a Put() call that doesn't change Has(key') // doesn't change GetOrDefault(key', ...) either. // // Implementation details: // // This is a direct-mapped cache with 2^kHashbits entries; the hash // function simply takes the low bits of the key. We store whole keys // if a whole key plus a whole value fits in an entry. Otherwise, an // entry is the high bits of a key and a value, packed together. // E.g., a 20 bit key and a 7 bit value only require a uint16 for each // entry if kHashbits >= 11. // // Alternatives to this scheme will be added as needed. #ifndef TCMALLOC_PACKED_CACHE_INL_H_ #define TCMALLOC_PACKED_CACHE_INL_H_ #include "config.h" #include <stddef.h> // for size_t #ifdef HAVE_STDINT_H #include <stdint.h> // for uintptr_t #endif #include "base/basictypes.h" #include "common.h" #include "internal_logging.h" // A safe way of doing "(1 << n) - 1" -- without worrying about overflow // Note this will all be resolved to a constant expression at compile-time #define N_ONES_(IntType, N) \ ( (N) == 0 ? 0 : ((static_cast<IntType>(1) << ((N)-1))-1 + \ (static_cast<IntType>(1) << ((N)-1))) ) // The types K and V provide upper bounds on the number of valid keys // and values, but we explicitly require the keys to be less than // 2^kKeybits and the values to be less than 2^kValuebits. The size // of the table is controlled by kHashbits, and the type of each entry // in the cache is uintptr_t (native machine word). See also the big // comment at the top of the file. template <int kKeybits> class PackedCache { public: typedef uintptr_t T; typedef uintptr_t K; typedef uint32 V; #ifdef TCMALLOC_SMALL_BUT_SLOW // Decrease the size map cache if running in the small memory mode. static const int kHashbits = 12; #else static const int kHashbits = 16; #endif static const int kValuebits = 7; // one bit after value bits static const int kInvalidMask = 0x80; explicit PackedCache() { COMPILE_ASSERT(kKeybits + kValuebits + 1 <= 8 * sizeof(T), use_whole_keys); COMPILE_ASSERT(kHashbits <= kKeybits, hash_function); COMPILE_ASSERT(kHashbits >= kValuebits + 1, small_values_space); Clear(); } bool TryGet(K key, V* out) const { // As with other code in this class, we touch array_ as few times // as we can. Assuming entries are read atomically then certain // races are harmless. ASSERT(key == (key & kKeyMask)); T hash = Hash(key); T expected_entry = key; expected_entry &= ~N_ONES_(T, kHashbits); T entry = array_[hash]; entry ^= expected_entry; if (PREDICT_FALSE(entry >= (1 << kValuebits))) { return false; } *out = static_cast<V>(entry); return true; } void Clear() { // sets 'invalid' bit in every byte, include value byte memset(const_cast<T* >(array_), kInvalidMask, sizeof(array_)); } void Put(K key, V value) { ASSERT(key == (key & kKeyMask)); ASSERT(value == (value & kValueMask)); array_[Hash(key)] = KeyToUpper(key) | value; } void Invalidate(K key) { ASSERT(key == (key & kKeyMask)); array_[Hash(key)] = KeyToUpper(key) | kInvalidMask; } private: // we just wipe all hash bits out of key. I.e. clear lower // kHashbits. We rely on compiler knowing value of Hash(k). static T KeyToUpper(K k) { return static_cast<T>(k) ^ Hash(k); } static T Hash(K key) { return static_cast<T>(key) & N_ONES_(size_t, kHashbits); } // For masking a K. static const K kKeyMask = N_ONES_(K, kKeybits); // For masking a V or a T. static const V kValueMask = N_ONES_(V, kValuebits); // array_ is the cache. Its elements are volatile because any // thread can write any array element at any time. volatile T array_[1 << kHashbits]; }; #undef N_ONES_ #endif // TCMALLOC_PACKED_CACHE_INL_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/profiledata.h
.h
6,596
185
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // --- // Author: Sanjay Ghemawat // Chris Demetriou (refactoring) // // Collect profiling data. // // The profile data file format is documented in // docs/cpuprofile-fileformat.html #ifndef BASE_PROFILEDATA_H_ #define BASE_PROFILEDATA_H_ #include <config.h> #include <time.h> // for time_t #include <stdint.h> #include "base/basictypes.h" // A class that accumulates profile samples and writes them to a file. // // Each sample contains a stack trace and a count. Memory usage is // reduced by combining profile samples that have the same stack trace // by adding up the associated counts. // // Profile data is accumulated in a bounded amount of memory, and will // flushed to a file as necessary to stay within the memory limit. // // Use of this class assumes external synchronization. The exact // requirements of that synchronization are that: // // - 'Add' may be called from asynchronous signals, but is not // re-entrant. // // - None of 'Start', 'Stop', 'Reset', 'Flush', and 'Add' may be // called at the same time. // // - 'Start', 'Stop', or 'Reset' should not be called while 'Enabled' // or 'GetCurrent' are running, and vice versa. // // A profiler which uses asyncronous signals to add samples will // typically use two locks to protect this data structure: // // - A SpinLock which is held over all calls except for the 'Add' // call made from the signal handler. // // - A SpinLock which is held over calls to 'Start', 'Stop', 'Reset', // 'Flush', and 'Add'. (This SpinLock should be acquired after // the first SpinLock in all cases where both are needed.) class ProfileData { public: struct State { bool enabled; // Is profiling currently enabled? time_t start_time; // If enabled, when was profiling started? char profile_name[1024]; // Name of file being written, or '\0' int samples_gathered; // Number of samples gathered to far (or 0) }; class Options { public: Options(); // Get and set the sample frequency. int frequency() const { return frequency_; } void set_frequency(int frequency) { frequency_ = frequency; } private: int frequency_; // Sample frequency. }; static const int kMaxStackDepth = 64; // Max stack depth stored in profile ProfileData(); ~ProfileData(); // If data collection is not already enabled start to collect data // into fname. Parameters related to this profiling run are specified // by 'options'. // // Returns true if data collection could be started, otherwise (if an // error occurred or if data collection was already enabled) returns // false. bool Start(const char *fname, const Options& options); // If data collection is enabled, stop data collection and write the // data to disk. void Stop(); // Stop data collection without writing anything else to disk, and // discard any collected data. void Reset(); // If data collection is enabled, record a sample with 'depth' // entries from 'stack'. (depth must be > 0.) At most // kMaxStackDepth stack entries will be recorded, starting with // stack[0]. // // This function is safe to call from asynchronous signals (but is // not re-entrant). void Add(int depth, const void* const* stack); // If data collection is enabled, write the data to disk (and leave // the collector enabled). void FlushTable(); // Is data collection currently enabled? bool enabled() const { return out_ >= 0; } // Get the current state of the data collector. void GetCurrentState(State* state) const; private: static const int kAssociativity = 4; // For hashtable static const int kBuckets = 1 << 10; // For hashtable static const int kBufferLength = 1 << 18; // For eviction buffer // Type of slots: each slot can be either a count, or a PC value typedef uintptr_t Slot; // Hash-table/eviction-buffer entry (a.k.a. a sample) struct Entry { Slot count; // Number of hits Slot depth; // Stack depth Slot stack[kMaxStackDepth]; // Stack contents }; // Hash table bucket struct Bucket { Entry entry[kAssociativity]; }; Bucket* hash_; // hash table Slot* evict_; // evicted entries int num_evicted_; // how many evicted entries? int out_; // fd for output file. int count_; // How many samples recorded int evictions_; // How many evictions size_t total_bytes_; // How much output char* fname_; // Profile file name time_t start_time_; // Start time, or 0 // Move 'entry' to the eviction buffer. void Evict(const Entry& entry); // Write contents of eviction buffer to disk. void FlushEvicted(); DISALLOW_COPY_AND_ASSIGN(ProfileData); }; #endif // BASE_PROFILEDATA_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/linked_list.h
.h
3,390
116
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> // // Some very basic linked list functions for dealing with using void * as // storage. #ifndef TCMALLOC_LINKED_LIST_H_ #define TCMALLOC_LINKED_LIST_H_ #include <stddef.h> namespace tcmalloc { inline void *SLL_Next(void *t) { return *(reinterpret_cast<void**>(t)); } inline void SLL_SetNext(void *t, void *n) { *(reinterpret_cast<void**>(t)) = n; } inline void SLL_Push(void **list, void *element) { void *next = *list; *list = element; SLL_SetNext(element, next); } inline void *SLL_Pop(void **list) { void *result = *list; *list = SLL_Next(*list); return result; } inline bool SLL_TryPop(void **list, void **rv) { void *result = *list; if (!result) { return false; } void *next = SLL_Next(*list); *list = next; *rv = result; return true; } // Remove N elements from a linked list to which head points. head will be // modified to point to the new head. start and end will point to the first // and last nodes of the range. Note that end will point to NULL after this // function is called. inline void SLL_PopRange(void **head, int N, void **start, void **end) { if (N == 0) { *start = NULL; *end = NULL; return; } void *tmp = *head; for (int i = 1; i < N; ++i) { tmp = SLL_Next(tmp); } *start = *head; *end = tmp; *head = SLL_Next(tmp); // Unlink range from list. SLL_SetNext(tmp, NULL); } inline void SLL_PushRange(void **head, void *start, void *end) { if (!start) return; SLL_SetNext(end, *head); *head = start; } inline size_t SLL_Size(void *head) { int count = 0; while (head) { count++; head = SLL_Next(head); } return count; } } // namespace tcmalloc #endif // TCMALLOC_LINKED_LIST_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/system-alloc.h
.h
4,011
93
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // // Routine that uses sbrk/mmap to allocate memory from the system. // Useful for implementing malloc. #ifndef TCMALLOC_SYSTEM_ALLOC_H_ #define TCMALLOC_SYSTEM_ALLOC_H_ #include <config.h> #include <stddef.h> // for size_t class SysAllocator; // REQUIRES: "alignment" is a power of two or "0" to indicate default alignment // // Allocate and return "N" bytes of zeroed memory. // // If actual_bytes is NULL then the returned memory is exactly the // requested size. If actual bytes is non-NULL then the allocator // may optionally return more bytes than asked for (i.e. return an // entire "huge" page if a huge page allocator is in use). // // The returned pointer is a multiple of "alignment" if non-zero. The // returned pointer will always be aligned suitably for holding a // void*, double, or size_t. In addition, if this platform defines // CACHELINE_ALIGNED, the return pointer will always be cacheline // aligned. // // Returns NULL when out of memory. extern PERFTOOLS_DLL_DECL void* TCMalloc_SystemAlloc(size_t bytes, size_t *actual_bytes, size_t alignment = 0); // This call is a hint to the operating system that the pages // contained in the specified range of memory will not be used for a // while, and can be released for use by other processes or the OS. // Pages which are released in this way may be destroyed (zeroed) by // the OS. The benefit of this function is that it frees memory for // use by the system, the cost is that the pages are faulted back into // the address space next time they are touched, which can impact // performance. (Only pages fully covered by the memory region will // be released, partial pages will not.) // // Returns false if release failed or not supported. extern PERFTOOLS_DLL_DECL bool TCMalloc_SystemRelease(void* start, size_t length); // Called to ressurect memory which has been previously released // to the system via TCMalloc_SystemRelease. An attempt to // commit a page that is already committed does not cause this // function to fail. extern PERFTOOLS_DLL_DECL void TCMalloc_SystemCommit(void* start, size_t length); // The current system allocator. extern PERFTOOLS_DLL_DECL SysAllocator* tcmalloc_sys_alloc; // Number of bytes taken from system. extern PERFTOOLS_DLL_DECL size_t TCMalloc_SystemTaken; #endif /* TCMALLOC_SYSTEM_ALLOC_H_ */
Unknown
3D
mcellteam/mcell
libs/gperftools/src/central_freelist.h
.h
8,329
212
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #ifndef TCMALLOC_CENTRAL_FREELIST_H_ #define TCMALLOC_CENTRAL_FREELIST_H_ #include "config.h" #include <stddef.h> // for size_t #ifdef HAVE_STDINT_H #include <stdint.h> // for int32_t #endif #include "base/spinlock.h" #include "base/thread_annotations.h" #include "common.h" #include "span.h" namespace tcmalloc { // Data kept per size-class in central cache. class CentralFreeList { public: // A CentralFreeList may be used before its constructor runs. // So we prevent lock_'s constructor from doing anything to the // lock_ state. CentralFreeList() : lock_(base::LINKER_INITIALIZED) { } void Init(size_t cl); // These methods all do internal locking. // Insert the specified range into the central freelist. N is the number of // elements in the range. RemoveRange() is the opposite operation. void InsertRange(void *start, void *end, int N); // Returns the actual number of fetched elements and sets *start and *end. int RemoveRange(void **start, void **end, int N); // Returns the number of free objects in cache. int length() { SpinLockHolder h(&lock_); return counter_; } // Returns the number of free objects in the transfer cache. int tc_length(); // Returns the memory overhead (internal fragmentation) attributable // to the freelist. This is memory lost when the size of elements // in a freelist doesn't exactly divide the page-size (an 8192-byte // page full of 5-byte objects would have 2 bytes memory overhead). size_t OverheadBytes(); // Lock/Unlock the internal SpinLock. Used on the pthread_atfork call // to set the lock in a consistent state before the fork. void Lock() { lock_.Lock(); } void Unlock() { lock_.Unlock(); } private: // TransferCache is used to cache transfers of // sizemap.num_objects_to_move(size_class) back and forth between // thread caches and the central cache for a given size class. struct TCEntry { void *head; // Head of chain of objects. void *tail; // Tail of chain of objects. }; // A central cache freelist can have anywhere from 0 to kMaxNumTransferEntries // slots to put link list chains into. #ifdef TCMALLOC_SMALL_BUT_SLOW // For the small memory model, the transfer cache is not used. static const int kMaxNumTransferEntries = 0; #else // Starting point for the the maximum number of entries in the transfer cache. // This actual maximum for a given size class may be lower than this // maximum value. static const int kMaxNumTransferEntries = 64; #endif // REQUIRES: lock_ is held // Remove object from cache and return. // Return NULL if no free entries in cache. int FetchFromOneSpans(int N, void **start, void **end) EXCLUSIVE_LOCKS_REQUIRED(lock_); // REQUIRES: lock_ is held // Remove object from cache and return. Fetches // from pageheap if cache is empty. Only returns // NULL on allocation failure. int FetchFromOneSpansSafe(int N, void **start, void **end) EXCLUSIVE_LOCKS_REQUIRED(lock_); // REQUIRES: lock_ is held // Release a linked list of objects to spans. // May temporarily release lock_. void ReleaseListToSpans(void *start) EXCLUSIVE_LOCKS_REQUIRED(lock_); // REQUIRES: lock_ is held // Release an object to spans. // May temporarily release lock_. void ReleaseToSpans(void* object) EXCLUSIVE_LOCKS_REQUIRED(lock_); // REQUIRES: lock_ is held // Populate cache by fetching from the page heap. // May temporarily release lock_. void Populate() EXCLUSIVE_LOCKS_REQUIRED(lock_); // REQUIRES: lock is held. // Tries to make room for a TCEntry. If the cache is full it will try to // expand it at the cost of some other cache size. Return false if there is // no space. bool MakeCacheSpace() EXCLUSIVE_LOCKS_REQUIRED(lock_); // REQUIRES: lock_ for locked_size_class is held. // Picks a "random" size class to steal TCEntry slot from. In reality it // just iterates over the sizeclasses but does so without taking a lock. // Returns true on success. // May temporarily lock a "random" size class. static bool EvictRandomSizeClass(int locked_size_class, bool force); // REQUIRES: lock_ is *not* held. // Tries to shrink the Cache. If force is true it will relase objects to // spans if it allows it to shrink the cache. Return false if it failed to // shrink the cache. Decrements cache_size_ on succeess. // May temporarily take lock_. If it takes lock_, the locked_size_class // lock is released to keep the thread from holding two size class locks // concurrently which could lead to a deadlock. bool ShrinkCache(int locked_size_class, bool force) LOCKS_EXCLUDED(lock_); // This lock protects all the data members. cached_entries and cache_size_ // may be looked at without holding the lock. SpinLock lock_; // We keep linked lists of empty and non-empty spans. size_t size_class_; // My size class Span empty_; // Dummy header for list of empty spans Span nonempty_; // Dummy header for list of non-empty spans size_t num_spans_; // Number of spans in empty_ plus nonempty_ size_t counter_; // Number of free objects in cache entry // Here we reserve space for TCEntry cache slots. Space is preallocated // for the largest possible number of entries than any one size class may // accumulate. Not all size classes are allowed to accumulate // kMaxNumTransferEntries, so there is some wasted space for those size // classes. TCEntry tc_slots_[kMaxNumTransferEntries]; // Number of currently used cached entries in tc_slots_. This variable is // updated under a lock but can be read without one. int32_t used_slots_; // The current number of slots for this size class. This is an // adaptive value that is increased if there is lots of traffic // on a given size class. int32_t cache_size_; // Maximum size of the cache for a given size class. int32_t max_cache_size_; }; // Pads each CentralCache object to multiple of 64 bytes. Since some // compilers (such as MSVC) don't like it when the padding is 0, I use // template specialization to remove the padding entirely when // sizeof(CentralFreeList) is a multiple of 64. template<int kFreeListSizeMod64> class CentralFreeListPaddedTo : public CentralFreeList { private: char pad_[64 - kFreeListSizeMod64]; }; template<> class CentralFreeListPaddedTo<0> : public CentralFreeList { }; class CentralFreeListPadded : public CentralFreeListPaddedTo< sizeof(CentralFreeList) % 64> { }; } // namespace tcmalloc #endif // TCMALLOC_CENTRAL_FREELIST_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/symbolize.cc
.cc
11,518
299
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein // // This forks out to pprof to do the actual symbolizing. We might // be better off writing our own in C++. #include "config.h" #include "symbolize.h" #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> // for write() #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> // for socketpair() -- needed by Symbolize #endif #ifdef HAVE_SYS_WAIT_H #include <sys/wait.h> // for wait() -- needed by Symbolize #endif #ifdef HAVE_POLL_H #include <poll.h> #endif #ifdef __MACH__ #include <mach-o/dyld.h> // for GetProgramInvocationName() #include <limits.h> // for PATH_MAX #endif #if defined(__CYGWIN__) || defined(__CYGWIN32__) #include <io.h> // for get_osfhandle() #endif #include <string> #include "base/commandlineflags.h" #include "base/logging.h" #include "base/sysinfo.h" #if defined(__FreeBSD__) #include <sys/sysctl.h> #endif using std::string; using tcmalloc::DumpProcSelfMaps; // from sysinfo.h // pprof may be used after destructors are // called (since that's when leak-checking is done), so we make // a more-permanent copy that won't ever get destroyed. static char* get_pprof_path() { static char* result = ([] () { string pprof_string = EnvToString("PPROF_PATH", "pprof-symbolize"); return strdup(pprof_string.c_str()); })(); return result; } // Returns NULL if we're on an OS where we can't get the invocation name. // Using a static var is ok because we're not called from a thread. static const char* GetProgramInvocationName() { #if defined(HAVE_PROGRAM_INVOCATION_NAME) #ifdef __UCLIBC__ extern const char* program_invocation_name; // uclibc provides this #else extern char* program_invocation_name; // gcc provides this #endif return program_invocation_name; #elif defined(__MACH__) // We don't want to allocate memory for this since we may be // calculating it when memory is corrupted. static char program_invocation_name[PATH_MAX]; if (program_invocation_name[0] == '\0') { // first time calculating uint32_t length = sizeof(program_invocation_name); if (_NSGetExecutablePath(program_invocation_name, &length)) return NULL; } return program_invocation_name; #elif defined(__FreeBSD__) static char program_invocation_name[PATH_MAX]; size_t len = sizeof(program_invocation_name); static const int name[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; if (!sysctl(name, 4, program_invocation_name, &len, NULL, 0)) return program_invocation_name; return NULL; #else return NULL; // figure out a way to get argv[0] #endif } // Prints an error message when you can't run Symbolize(). static void PrintError(const char* reason) { RAW_LOG(ERROR, "*** WARNING: Cannot convert addresses to symbols in output below.\n" "*** Reason: %s\n" "*** If you cannot fix this, try running pprof directly.\n", reason); } void SymbolTable::Add(const void* addr) { symbolization_table_[addr] = ""; } const char* SymbolTable::GetSymbol(const void* addr) { return symbolization_table_[addr]; } // Updates symbolization_table with the pointers to symbol names corresponding // to its keys. The symbol names are stored in out, which is allocated and // freed by the caller of this routine. // Note that the forking/etc is not thread-safe or re-entrant. That's // ok for the purpose we need -- reporting leaks detected by heap-checker // -- but be careful if you decide to use this routine for other purposes. // Returns number of symbols read on error. If can't symbolize, returns 0 // and emits an error message about why. int SymbolTable::Symbolize() { #if !defined(HAVE_UNISTD_H) || !defined(HAVE_SYS_SOCKET_H) || !defined(HAVE_SYS_WAIT_H) PrintError("Perftools does not know how to call a sub-process on this O/S"); return 0; #else const char* argv0 = GetProgramInvocationName(); if (argv0 == NULL) { // can't call symbolize if we can't figure out our name PrintError("Cannot figure out the name of this executable (argv0)"); return 0; } if (access(get_pprof_path(), R_OK) != 0) { PrintError("Cannot find 'pprof' (is PPROF_PATH set correctly?)"); return 0; } // All this work is to do two-way communication. ugh. int *child_in = NULL; // file descriptors int *child_out = NULL; // for now, we don't worry about child_err int child_fds[5][2]; // socketpair may be called up to five times below // The client program may close its stdin and/or stdout and/or stderr // thus allowing socketpair to reuse file descriptors 0, 1 or 2. // In this case the communication between the forked processes may be broken // if either the parent or the child tries to close or duplicate these // descriptors. The loop below produces two pairs of file descriptors, each // greater than 2 (stderr). for (int i = 0; i < 5; i++) { if (socketpair(AF_UNIX, SOCK_STREAM, 0, child_fds[i]) == -1) { for (int j = 0; j < i; j++) { close(child_fds[j][0]); close(child_fds[j][1]); PrintError("Cannot create a socket pair"); } return 0; } else { if ((child_fds[i][0] > 2) && (child_fds[i][1] > 2)) { if (child_in == NULL) { child_in = child_fds[i]; } else { child_out = child_fds[i]; for (int j = 0; j < i; j++) { if (child_fds[j] == child_in) continue; close(child_fds[j][0]); close(child_fds[j][1]); } break; } } } } switch (fork()) { case -1: { // error close(child_in[0]); close(child_in[1]); close(child_out[0]); close(child_out[1]); PrintError("Unknown error calling fork()"); return 0; } case 0: { // child close(child_in[1]); // child uses the 0's, parent uses the 1's close(child_out[1]); // child uses the 0's, parent uses the 1's close(0); close(1); if (dup2(child_in[0], 0) == -1) _exit(1); if (dup2(child_out[0], 1) == -1) _exit(2); // Unset vars that might cause trouble when we fork unsetenv("CPUPROFILE"); unsetenv("HEAPPROFILE"); unsetenv("HEAPCHECK"); unsetenv("PERFTOOLS_VERBOSE"); execlp(get_pprof_path(), get_pprof_path(), "--symbols", argv0, NULL); _exit(3); // if execvp fails, it's bad news for us } default: { // parent close(child_in[0]); // child uses the 0's, parent uses the 1's close(child_out[0]); // child uses the 0's, parent uses the 1's #ifdef HAVE_POLL_H // Waiting for 1ms seems to give the OS time to notice any errors. poll(0, 0, 1); // For maximum safety, we check to make sure the execlp // succeeded before trying to write. (Otherwise we'll get a // SIGPIPE.) For systems without poll.h, we'll just skip this // check, and trust that the user set PPROF_PATH correctly! struct pollfd pfd = { child_in[1], POLLOUT, 0 }; if (!poll(&pfd, 1, 0) || !(pfd.revents & POLLOUT) || (pfd.revents & (POLLHUP|POLLERR))) { PrintError("Cannot run 'pprof' (is PPROF_PATH set correctly?)"); return 0; } #endif #if defined(__CYGWIN__) || defined(__CYGWIN32__) // On cygwin, DumpProcSelfMaps() takes a HANDLE, not an fd. Convert. const HANDLE symbols_handle = (HANDLE) get_osfhandle(child_in[1]); DumpProcSelfMaps(symbols_handle); #else DumpProcSelfMaps(child_in[1]); // what pprof expects on stdin #endif // Allocate 24 bytes = ("0x" + 8 bytes + "\n" + overhead) for each // address to feed to pprof. const int kOutBufSize = 24 * symbolization_table_.size(); char *pprof_buffer = new char[kOutBufSize]; int written = 0; for (SymbolMap::const_iterator iter = symbolization_table_.begin(); iter != symbolization_table_.end(); ++iter) { written += snprintf(pprof_buffer + written, kOutBufSize - written, // pprof expects format to be 0xXXXXXX "0x%" PRIxPTR "\n", reinterpret_cast<uintptr_t>(iter->first)); } write(child_in[1], pprof_buffer, strlen(pprof_buffer)); close(child_in[1]); // that's all we need to write delete[] pprof_buffer; const int kSymbolBufferSize = kSymbolSize * symbolization_table_.size(); int total_bytes_read = 0; delete[] symbol_buffer_; symbol_buffer_ = new char[kSymbolBufferSize]; memset(symbol_buffer_, '\0', kSymbolBufferSize); while (1) { int bytes_read = read(child_out[1], symbol_buffer_ + total_bytes_read, kSymbolBufferSize - total_bytes_read); if (bytes_read < 0) { close(child_out[1]); PrintError("Cannot read data from pprof"); return 0; } else if (bytes_read == 0) { close(child_out[1]); wait(NULL); break; } else { total_bytes_read += bytes_read; } } // We have successfully read the output of pprof into out. Make sure // the last symbol is full (we can tell because it ends with a \n). if (total_bytes_read == 0 || symbol_buffer_[total_bytes_read - 1] != '\n') return 0; // make the symbolization_table_ values point to the output vector SymbolMap::iterator fill = symbolization_table_.begin(); int num_symbols = 0; const char *current_name = symbol_buffer_; for (int i = 0; i < total_bytes_read; i++) { if (symbol_buffer_[i] == '\n') { fill->second = current_name; symbol_buffer_[i] = '\0'; current_name = symbol_buffer_ + i + 1; fill++; num_symbols++; } } return num_symbols; } } PrintError("Unkown error (should never occur!)"); return 0; // shouldn't be reachable #endif }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/malloc_hook_mmap_linux.h
.h
8,603
245
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> // We define mmap() and mmap64(), which somewhat reimplements libc's mmap // syscall stubs. Unfortunately libc only exports the stubs via weak symbols // (which we're overriding with our mmap64() and mmap() wrappers) so we can't // just call through to them. #ifndef __linux # error Should only be including malloc_hook_mmap_linux.h on linux systems. #endif #include <unistd.h> #include <syscall.h> #include <sys/mman.h> #include <errno.h> #include "base/linux_syscall_support.h" // The x86-32 case and the x86-64 case differ: // 32b has a mmap2() syscall, 64b does not. // 64b and 32b have different calling conventions for mmap(). // I test for 64-bit first so I don't have to do things like // '#if (defined(__mips__) && !defined(__MIPS64__))' as a mips32 check. #if defined(__x86_64__) \ || defined(__PPC64__) \ || defined(__aarch64__) \ || (defined(_MIPS_SIM) && (_MIPS_SIM == _ABI64 || _MIPS_SIM == _ABIN32)) \ || defined(__s390__) static inline void* do_mmap64(void *start, size_t length, int prot, int flags, int fd, off64_t offset) __THROW { return (void*)syscall(SYS_mmap, start, length, prot, flags, fd, offset); } #define MALLOC_HOOK_HAVE_DO_MMAP64 1 #elif defined(__i386__) || defined(__PPC__) || defined(__mips__) || \ defined(__arm__) static inline void* do_mmap64(void *start, size_t length, int prot, int flags, int fd, off64_t offset) __THROW { void *result; // Try mmap2() unless it's not supported static bool have_mmap2 = true; if (have_mmap2) { static int pagesize = 0; if (!pagesize) pagesize = getpagesize(); // Check that the offset is page aligned if (offset & (pagesize - 1)) { result = MAP_FAILED; errno = EINVAL; goto out; } result = (void *)syscall(SYS_mmap2, start, length, prot, flags, fd, (off_t) (offset / pagesize)); if (result != MAP_FAILED || errno != ENOSYS) goto out; // We don't have mmap2() after all - don't bother trying it in future have_mmap2 = false; } if (((off_t)offset) != offset) { // If we're trying to map a 64-bit offset, fail now since we don't // have 64-bit mmap() support. result = MAP_FAILED; errno = EINVAL; goto out; } #ifdef __NR_mmap { // Fall back to old 32-bit offset mmap() call // Old syscall interface cannot handle six args, so pass in an array int32 args[6] = { (int32) start, (int32) length, prot, flags, fd, (int32)(off_t) offset }; result = (void *)syscall(SYS_mmap, args); } #else // Some Linux ports like ARM EABI Linux has no mmap, just mmap2. result = MAP_FAILED; #endif out: return result; } #define MALLOC_HOOK_HAVE_DO_MMAP64 1 #endif // #if defined(__x86_64__) #ifdef MALLOC_HOOK_HAVE_DO_MMAP64 // We use do_mmap64 abstraction to put MallocHook::InvokeMmapHook // calls right into mmap and mmap64, so that the stack frames in the caller's // stack are at the same offsets for all the calls of memory allocating // functions. // Put all callers of MallocHook::Invoke* in this module into // malloc_hook section, // so that MallocHook::GetCallerStackTrace can function accurately: // Make sure mmap64 and mmap doesn't get #define'd away by <sys/mman.h> # undef mmap64 # undef mmap extern "C" { void* mmap64(void *start, size_t length, int prot, int flags, int fd, off64_t offset ) __THROW ATTRIBUTE_SECTION(malloc_hook); void* mmap(void *start, size_t length,int prot, int flags, int fd, off_t offset) __THROW ATTRIBUTE_SECTION(malloc_hook); int munmap(void* start, size_t length) __THROW ATTRIBUTE_SECTION(malloc_hook); void* mremap(void* old_addr, size_t old_size, size_t new_size, int flags, ...) __THROW ATTRIBUTE_SECTION(malloc_hook); void* sbrk(intptr_t increment) __THROW ATTRIBUTE_SECTION(malloc_hook); } extern "C" void* mmap64(void *start, size_t length, int prot, int flags, int fd, off64_t offset) __THROW { MallocHook::InvokePreMmapHook(start, length, prot, flags, fd, offset); void *result; if (!MallocHook::InvokeMmapReplacement( start, length, prot, flags, fd, offset, &result)) { result = do_mmap64(start, length, prot, flags, fd, offset); } MallocHook::InvokeMmapHook(result, start, length, prot, flags, fd, offset); return result; } # if !defined(__USE_FILE_OFFSET64) || !defined(__REDIRECT_NTH) extern "C" void* mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset) __THROW { MallocHook::InvokePreMmapHook(start, length, prot, flags, fd, offset); void *result; if (!MallocHook::InvokeMmapReplacement( start, length, prot, flags, fd, offset, &result)) { result = do_mmap64(start, length, prot, flags, fd, static_cast<size_t>(offset)); // avoid sign extension } MallocHook::InvokeMmapHook(result, start, length, prot, flags, fd, offset); return result; } # endif // !defined(__USE_FILE_OFFSET64) || !defined(__REDIRECT_NTH) extern "C" int munmap(void* start, size_t length) __THROW { MallocHook::InvokeMunmapHook(start, length); int result; if (!MallocHook::InvokeMunmapReplacement(start, length, &result)) { result = syscall(SYS_munmap, start, length); } return result; } extern "C" void* mremap(void* old_addr, size_t old_size, size_t new_size, int flags, ...) __THROW { va_list ap; va_start(ap, flags); void *new_address = va_arg(ap, void *); va_end(ap); void* result = (void*)syscall(SYS_mremap, old_addr, old_size, new_size, flags, new_address); MallocHook::InvokeMremapHook(result, old_addr, old_size, new_size, flags, new_address); return result; } #ifdef HAVE___SBRK // libc's version: extern "C" void* __sbrk(intptr_t increment); extern "C" void* sbrk(intptr_t increment) __THROW { MallocHook::InvokePreSbrkHook(increment); void *result = __sbrk(increment); MallocHook::InvokeSbrkHook(result, increment); return result; } #endif /*static*/void* MallocHook::UnhookedMMap(void *start, size_t length, int prot, int flags, int fd, off_t offset) { void* result; if (!MallocHook::InvokeMmapReplacement( start, length, prot, flags, fd, offset, &result)) { result = do_mmap64(start, length, prot, flags, fd, offset); } return result; } /*static*/int MallocHook::UnhookedMUnmap(void *start, size_t length) { int result; if (!MallocHook::InvokeMunmapReplacement(start, length, &result)) { result = syscall(SYS_munmap, start, length); } return result; } #undef MALLOC_HOOK_HAVE_DO_MMAP64 #endif // #ifdef MALLOC_HOOK_HAVE_DO_MMAP64
Unknown
3D
mcellteam/mcell
libs/gperftools/src/maybe_threads.h
.h
2,782
62
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Paul Menage <opensource@google.com> //------------------------------------------------------------------- // Some wrappers for pthread functions so that we can be LD_PRELOADed // against non-pthreads apps. //------------------------------------------------------------------- #ifndef GOOGLE_MAYBE_THREADS_H_ #define GOOGLE_MAYBE_THREADS_H_ #ifdef HAVE_PTHREAD #include <pthread.h> #endif int perftools_pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)); int perftools_pthread_key_delete(pthread_key_t key); void *perftools_pthread_getspecific(pthread_key_t key); int perftools_pthread_setspecific(pthread_key_t key, void *val); int perftools_pthread_once(pthread_once_t *ctl, void (*init_routine) (void)); // Our wrapper for pthread_atfork. Does _nothing_ when there are no // threads. See static_vars.cc:SetupAtForkLocksHandler for only user // of this. void perftools_pthread_atfork(void (*before)(), void (*parent_after)(), void (*child_after)()); #endif /* GOOGLE_MAYBE_THREADS_H_ */
Unknown
3D
mcellteam/mcell
libs/gperftools/src/malloc_extension.cc
.cc
12,819
389
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #include <config.h> #include <assert.h> #include <string.h> #include <stdio.h> #if defined HAVE_STDINT_H #include <stdint.h> #elif defined HAVE_INTTYPES_H #include <inttypes.h> #else #include <sys/types.h> #endif #include <string> #include "base/dynamic_annotations.h" #include "base/sysinfo.h" // for FillProcSelfMaps #ifndef NO_HEAP_CHECK #include "gperftools/heap-checker.h" #endif #include "gperftools/malloc_extension.h" #include "gperftools/malloc_extension_c.h" #include "maybe_threads.h" #include "base/googleinit.h" using STL_NAMESPACE::string; using STL_NAMESPACE::vector; static void DumpAddressMap(string* result) { *result += "\nMAPPED_LIBRARIES:\n"; // We keep doubling until we get a fit const size_t old_resultlen = result->size(); for (int amap_size = 10240; amap_size < 10000000; amap_size *= 2) { result->resize(old_resultlen + amap_size); bool wrote_all = false; const int bytes_written = tcmalloc::FillProcSelfMaps(&((*result)[old_resultlen]), amap_size, &wrote_all); if (wrote_all) { // we fit! (*result)[old_resultlen + bytes_written] = '\0'; result->resize(old_resultlen + bytes_written); return; } } result->reserve(old_resultlen); // just don't print anything } // Note: this routine is meant to be called before threads are spawned. void MallocExtension::Initialize() { static bool initialize_called = false; if (initialize_called) return; initialize_called = true; #ifdef __GLIBC__ // GNU libc++ versions 3.3 and 3.4 obey the environment variables // GLIBCPP_FORCE_NEW and GLIBCXX_FORCE_NEW respectively. Setting // one of these variables forces the STL default allocator to call // new() or delete() for each allocation or deletion. Otherwise // the STL allocator tries to avoid the high cost of doing // allocations by pooling memory internally. However, tcmalloc // does allocations really fast, especially for the types of small // items one sees in STL, so it's better off just using us. // TODO: control whether we do this via an environment variable? setenv("GLIBCPP_FORCE_NEW", "1", false /* no overwrite*/); setenv("GLIBCXX_FORCE_NEW", "1", false /* no overwrite*/); // Now we need to make the setenv 'stick', which it may not do since // the env is flakey before main() is called. But luckily stl only // looks at this env var the first time it tries to do an alloc, and // caches what it finds. So we just cause an stl alloc here. string dummy("I need to be allocated"); dummy += "!"; // so the definition of dummy isn't optimized out #endif /* __GLIBC__ */ } // SysAllocator implementation SysAllocator::~SysAllocator() {} // Default implementation -- does nothing MallocExtension::~MallocExtension() { } bool MallocExtension::VerifyAllMemory() { return true; } bool MallocExtension::VerifyNewMemory(const void* p) { return true; } bool MallocExtension::VerifyArrayNewMemory(const void* p) { return true; } bool MallocExtension::VerifyMallocMemory(const void* p) { return true; } bool MallocExtension::GetNumericProperty(const char* property, size_t* value) { return false; } bool MallocExtension::SetNumericProperty(const char* property, size_t value) { return false; } void MallocExtension::GetStats(char* buffer, int length) { assert(length > 0); buffer[0] = '\0'; } bool MallocExtension::MallocMemoryStats(int* blocks, size_t* total, int histogram[kMallocHistogramSize]) { *blocks = 0; *total = 0; memset(histogram, 0, sizeof(*histogram) * kMallocHistogramSize); return true; } void** MallocExtension::ReadStackTraces(int* sample_period) { return NULL; } void** MallocExtension::ReadHeapGrowthStackTraces() { return NULL; } void MallocExtension::MarkThreadIdle() { // Default implementation does nothing } void MallocExtension::MarkThreadBusy() { // Default implementation does nothing } SysAllocator* MallocExtension::GetSystemAllocator() { return NULL; } void MallocExtension::SetSystemAllocator(SysAllocator *a) { // Default implementation does nothing } void MallocExtension::ReleaseToSystem(size_t num_bytes) { // Default implementation does nothing } void MallocExtension::ReleaseFreeMemory() { ReleaseToSystem(static_cast<size_t>(-1)); // SIZE_T_MAX } void MallocExtension::SetMemoryReleaseRate(double rate) { // Default implementation does nothing } double MallocExtension::GetMemoryReleaseRate() { return -1.0; } size_t MallocExtension::GetEstimatedAllocatedSize(size_t size) { return size; } size_t MallocExtension::GetAllocatedSize(const void* p) { assert(GetOwnership(p) != kNotOwned); return 0; } MallocExtension::Ownership MallocExtension::GetOwnership(const void* p) { return kUnknownOwnership; } void MallocExtension::GetFreeListSizes( vector<MallocExtension::FreeListInfo>* v) { v->clear(); } size_t MallocExtension::GetThreadCacheSize() { return 0; } void MallocExtension::MarkThreadTemporarilyIdle() { // Default implementation does nothing } // The current malloc extension object. static MallocExtension* current_instance; static void InitModule() { if (current_instance != NULL) { return; } current_instance = new MallocExtension; #ifndef NO_HEAP_CHECK HeapLeakChecker::IgnoreObject(current_instance); #endif } REGISTER_MODULE_INITIALIZER(malloc_extension_init, InitModule()) MallocExtension* MallocExtension::instance() { InitModule(); return current_instance; } void MallocExtension::Register(MallocExtension* implementation) { InitModule(); // When running under valgrind, our custom malloc is replaced with // valgrind's one and malloc extensions will not work. (Note: // callers should be responsible for checking that they are the // malloc that is really being run, before calling Register. This // is just here as an extra sanity check.) if (!RunningOnValgrind()) { current_instance = implementation; } } // ----------------------------------------------------------------------- // Heap sampling support // ----------------------------------------------------------------------- namespace { // Accessors uintptr_t Count(void** entry) { return reinterpret_cast<uintptr_t>(entry[0]); } uintptr_t Size(void** entry) { return reinterpret_cast<uintptr_t>(entry[1]); } uintptr_t Depth(void** entry) { return reinterpret_cast<uintptr_t>(entry[2]); } void* PC(void** entry, int i) { return entry[3+i]; } void PrintCountAndSize(MallocExtensionWriter* writer, uintptr_t count, uintptr_t size) { char buf[100]; snprintf(buf, sizeof(buf), "%6" PRIu64 ": %8" PRIu64 " [%6" PRIu64 ": %8" PRIu64 "] @", static_cast<uint64>(count), static_cast<uint64>(size), static_cast<uint64>(count), static_cast<uint64>(size)); writer->append(buf, strlen(buf)); } void PrintHeader(MallocExtensionWriter* writer, const char* label, void** entries) { // Compute the total count and total size uintptr_t total_count = 0; uintptr_t total_size = 0; for (void** entry = entries; Count(entry) != 0; entry += 3 + Depth(entry)) { total_count += Count(entry); total_size += Size(entry); } const char* const kTitle = "heap profile: "; writer->append(kTitle, strlen(kTitle)); PrintCountAndSize(writer, total_count, total_size); writer->append(" ", 1); writer->append(label, strlen(label)); writer->append("\n", 1); } void PrintStackEntry(MallocExtensionWriter* writer, void** entry) { PrintCountAndSize(writer, Count(entry), Size(entry)); for (int i = 0; i < Depth(entry); i++) { char buf[32]; snprintf(buf, sizeof(buf), " %p", PC(entry, i)); writer->append(buf, strlen(buf)); } writer->append("\n", 1); } } void MallocExtension::GetHeapSample(MallocExtensionWriter* writer) { int sample_period = 0; void** entries = ReadStackTraces(&sample_period); if (entries == NULL) { const char* const kErrorMsg = "This malloc implementation does not support sampling.\n" "As of 2005/01/26, only tcmalloc supports sampling, and\n" "you are probably running a binary that does not use\n" "tcmalloc.\n"; writer->append(kErrorMsg, strlen(kErrorMsg)); return; } char label[32]; sprintf(label, "heap_v2/%d", sample_period); PrintHeader(writer, label, entries); for (void** entry = entries; Count(entry) != 0; entry += 3 + Depth(entry)) { PrintStackEntry(writer, entry); } delete[] entries; DumpAddressMap(writer); } void MallocExtension::GetHeapGrowthStacks(MallocExtensionWriter* writer) { void** entries = ReadHeapGrowthStackTraces(); if (entries == NULL) { const char* const kErrorMsg = "This malloc implementation does not support " "ReadHeapGrowthStackTraces().\n" "As of 2005/09/27, only tcmalloc supports this, and you\n" "are probably running a binary that does not use tcmalloc.\n"; writer->append(kErrorMsg, strlen(kErrorMsg)); return; } // Do not canonicalize the stack entries, so that we get a // time-ordered list of stack traces, which may be useful if the // client wants to focus on the latest stack traces. PrintHeader(writer, "growth", entries); for (void** entry = entries; Count(entry) != 0; entry += 3 + Depth(entry)) { PrintStackEntry(writer, entry); } delete[] entries; DumpAddressMap(writer); } void MallocExtension::Ranges(void* arg, RangeFunction func) { // No callbacks by default } // These are C shims that work on the current instance. #define C_SHIM(fn, retval, paramlist, arglist) \ extern "C" PERFTOOLS_DLL_DECL retval MallocExtension_##fn paramlist { \ return MallocExtension::instance()->fn arglist; \ } C_SHIM(VerifyAllMemory, int, (void), ()); C_SHIM(VerifyNewMemory, int, (const void* p), (p)); C_SHIM(VerifyArrayNewMemory, int, (const void* p), (p)); C_SHIM(VerifyMallocMemory, int, (const void* p), (p)); C_SHIM(MallocMemoryStats, int, (int* blocks, size_t* total, int histogram[kMallocHistogramSize]), (blocks, total, histogram)); C_SHIM(GetStats, void, (char* buffer, int buffer_length), (buffer, buffer_length)); C_SHIM(GetNumericProperty, int, (const char* property, size_t* value), (property, value)); C_SHIM(SetNumericProperty, int, (const char* property, size_t value), (property, value)); C_SHIM(MarkThreadIdle, void, (void), ()); C_SHIM(MarkThreadBusy, void, (void), ()); C_SHIM(ReleaseFreeMemory, void, (void), ()); C_SHIM(ReleaseToSystem, void, (size_t num_bytes), (num_bytes)); C_SHIM(GetEstimatedAllocatedSize, size_t, (size_t size), (size)); C_SHIM(GetAllocatedSize, size_t, (const void* p), (p)); C_SHIM(GetThreadCacheSize, size_t, (void), ()); C_SHIM(MarkThreadTemporarilyIdle, void, (void), ()); // Can't use the shim here because of the need to translate the enums. extern "C" MallocExtension_Ownership MallocExtension_GetOwnership(const void* p) { return static_cast<MallocExtension_Ownership>( MallocExtension::instance()->GetOwnership(p)); }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/malloc_hook_mmap_freebsd.h
.h
4,992
136
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Override mmap/munmap/mremap/sbrk to provide support for calling the // related hooks (in addition, of course, to doing what these // functions normally do). #ifndef __FreeBSD__ # error Should only be including malloc_hook_mmap_freebsd.h on FreeBSD systems. #endif #include <unistd.h> #include <sys/syscall.h> #include <sys/mman.h> #include <errno.h> #include <dlfcn.h> // Make sure mmap doesn't get #define'd away by <sys/mman.h> #undef mmap // According to the FreeBSD documentation, use syscall if you do not // need 64-bit alignment otherwise use __syscall. Indeed, syscall // doesn't work correctly in most situations on 64-bit. It's return // type is 'int' so for things like SYS_mmap, it actually truncates // the returned address to 32-bits. #if defined(__amd64__) || defined(__x86_64__) # define MALLOC_HOOK_SYSCALL __syscall #else # define MALLOC_HOOK_SYSCALL syscall #endif extern "C" { void* mmap(void *start, size_t length,int prot, int flags, int fd, off_t offset) __THROW ATTRIBUTE_SECTION(malloc_hook); int munmap(void* start, size_t length) __THROW ATTRIBUTE_SECTION(malloc_hook); void* sbrk(intptr_t increment) __THROW ATTRIBUTE_SECTION(malloc_hook); } static inline void* do_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset) __THROW { return (void *)MALLOC_HOOK_SYSCALL(SYS_mmap, start, length, prot, flags, fd, offset); } static inline void* do_sbrk(intptr_t increment) { static void *(*libc_sbrk)(intptr_t); if (libc_sbrk == NULL) libc_sbrk = (void *(*)(intptr_t))dlsym(RTLD_NEXT, "sbrk"); return libc_sbrk(increment); } extern "C" void* mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset) __THROW { MallocHook::InvokePreMmapHook(start, length, prot, flags, fd, offset); void *result; if (!MallocHook::InvokeMmapReplacement( start, length, prot, flags, fd, offset, &result)) { result = do_mmap(start, length, prot, flags, fd, static_cast<size_t>(offset)); // avoid sign extension } MallocHook::InvokeMmapHook(result, start, length, prot, flags, fd, offset); return result; } extern "C" int munmap(void* start, size_t length) __THROW { MallocHook::InvokeMunmapHook(start, length); int result; if (!MallocHook::InvokeMunmapReplacement(start, length, &result)) { result = MALLOC_HOOK_SYSCALL(SYS_munmap, start, length); } return result; } extern "C" void* sbrk(intptr_t increment) __THROW { MallocHook::InvokePreSbrkHook(increment); void *result = do_sbrk(increment); MallocHook::InvokeSbrkHook(result, increment); return result; } /*static*/void* MallocHook::UnhookedMMap(void *start, size_t length, int prot, int flags, int fd, off_t offset) { void* result; if (!MallocHook::InvokeMmapReplacement( start, length, prot, flags, fd, offset, &result)) { result = do_mmap(start, length, prot, flags, fd, offset); } return result; } /*static*/int MallocHook::UnhookedMUnmap(void *start, size_t length) { int result; if (!MallocHook::InvokeMunmapReplacement(start, length, &result)) { result = MALLOC_HOOK_SYSCALL(SYS_munmap, start, length); } return result; } #undef MALLOC_HOOK_SYSCALL
Unknown
3D
mcellteam/mcell
libs/gperftools/src/maybe_threads.cc
.cc
6,189
178
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Paul Menage <opensource@google.com> // // Some wrappers for pthread functions so that we can be LD_PRELOADed // against non-pthreads apps. // // This module will behave very strangely if some pthreads functions // exist and others don't. #include "config.h" #include <assert.h> #include <string.h> // for memcmp #include <stdio.h> // for __isthreaded on FreeBSD // We don't actually need strings. But including this header seems to // stop the compiler trying to short-circuit our pthreads existence // tests and claiming that the address of a function is always // non-zero. I have no idea why ... #include <string> #include "maybe_threads.h" #include "base/basictypes.h" #include "base/logging.h" // __THROW is defined in glibc systems. It means, counter-intuitively, // "This function will never throw an exception." It's an optional // optimization tool, but we may need to use it to match glibc prototypes. #ifndef __THROW // I guess we're not on a glibc system # define __THROW // __THROW is just an optimization, so ok to make it "" #endif // These are the methods we're going to conditionally include. extern "C" { int pthread_key_create (pthread_key_t*, void (*)(void*)) __THROW ATTRIBUTE_WEAK; int pthread_key_delete (pthread_key_t) __THROW ATTRIBUTE_WEAK; void *pthread_getspecific(pthread_key_t) __THROW ATTRIBUTE_WEAK; int pthread_setspecific(pthread_key_t, const void*) __THROW ATTRIBUTE_WEAK; int pthread_once(pthread_once_t *, void (*)(void)) ATTRIBUTE_WEAK; #ifdef HAVE_FORK int pthread_atfork(void (*__prepare) (void), void (*__parent) (void), void (*__child) (void)) __THROW ATTRIBUTE_WEAK; #endif } #define MAX_PERTHREAD_VALS 16 static void *perftools_pthread_specific_vals[MAX_PERTHREAD_VALS]; static int next_key; // NOTE: it's similar to bitcast defined in basic_types.h with // exception of ignoring sizes mismatch template <typename T1, typename T2> static T2 memcpy_cast(const T1 &input) { T2 output; size_t s = sizeof(input); if (sizeof(output) < s) { s = sizeof(output); } memcpy(&output, &input, s); return output; } int perftools_pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)) { if (pthread_key_create) { return pthread_key_create(key, destr_function); } else { assert(next_key < MAX_PERTHREAD_VALS); *key = memcpy_cast<int, pthread_key_t>(next_key++); return 0; } } int perftools_pthread_key_delete(pthread_key_t key) { if (pthread_key_delete) { return pthread_key_delete(key); } else { return 0; } } void *perftools_pthread_getspecific(pthread_key_t key) { if (pthread_getspecific) { return pthread_getspecific(key); } else { return perftools_pthread_specific_vals[memcpy_cast<pthread_key_t, int>(key)]; } } int perftools_pthread_setspecific(pthread_key_t key, void *val) { if (pthread_setspecific) { return pthread_setspecific(key, val); } else { perftools_pthread_specific_vals[memcpy_cast<pthread_key_t, int>(key)] = val; return 0; } } static pthread_once_t pthread_once_init = PTHREAD_ONCE_INIT; int perftools_pthread_once(pthread_once_t *ctl, void (*init_routine) (void)) { #ifdef __FreeBSD__ // On __FreeBSD__, calling pthread_once on a system that is not // linked with -pthread is silently a noop. :-( Luckily, we have a // workaround: FreeBSD exposes __isthreaded in <stdio.h>, which is // set to 1 when the first thread is spawned. So on those systems, // we can use our own separate pthreads-once mechanism, which is // used until __isthreaded is 1 (which will never be true if the app // is not linked with -pthread). static bool pthread_once_ran_before_threads = false; if (pthread_once_ran_before_threads) { return 0; } if (!__isthreaded) { init_routine(); pthread_once_ran_before_threads = true; return 0; } #endif if (pthread_once) { return pthread_once(ctl, init_routine); } else { if (memcmp(ctl, &pthread_once_init, sizeof(*ctl)) == 0) { init_routine(); ++*(char*)(ctl); // make it so it's no longer equal to init } return 0; } } #ifdef HAVE_FORK void perftools_pthread_atfork(void (*before)(), void (*parent_after)(), void (*child_after)()) { if (pthread_atfork) { int rv = pthread_atfork(before, parent_after, child_after); CHECK(rv == 0); } } #endif
Unknown
3D
mcellteam/mcell
libs/gperftools/src/debugallocation.cc
.cc
58,647
1,584
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2000, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Urs Holzle <opensource@google.com> #include "config.h" #include <errno.h> #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif // We only need malloc.h for struct mallinfo. #ifdef HAVE_STRUCT_MALLINFO // Malloc can be in several places on older versions of OS X. # if defined(HAVE_MALLOC_H) # include <malloc.h> # elif defined(HAVE_MALLOC_MALLOC_H) # include <malloc/malloc.h> # elif defined(HAVE_SYS_MALLOC_H) # include <sys/malloc.h> # endif #endif #ifdef HAVE_PTHREAD #include <pthread.h> #endif #include <stdarg.h> #include <stdio.h> #include <string.h> #ifdef HAVE_MMAP #include <sys/mman.h> #endif #include <sys/stat.h> #include <sys/types.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <gperftools/malloc_extension.h> #include <gperftools/malloc_hook.h> #include <gperftools/stacktrace.h> #include "addressmap-inl.h" #include "base/commandlineflags.h" #include "base/googleinit.h" #include "base/logging.h" #include "base/spinlock.h" #include "malloc_hook-inl.h" #include "symbolize.h" // NOTE: due to #define below, tcmalloc.cc will omit tc_XXX // definitions. So that debug implementations can be defined // instead. We're going to use do_malloc, do_free and other do_XXX // functions that are defined in tcmalloc.cc for actual memory // management #define TCMALLOC_USING_DEBUGALLOCATION #include "tcmalloc.cc" // __THROW is defined in glibc systems. It means, counter-intuitively, // "This function will never throw an exception." It's an optional // optimization tool, but we may need to use it to match glibc prototypes. #ifndef __THROW // I guess we're not on a glibc system # define __THROW // __THROW is just an optimization, so ok to make it "" #endif // On systems (like freebsd) that don't define MAP_ANONYMOUS, use the old // form of the name instead. #ifndef MAP_ANONYMOUS # define MAP_ANONYMOUS MAP_ANON #endif // ========================================================================= // DEFINE_bool(malloctrace, EnvToBool("TCMALLOC_TRACE", false), "Enables memory (de)allocation tracing to /tmp/google.alloc."); #ifdef HAVE_MMAP DEFINE_bool(malloc_page_fence, EnvToBool("TCMALLOC_PAGE_FENCE", false), "Enables putting of memory allocations at page boundaries " "with a guard page following the allocation (to catch buffer " "overruns right when they happen)."); DEFINE_bool(malloc_page_fence_never_reclaim, EnvToBool("TCMALLOC_PAGE_FENCE_NEVER_RECLAIM", false), "Enables making the virtual address space inaccessible " "upon a deallocation instead of returning it and reusing later."); #else DEFINE_bool(malloc_page_fence, false, "Not usable (requires mmap)"); DEFINE_bool(malloc_page_fence_never_reclaim, false, "Not usable (required mmap)"); #endif DEFINE_bool(malloc_reclaim_memory, EnvToBool("TCMALLOC_RECLAIM_MEMORY", true), "If set to false, we never return memory to malloc " "when an object is deallocated. This ensures that all " "heap object addresses are unique."); DEFINE_int32(max_free_queue_size, EnvToInt("TCMALLOC_MAX_FREE_QUEUE_SIZE", 10*1024*1024), "If greater than 0, keep freed blocks in a queue instead of " "releasing them to the allocator immediately. Release them when " "the total size of all blocks in the queue would otherwise exceed " "this limit."); DEFINE_bool(symbolize_stacktrace, EnvToBool("TCMALLOC_SYMBOLIZE_STACKTRACE", true), "Symbolize the stack trace when provided (on some error exits)"); // If we are LD_PRELOAD-ed against a non-pthreads app, then // pthread_once won't be defined. We declare it here, for that // case (with weak linkage) which will cause the non-definition to // resolve to NULL. We can then check for NULL or not in Instance. extern "C" int pthread_once(pthread_once_t *, void (*)(void)) ATTRIBUTE_WEAK; // ========================================================================= // // A safe version of printf() that does not do any allocation and // uses very little stack space. static void TracePrintf(int fd, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))); // Round "value" up to next "alignment" boundary. // Requires that "alignment" be a power of two. static intptr_t RoundUp(intptr_t value, intptr_t alignment) { return (value + alignment - 1) & ~(alignment - 1); } // ========================================================================= // class MallocBlock; // A circular buffer to hold freed blocks of memory. MallocBlock::Deallocate // (below) pushes blocks into this queue instead of returning them to the // underlying allocator immediately. See MallocBlock::Deallocate for more // information. // // We can't use an STL class for this because we need to be careful not to // perform any heap de-allocations in any of the code in this class, since the // code in MallocBlock::Deallocate is not re-entrant. template <typename QueueEntry> class FreeQueue { public: FreeQueue() : q_front_(0), q_back_(0) {} bool Full() { return (q_front_ + 1) % kFreeQueueSize == q_back_; } void Push(const QueueEntry& block) { q_[q_front_] = block; q_front_ = (q_front_ + 1) % kFreeQueueSize; } QueueEntry Pop() { RAW_CHECK(q_back_ != q_front_, "Queue is empty"); const QueueEntry& ret = q_[q_back_]; q_back_ = (q_back_ + 1) % kFreeQueueSize; return ret; } size_t size() const { return (q_front_ - q_back_ + kFreeQueueSize) % kFreeQueueSize; } private: // Maximum number of blocks kept in the free queue before being freed. static const int kFreeQueueSize = 1024; QueueEntry q_[kFreeQueueSize]; int q_front_; int q_back_; }; struct MallocBlockQueueEntry { MallocBlockQueueEntry() : block(NULL), size(0), num_deleter_pcs(0), deleter_threadid(0) {} MallocBlockQueueEntry(MallocBlock* b, size_t s) : block(b), size(s) { if (FLAGS_max_free_queue_size != 0 && b != NULL) { // Adjust the number of frames to skip (4) if you change the // location of this call. num_deleter_pcs = MallocHook::GetCallerStackTrace( deleter_pcs, sizeof(deleter_pcs) / sizeof(deleter_pcs[0]), 4); deleter_threadid = pthread_self(); } else { num_deleter_pcs = 0; // Zero is an illegal pthread id by my reading of the pthread // implementation: deleter_threadid = 0; } } MallocBlock* block; size_t size; // When deleted and put in the free queue, we (flag-controlled) // record the stack so that if corruption is later found, we can // print the deleter's stack. (These three vars add 144 bytes of // overhead under the LP64 data model.) void* deleter_pcs[16]; int num_deleter_pcs; pthread_t deleter_threadid; }; class MallocBlock { public: // allocation type constants // Different allocation types we distinguish. // Note: The lower 4 bits are not random: we index kAllocName array // by these values masked with kAllocTypeMask; // the rest are "random" magic bits to help catch memory corruption. static const int kMallocType = 0xEFCDAB90; static const int kNewType = 0xFEBADC81; static const int kArrayNewType = 0xBCEADF72; private: // constants // A mask used on alloc types above to get to 0, 1, 2 static const int kAllocTypeMask = 0x3; // An additional bit to set in AllocType constants // to mark now deallocated regions. static const int kDeallocatedTypeBit = 0x4; // For better memory debugging, we initialize all storage to known // values, and overwrite the storage when it's deallocated: // Byte that fills uninitialized storage. static const int kMagicUninitializedByte = 0xAB; // Byte that fills deallocated storage. // NOTE: tcmalloc.cc depends on the value of kMagicDeletedByte // to work around a bug in the pthread library. static const int kMagicDeletedByte = 0xCD; // A size_t (type of alloc_type_ below) in a deallocated storage // filled with kMagicDeletedByte. static const size_t kMagicDeletedSizeT = 0xCDCDCDCD | (((size_t)0xCDCDCDCD << 16) << 16); // Initializer works for 32 and 64 bit size_ts; // "<< 16 << 16" is to fool gcc from issuing a warning // when size_ts are 32 bits. // NOTE: on Linux, you can enable malloc debugging support in libc by // setting the environment variable MALLOC_CHECK_ to 1 before you // start the program (see man malloc). // We use either do_malloc or mmap to make the actual allocation. In // order to remember which one of the two was used for any block, we store an // appropriate magic word next to the block. static const size_t kMagicMalloc = 0xDEADBEEF; static const size_t kMagicMMap = 0xABCDEFAB; // This array will be filled with 0xCD, for use with memcmp. static unsigned char kMagicDeletedBuffer[1024]; static pthread_once_t deleted_buffer_initialized_; static bool deleted_buffer_initialized_no_pthreads_; private: // data layout // The four fields size1_,offset_,magic1_,alloc_type_ // should together occupy a multiple of 16 bytes. (At the // moment, sizeof(size_t) == 4 or 8 depending on piii vs // k8, and 4 of those sum to 16 or 32 bytes). // This, combined with do_malloc's alignment guarantees, // ensures that SSE types can be stored into the returned // block, at &size2_. size_t size1_; size_t offset_; // normally 0 unless memaligned memory // see comments in memalign() and FromRawPointer(). size_t magic1_; size_t alloc_type_; // here comes the actual data (variable length) // ... // then come the size2_ and magic2_, or a full page of mprotect-ed memory // if the malloc_page_fence feature is enabled. size_t size2_; size_t magic2_; private: // static data and helpers // Allocation map: stores the allocation type for each allocated object, // or the type or'ed with kDeallocatedTypeBit // for each formerly allocated object. typedef AddressMap<int> AllocMap; static AllocMap* alloc_map_; // This protects alloc_map_ and consistent state of metadata // for each still-allocated object in it. // We use spin locks instead of pthread_mutex_t locks // to prevent crashes via calls to pthread_mutex_(un)lock // for the (de)allocations coming from pthreads initialization itself. static SpinLock alloc_map_lock_; // A queue of freed blocks. Instead of releasing blocks to the allocator // immediately, we put them in a queue, freeing them only when necessary // to keep the total size of all the freed blocks below the limit set by // FLAGS_max_free_queue_size. static FreeQueue<MallocBlockQueueEntry>* free_queue_; static size_t free_queue_size_; // total size of blocks in free_queue_ // protects free_queue_ and free_queue_size_ static SpinLock free_queue_lock_; // Names of allocation types (kMallocType, kNewType, kArrayNewType) static const char* const kAllocName[]; // Names of corresponding deallocation types static const char* const kDeallocName[]; static const char* AllocName(int type) { return kAllocName[type & kAllocTypeMask]; } static const char* DeallocName(int type) { return kDeallocName[type & kAllocTypeMask]; } private: // helper accessors bool IsMMapped() const { return kMagicMMap == magic1_; } bool IsValidMagicValue(size_t value) const { return kMagicMMap == value || kMagicMalloc == value; } static size_t real_malloced_size(size_t size) { return size + sizeof(MallocBlock); } /* * Here we assume size of page is kMinAlign aligned, * so if size is MALLOC_ALIGNMENT aligned too, then we could * guarantee return address is also kMinAlign aligned, because * mmap return address at nearby page boundary on Linux. */ static size_t real_mmapped_size(size_t size) { size_t tmp = size + MallocBlock::data_offset(); tmp = RoundUp(tmp, kMinAlign); return tmp; } size_t real_size() { return IsMMapped() ? real_mmapped_size(size1_) : real_malloced_size(size1_); } // NOTE: if the block is mmapped (that is, we're using the // malloc_page_fence option) then there's no size2 or magic2 // (instead, the guard page begins where size2 would be). size_t* size2_addr() { return (size_t*)((char*)&size2_ + size1_); } const size_t* size2_addr() const { return (const size_t*)((char*)&size2_ + size1_); } size_t* magic2_addr() { return (size_t*)(size2_addr() + 1); } const size_t* magic2_addr() const { return (const size_t*)(size2_addr() + 1); } private: // other helpers void Initialize(size_t size, int type) { RAW_CHECK(IsValidMagicValue(magic1_), ""); // record us as allocated in the map alloc_map_lock_.Lock(); if (!alloc_map_) { void* p = do_malloc(sizeof(AllocMap)); alloc_map_ = new(p) AllocMap(do_malloc, do_free); } alloc_map_->Insert(data_addr(), type); // initialize us size1_ = size; offset_ = 0; alloc_type_ = type; if (!IsMMapped()) { bit_store(magic2_addr(), &magic1_); bit_store(size2_addr(), &size); } alloc_map_lock_.Unlock(); memset(data_addr(), kMagicUninitializedByte, size); if (!IsMMapped()) { RAW_CHECK(memcmp(&size1_, size2_addr(), sizeof(size1_)) == 0, "should hold"); RAW_CHECK(memcmp(&magic1_, magic2_addr(), sizeof(magic1_)) == 0, "should hold"); } } size_t CheckAndClear(int type, size_t given_size) { alloc_map_lock_.Lock(); CheckLocked(type); if (!IsMMapped()) { RAW_CHECK(memcmp(&size1_, size2_addr(), sizeof(size1_)) == 0, "should hold"); } // record us as deallocated in the map alloc_map_->Insert(data_addr(), type | kDeallocatedTypeBit); alloc_map_lock_.Unlock(); // clear us const size_t size = real_size(); RAW_CHECK(!given_size || given_size == size1_, "right size must be passed to sized delete"); memset(this, kMagicDeletedByte, size); return size; } void CheckLocked(int type) const { int map_type = 0; const int* found_type = alloc_map_ != NULL ? alloc_map_->Find(data_addr()) : NULL; if (found_type == NULL) { RAW_LOG(FATAL, "memory allocation bug: object at %p " "has never been allocated", data_addr()); } else { map_type = *found_type; } if ((map_type & kDeallocatedTypeBit) != 0) { RAW_LOG(FATAL, "memory allocation bug: object at %p " "has been already deallocated (it was allocated with %s)", data_addr(), AllocName(map_type & ~kDeallocatedTypeBit)); } if (alloc_type_ == kMagicDeletedSizeT) { RAW_LOG(FATAL, "memory stomping bug: a word before object at %p " "has been corrupted; or else the object has been already " "deallocated and our memory map has been corrupted", data_addr()); } if (!IsValidMagicValue(magic1_)) { RAW_LOG(FATAL, "memory stomping bug: a word before object at %p " "has been corrupted; " "or else our memory map has been corrupted and this is a " "deallocation for not (currently) heap-allocated object", data_addr()); } if (!IsMMapped()) { if (memcmp(&size1_, size2_addr(), sizeof(size1_))) { RAW_LOG(FATAL, "memory stomping bug: a word after object at %p " "has been corrupted", data_addr()); } size_t addr; bit_store(&addr, magic2_addr()); if (!IsValidMagicValue(addr)) { RAW_LOG(FATAL, "memory stomping bug: a word after object at %p " "has been corrupted", data_addr()); } } if (alloc_type_ != type) { if ((alloc_type_ != MallocBlock::kMallocType) && (alloc_type_ != MallocBlock::kNewType) && (alloc_type_ != MallocBlock::kArrayNewType)) { RAW_LOG(FATAL, "memory stomping bug: a word before object at %p " "has been corrupted", data_addr()); } RAW_LOG(FATAL, "memory allocation/deallocation mismatch at %p: " "allocated with %s being deallocated with %s", data_addr(), AllocName(alloc_type_), DeallocName(type)); } if (alloc_type_ != map_type) { RAW_LOG(FATAL, "memory stomping bug: our memory map has been corrupted : " "allocation at %p made with %s " "is recorded in the map to be made with %s", data_addr(), AllocName(alloc_type_), AllocName(map_type)); } } public: // public accessors void* data_addr() { return (void*)&size2_; } const void* data_addr() const { return (const void*)&size2_; } static size_t data_offset() { return OFFSETOF_MEMBER(MallocBlock, size2_); } size_t data_size() const { return size1_; } void set_offset(int offset) { this->offset_ = offset; } public: // our main interface static MallocBlock* Allocate(size_t size, int type) { // Prevent an integer overflow / crash with large allocation sizes. // TODO - Note that for a e.g. 64-bit size_t, max_size_t may not actually // be the maximum value, depending on how the compiler treats ~0. The worst // practical effect is that allocations are limited to 4Gb or so, even if // the address space could take more. static size_t max_size_t = ~0; if (size > max_size_t - sizeof(MallocBlock)) { RAW_LOG(ERROR, "Massive size passed to malloc: %" PRIuS "", size); return NULL; } MallocBlock* b = NULL; const bool use_malloc_page_fence = FLAGS_malloc_page_fence; #ifdef HAVE_MMAP if (use_malloc_page_fence) { // Put the block towards the end of the page and make the next page // inaccessible. This will catch buffer overrun right when it happens. size_t sz = real_mmapped_size(size); int pagesize = getpagesize(); int num_pages = (sz + pagesize - 1) / pagesize + 1; char* p = (char*) mmap(NULL, num_pages * pagesize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (p == MAP_FAILED) { // If the allocation fails, abort rather than returning NULL to // malloc. This is because in most cases, the program will run out // of memory in this mode due to tremendous amount of wastage. There // is no point in propagating the error elsewhere. RAW_LOG(FATAL, "Out of memory: possibly due to page fence overhead: %s", strerror(errno)); } // Mark the page after the block inaccessible if (mprotect(p + (num_pages - 1) * pagesize, pagesize, PROT_NONE)) { RAW_LOG(FATAL, "Guard page setup failed: %s", strerror(errno)); } b = (MallocBlock*) (p + (num_pages - 1) * pagesize - sz); } else { b = (MallocBlock*) do_malloc(real_malloced_size(size)); } #else b = (MallocBlock*) do_malloc(real_malloced_size(size)); #endif // It would be nice to output a diagnostic on allocation failure // here, but logging (other than FATAL) requires allocating // memory, which could trigger a nasty recursion. Instead, preserve // malloc semantics and return NULL on failure. if (b != NULL) { b->magic1_ = use_malloc_page_fence ? kMagicMMap : kMagicMalloc; b->Initialize(size, type); } return b; } void Deallocate(int type, size_t given_size) { if (IsMMapped()) { // have to do this before CheckAndClear #ifdef HAVE_MMAP int size = CheckAndClear(type, given_size); int pagesize = getpagesize(); int num_pages = (size + pagesize - 1) / pagesize + 1; char* p = (char*) this; if (FLAGS_malloc_page_fence_never_reclaim || !FLAGS_malloc_reclaim_memory) { mprotect(p - (num_pages - 1) * pagesize + size, num_pages * pagesize, PROT_NONE); } else { munmap(p - (num_pages - 1) * pagesize + size, num_pages * pagesize); } #endif } else { const size_t size = CheckAndClear(type, given_size); if (FLAGS_malloc_reclaim_memory) { // Instead of freeing the block immediately, push it onto a queue of // recently freed blocks. Free only enough blocks to keep from // exceeding the capacity of the queue or causing the total amount of // un-released memory in the queue from exceeding // FLAGS_max_free_queue_size. ProcessFreeQueue(this, size, FLAGS_max_free_queue_size); } } } static size_t FreeQueueSize() { SpinLockHolder l(&free_queue_lock_); return free_queue_size_; } static void ProcessFreeQueue(MallocBlock* b, size_t size, int max_free_queue_size) { // MallocBlockQueueEntry are about 144 in size, so we can only // use a small array of them on the stack. MallocBlockQueueEntry entries[4]; int num_entries = 0; MallocBlockQueueEntry new_entry(b, size); free_queue_lock_.Lock(); if (free_queue_ == NULL) free_queue_ = new FreeQueue<MallocBlockQueueEntry>; RAW_CHECK(!free_queue_->Full(), "Free queue mustn't be full!"); if (b != NULL) { free_queue_size_ += size + sizeof(MallocBlockQueueEntry); free_queue_->Push(new_entry); } // Free blocks until the total size of unfreed blocks no longer exceeds // max_free_queue_size, and the free queue has at least one free // space in it. while (free_queue_size_ > max_free_queue_size || free_queue_->Full()) { RAW_CHECK(num_entries < arraysize(entries), "entries array overflow"); entries[num_entries] = free_queue_->Pop(); free_queue_size_ -= entries[num_entries].size + sizeof(MallocBlockQueueEntry); num_entries++; if (num_entries == arraysize(entries)) { // The queue will not be full at this point, so it is ok to // release the lock. The queue may still contain more than // max_free_queue_size, but this is not a strict invariant. free_queue_lock_.Unlock(); for (int i = 0; i < num_entries; i++) { CheckForDanglingWrites(entries[i]); do_free(entries[i].block); } num_entries = 0; free_queue_lock_.Lock(); } } free_queue_lock_.Unlock(); for (int i = 0; i < num_entries; i++) { CheckForDanglingWrites(entries[i]); do_free(entries[i].block); } } static void InitDeletedBuffer() { memset(kMagicDeletedBuffer, kMagicDeletedByte, sizeof(kMagicDeletedBuffer)); deleted_buffer_initialized_no_pthreads_ = true; } static void CheckForDanglingWrites(const MallocBlockQueueEntry& queue_entry) { // Initialize the buffer if necessary. if (pthread_once) pthread_once(&deleted_buffer_initialized_, &InitDeletedBuffer); if (!deleted_buffer_initialized_no_pthreads_) { // This will be the case on systems that don't link in pthreads, // including on FreeBSD where pthread_once has a non-zero address // (but doesn't do anything) even when pthreads isn't linked in. InitDeletedBuffer(); } const unsigned char* p = reinterpret_cast<unsigned char*>(queue_entry.block); static const size_t size_of_buffer = sizeof(kMagicDeletedBuffer); const size_t size = queue_entry.size; const size_t buffers = size / size_of_buffer; const size_t remainder = size % size_of_buffer; size_t buffer_idx; for (buffer_idx = 0; buffer_idx < buffers; ++buffer_idx) { CheckForCorruptedBuffer(queue_entry, buffer_idx, p, size_of_buffer); p += size_of_buffer; } CheckForCorruptedBuffer(queue_entry, buffer_idx, p, remainder); } static void CheckForCorruptedBuffer(const MallocBlockQueueEntry& queue_entry, size_t buffer_idx, const unsigned char* buffer, size_t size_of_buffer) { if (memcmp(buffer, kMagicDeletedBuffer, size_of_buffer) == 0) { return; } RAW_LOG(ERROR, "Found a corrupted memory buffer in MallocBlock (may be offset " "from user ptr): buffer index: %zd, buffer ptr: %p, size of " "buffer: %zd", buffer_idx, buffer, size_of_buffer); // The magic deleted buffer should only be 1024 bytes, but in case // this changes, let's put an upper limit on the number of debug // lines we'll output: if (size_of_buffer <= 1024) { for (int i = 0; i < size_of_buffer; ++i) { if (buffer[i] != kMagicDeletedByte) { RAW_LOG(ERROR, "Buffer byte %d is 0x%02x (should be 0x%02x).", i, buffer[i], kMagicDeletedByte); } } } else { RAW_LOG(ERROR, "Buffer too large to print corruption."); } const MallocBlock* b = queue_entry.block; const size_t size = queue_entry.size; if (queue_entry.num_deleter_pcs > 0) { TracePrintf(STDERR_FILENO, "Deleted by thread %p\n", reinterpret_cast<void*>( PRINTABLE_PTHREAD(queue_entry.deleter_threadid))); // We don't want to allocate or deallocate memory here, so we use // placement-new. It's ok that we don't destroy this, since we're // just going to error-exit below anyway. Union is for alignment. union { void* alignment; char buf[sizeof(SymbolTable)]; } tablebuf; SymbolTable* symbolization_table = new (tablebuf.buf) SymbolTable; for (int i = 0; i < queue_entry.num_deleter_pcs; i++) { // Symbolizes the previous address of pc because pc may be in the // next function. This may happen when the function ends with // a call to a function annotated noreturn (e.g. CHECK). char *pc = reinterpret_cast<char*>(queue_entry.deleter_pcs[i]); symbolization_table->Add(pc - 1); } if (FLAGS_symbolize_stacktrace) symbolization_table->Symbolize(); for (int i = 0; i < queue_entry.num_deleter_pcs; i++) { char *pc = reinterpret_cast<char*>(queue_entry.deleter_pcs[i]); TracePrintf(STDERR_FILENO, " @ %p %s\n", pc, symbolization_table->GetSymbol(pc - 1)); } } else { RAW_LOG(ERROR, "Skipping the printing of the deleter's stack! Its stack was " "not found; either the corruption occurred too early in " "execution to obtain a stack trace or --max_free_queue_size was " "set to 0."); } RAW_LOG(FATAL, "Memory was written to after being freed. MallocBlock: %p, user " "ptr: %p, size: %zd. If you can't find the source of the error, " "try using ASan (http://code.google.com/p/address-sanitizer/), " "Valgrind, or Purify, or study the " "output of the deleter's stack printed above.", b, b->data_addr(), size); } static MallocBlock* FromRawPointer(void* p) { const size_t data_offset = MallocBlock::data_offset(); // Find the header just before client's memory. MallocBlock *mb = reinterpret_cast<MallocBlock *>( reinterpret_cast<char *>(p) - data_offset); // If mb->alloc_type_ is kMagicDeletedSizeT, we're not an ok pointer. if (mb->alloc_type_ == kMagicDeletedSizeT) { RAW_LOG(FATAL, "memory allocation bug: object at %p has been already" " deallocated; or else a word before the object has been" " corrupted (memory stomping bug)", p); } // If mb->offset_ is zero (common case), mb is the real header. // If mb->offset_ is non-zero, this block was allocated by debug // memallign implementation, and mb->offset_ is the distance // backwards to the real header from mb, which is a fake header. if (mb->offset_ == 0) { return mb; } MallocBlock *main_block = reinterpret_cast<MallocBlock *>( reinterpret_cast<char *>(mb) - mb->offset_); if (main_block->offset_ != 0) { RAW_LOG(FATAL, "memory corruption bug: offset_ field is corrupted." " Need 0 but got %x", (unsigned)(main_block->offset_)); } if (main_block >= p) { RAW_LOG(FATAL, "memory corruption bug: offset_ field is corrupted." " Detected main_block address overflow: %x", (unsigned)(mb->offset_)); } if (main_block->size2_addr() < p) { RAW_LOG(FATAL, "memory corruption bug: offset_ field is corrupted." " It points below it's own main_block: %x", (unsigned)(mb->offset_)); } return main_block; } static const MallocBlock* FromRawPointer(const void* p) { // const-safe version: we just cast about return FromRawPointer(const_cast<void*>(p)); } void Check(int type) const { alloc_map_lock_.Lock(); CheckLocked(type); alloc_map_lock_.Unlock(); } static bool CheckEverything() { alloc_map_lock_.Lock(); if (alloc_map_ != NULL) alloc_map_->Iterate(CheckCallback, 0); alloc_map_lock_.Unlock(); return true; // if we get here, we're okay } static bool MemoryStats(int* blocks, size_t* total, int histogram[kMallocHistogramSize]) { memset(histogram, 0, kMallocHistogramSize * sizeof(int)); alloc_map_lock_.Lock(); stats_blocks_ = 0; stats_total_ = 0; stats_histogram_ = histogram; if (alloc_map_ != NULL) alloc_map_->Iterate(StatsCallback, 0); *blocks = stats_blocks_; *total = stats_total_; alloc_map_lock_.Unlock(); return true; } private: // helpers for CheckEverything and MemoryStats static void CheckCallback(const void* ptr, int* type, int dummy) { if ((*type & kDeallocatedTypeBit) == 0) { FromRawPointer(ptr)->CheckLocked(*type); } } // Accumulation variables for StatsCallback protected by alloc_map_lock_ static int stats_blocks_; static size_t stats_total_; static int* stats_histogram_; static void StatsCallback(const void* ptr, int* type, int dummy) { if ((*type & kDeallocatedTypeBit) == 0) { const MallocBlock* b = FromRawPointer(ptr); b->CheckLocked(*type); ++stats_blocks_; size_t mysize = b->size1_; int entry = 0; stats_total_ += mysize; while (mysize) { ++entry; mysize >>= 1; } RAW_CHECK(entry < kMallocHistogramSize, "kMallocHistogramSize should be at least as large as log2 " "of the maximum process memory size"); stats_histogram_[entry] += 1; } } }; void DanglingWriteChecker() { // Clear out the remaining free queue to check for dangling writes. MallocBlock::ProcessFreeQueue(NULL, 0, 0); } // ========================================================================= // const size_t MallocBlock::kMagicMalloc; const size_t MallocBlock::kMagicMMap; MallocBlock::AllocMap* MallocBlock::alloc_map_ = NULL; SpinLock MallocBlock::alloc_map_lock_(SpinLock::LINKER_INITIALIZED); FreeQueue<MallocBlockQueueEntry>* MallocBlock::free_queue_ = NULL; size_t MallocBlock::free_queue_size_ = 0; SpinLock MallocBlock::free_queue_lock_(SpinLock::LINKER_INITIALIZED); unsigned char MallocBlock::kMagicDeletedBuffer[1024]; pthread_once_t MallocBlock::deleted_buffer_initialized_ = PTHREAD_ONCE_INIT; bool MallocBlock::deleted_buffer_initialized_no_pthreads_ = false; const char* const MallocBlock::kAllocName[] = { "malloc", "new", "new []", NULL, }; const char* const MallocBlock::kDeallocName[] = { "free", "delete", "delete []", NULL, }; int MallocBlock::stats_blocks_; size_t MallocBlock::stats_total_; int* MallocBlock::stats_histogram_; // ========================================================================= // // The following cut-down version of printf() avoids // using stdio or ostreams. // This is to guarantee no recursive calls into // the allocator and to bound the stack space consumed. (The pthread // manager thread in linuxthreads has a very small stack, // so fprintf can't be called.) static void TracePrintf(int fd, const char *fmt, ...) { char buf[64]; int i = 0; va_list ap; va_start(ap, fmt); const char *p = fmt; char numbuf[25]; if (fd < 0) { va_end(ap); return; } numbuf[sizeof(numbuf)-1] = 0; while (*p != '\0') { // until end of format string char *s = &numbuf[sizeof(numbuf)-1]; if (p[0] == '%' && p[1] != 0) { // handle % formats int64 l = 0; unsigned long base = 0; if (*++p == 's') { // %s s = va_arg(ap, char *); } else if (*p == 'l' && p[1] == 'd') { // %ld l = va_arg(ap, long); base = 10; p++; } else if (*p == 'l' && p[1] == 'u') { // %lu l = va_arg(ap, unsigned long); base = 10; p++; } else if (*p == 'z' && p[1] == 'u') { // %zu l = va_arg(ap, size_t); base = 10; p++; } else if (*p == 'u') { // %u l = va_arg(ap, unsigned int); base = 10; } else if (*p == 'd') { // %d l = va_arg(ap, int); base = 10; } else if (*p == 'p') { // %p l = va_arg(ap, intptr_t); base = 16; } else { write(STDERR_FILENO, "Unimplemented TracePrintf format\n", 33); write(STDERR_FILENO, p, 2); write(STDERR_FILENO, "\n", 1); abort(); } p++; if (base != 0) { bool minus = (l < 0 && base == 10); uint64 ul = minus? -l : l; do { *--s = "0123456789abcdef"[ul % base]; ul /= base; } while (ul != 0); if (base == 16) { *--s = 'x'; *--s = '0'; } else if (minus) { *--s = '-'; } } } else { // handle normal characters *--s = *p++; } while (*s != 0) { if (i == sizeof(buf)) { write(fd, buf, i); i = 0; } buf[i++] = *s++; } } if (i != 0) { write(fd, buf, i); } va_end(ap); } // Return the file descriptor we're writing a log to static int TraceFd() { static int trace_fd = -1; if (trace_fd == -1) { // Open the trace file on the first call const char *val = getenv("TCMALLOC_TRACE_FILE"); bool fallback_to_stderr = false; if (!val) { val = "/tmp/google.alloc"; fallback_to_stderr = true; } trace_fd = open(val, O_CREAT|O_TRUNC|O_WRONLY, 0666); if (trace_fd == -1) { if (fallback_to_stderr) { trace_fd = 2; TracePrintf(trace_fd, "Can't open %s. Logging to stderr.\n", val); } else { TracePrintf(2, "Can't open %s. Logging disabled.\n", val); } } // Add a header to the log. TracePrintf(trace_fd, "Trace started: %lu\n", static_cast<unsigned long>(time(NULL))); TracePrintf(trace_fd, "func\tsize\tptr\tthread_id\tstack pcs for tools/symbolize\n"); } return trace_fd; } // Print the hex stack dump on a single line. PCs are separated by tabs. static void TraceStack(void) { void *pcs[16]; int n = GetStackTrace(pcs, sizeof(pcs)/sizeof(pcs[0]), 0); for (int i = 0; i != n; i++) { TracePrintf(TraceFd(), "\t%p", pcs[i]); } } // This protects MALLOC_TRACE, to make sure its info is atomically written. static SpinLock malloc_trace_lock(SpinLock::LINKER_INITIALIZED); #define MALLOC_TRACE(name, size, addr) \ do { \ if (FLAGS_malloctrace) { \ SpinLockHolder l(&malloc_trace_lock); \ TracePrintf(TraceFd(), "%s\t%" PRIuS "\t%p\t%" GPRIuPTHREAD, \ name, size, addr, PRINTABLE_PTHREAD(pthread_self())); \ TraceStack(); \ TracePrintf(TraceFd(), "\n"); \ } \ } while (0) // ========================================================================= // // Write the characters buf[0, ..., size-1] to // the malloc trace buffer. // This function is intended for debugging, // and is not declared in any header file. // You must insert a declaration of it by hand when you need // to use it. void __malloctrace_write(const char *buf, size_t size) { if (FLAGS_malloctrace) { write(TraceFd(), buf, size); } } // ========================================================================= // // General debug allocation/deallocation static inline void* DebugAllocate(size_t size, int type) { MallocBlock* ptr = MallocBlock::Allocate(size, type); if (ptr == NULL) return NULL; MALLOC_TRACE("malloc", size, ptr->data_addr()); return ptr->data_addr(); } static inline void DebugDeallocate(void* ptr, int type, size_t given_size) { MALLOC_TRACE("free", (ptr != 0 ? MallocBlock::FromRawPointer(ptr)->data_size() : 0), ptr); if (ptr) MallocBlock::FromRawPointer(ptr)->Deallocate(type, given_size); } // ========================================================================= // // The following functions may be called via MallocExtension::instance() // for memory verification and statistics. class DebugMallocImplementation : public TCMallocImplementation { public: virtual bool GetNumericProperty(const char* name, size_t* value) { bool result = TCMallocImplementation::GetNumericProperty(name, value); if (result && (strcmp(name, "generic.current_allocated_bytes") == 0)) { // Subtract bytes kept in the free queue size_t qsize = MallocBlock::FreeQueueSize(); if (*value >= qsize) { *value -= qsize; } } return result; } virtual bool VerifyNewMemory(const void* p) { if (p) MallocBlock::FromRawPointer(p)->Check(MallocBlock::kNewType); return true; } virtual bool VerifyArrayNewMemory(const void* p) { if (p) MallocBlock::FromRawPointer(p)->Check(MallocBlock::kArrayNewType); return true; } virtual bool VerifyMallocMemory(const void* p) { if (p) MallocBlock::FromRawPointer(p)->Check(MallocBlock::kMallocType); return true; } virtual bool VerifyAllMemory() { return MallocBlock::CheckEverything(); } virtual bool MallocMemoryStats(int* blocks, size_t* total, int histogram[kMallocHistogramSize]) { return MallocBlock::MemoryStats(blocks, total, histogram); } virtual size_t GetEstimatedAllocatedSize(size_t size) { return size; } virtual size_t GetAllocatedSize(const void* p) { if (p) { RAW_CHECK(GetOwnership(p) != MallocExtension::kNotOwned, "ptr not allocated by tcmalloc"); return MallocBlock::FromRawPointer(p)->data_size(); } return 0; } virtual MallocExtension::Ownership GetOwnership(const void* p) { if (!p) { // nobody owns NULL return MallocExtension::kNotOwned; } // FIXME: note that correct GetOwnership should not touch memory // that is not owned by tcmalloc. Main implementation is using // pagemap to discover if page in question is owned by us or // not. But pagemap only has marks for first and last page of // spans. Note that if p was returned out of our memalign with // big alignment, then it will point outside of marked pages. Also // note that FromRawPointer call below requires touching memory // before pointer in order to handle memalign-ed chunks // (offset_). This leaves us with two options: // // * do FromRawPointer first and have possibility of crashing if // we're given not owned pointer // // * return incorrect ownership for those large memalign chunks // // I've decided to choose later, which appears to happen rarer and // therefore is arguably a lesser evil MallocExtension::Ownership rv = TCMallocImplementation::GetOwnership(p); if (rv != MallocExtension::kOwned) { return rv; } const MallocBlock* mb = MallocBlock::FromRawPointer(p); return TCMallocImplementation::GetOwnership(mb); } virtual void GetFreeListSizes(vector<MallocExtension::FreeListInfo>* v) { static const char* kDebugFreeQueue = "debug.free_queue"; TCMallocImplementation::GetFreeListSizes(v); MallocExtension::FreeListInfo i; i.type = kDebugFreeQueue; i.min_object_size = 0; i.max_object_size = numeric_limits<size_t>::max(); i.total_bytes_free = MallocBlock::FreeQueueSize(); v->push_back(i); } }; static union { char chars[sizeof(DebugMallocImplementation)]; void *ptr; } debug_malloc_implementation_space; REGISTER_MODULE_INITIALIZER(debugallocation, { #if (__cplusplus >= 201103L) static_assert(alignof(decltype(debug_malloc_implementation_space)) >= alignof(DebugMallocImplementation), "DebugMallocImplementation is expected to need just word alignment"); #endif // Either we or valgrind will control memory management. We // register our extension if we're the winner. Otherwise let // Valgrind use its own malloc (so don't register our extension). if (!RunningOnValgrind()) { DebugMallocImplementation *impl = new (debug_malloc_implementation_space.chars) DebugMallocImplementation(); MallocExtension::Register(impl); } }); REGISTER_MODULE_DESTRUCTOR(debugallocation, { if (!RunningOnValgrind()) { // When the program exits, check all blocks still in the free // queue for corruption. DanglingWriteChecker(); } }); // ========================================================================= // struct debug_alloc_retry_data { size_t size; int new_type; }; static void *retry_debug_allocate(void *arg) { debug_alloc_retry_data *data = static_cast<debug_alloc_retry_data *>(arg); return DebugAllocate(data->size, data->new_type); } // This is mostly the same a cpp_alloc in tcmalloc.cc. // TODO(csilvers): change Allocate() above to call cpp_alloc, so we // don't have to reproduce the logic here. To make tc_new_mode work // properly, I think we'll need to separate out the logic of throwing // from the logic of calling the new-handler. inline void* debug_cpp_alloc(size_t size, int new_type, bool nothrow) { void* p = DebugAllocate(size, new_type); if (p != NULL) { return p; } struct debug_alloc_retry_data data; data.size = size; data.new_type = new_type; return handle_oom(retry_debug_allocate, &data, true, nothrow); } inline void* do_debug_malloc_or_debug_cpp_alloc(size_t size) { void* p = DebugAllocate(size, MallocBlock::kMallocType); if (p != NULL) { return p; } struct debug_alloc_retry_data data; data.size = size; data.new_type = MallocBlock::kMallocType; return handle_oom(retry_debug_allocate, &data, false, true); } // Exported routines // frame forcer and force_frame exist only to prevent tail calls to // DebugDeallocate to be actually implemented as tail calls. This is // important because stack trace capturing in MallocBlockQueueEntry // relies on google_malloc section being on stack and tc_XXX functions // are in that section. So they must not jump to DebugDeallocate but // have to do call. frame_forcer call at the end of such functions // prevents tail calls to DebugDeallocate. static int frame_forcer; static void force_frame() { int dummy = *(int volatile *)&frame_forcer; (void)dummy; } extern "C" PERFTOOLS_DLL_DECL void* tc_malloc(size_t size) PERFTOOLS_NOTHROW { if (ThreadCache::IsUseEmergencyMalloc()) { return tcmalloc::EmergencyMalloc(size); } void* ptr = do_debug_malloc_or_debug_cpp_alloc(size); MallocHook::InvokeNewHook(ptr, size); return ptr; } extern "C" PERFTOOLS_DLL_DECL void tc_free(void* ptr) PERFTOOLS_NOTHROW { if (tcmalloc::IsEmergencyPtr(ptr)) { return tcmalloc::EmergencyFree(ptr); } MallocHook::InvokeDeleteHook(ptr); DebugDeallocate(ptr, MallocBlock::kMallocType, 0); force_frame(); } extern "C" PERFTOOLS_DLL_DECL void tc_free_sized(void *ptr, size_t size) PERFTOOLS_NOTHROW { MallocHook::InvokeDeleteHook(ptr); DebugDeallocate(ptr, MallocBlock::kMallocType, size); force_frame(); } extern "C" PERFTOOLS_DLL_DECL void* tc_calloc(size_t count, size_t size) PERFTOOLS_NOTHROW { if (ThreadCache::IsUseEmergencyMalloc()) { return tcmalloc::EmergencyCalloc(count, size); } // Overflow check const size_t total_size = count * size; if (size != 0 && total_size / size != count) return NULL; void* block = do_debug_malloc_or_debug_cpp_alloc(total_size); MallocHook::InvokeNewHook(block, total_size); if (block) memset(block, 0, total_size); return block; } extern "C" PERFTOOLS_DLL_DECL void tc_cfree(void* ptr) PERFTOOLS_NOTHROW { if (tcmalloc::IsEmergencyPtr(ptr)) { return tcmalloc::EmergencyFree(ptr); } MallocHook::InvokeDeleteHook(ptr); DebugDeallocate(ptr, MallocBlock::kMallocType, 0); force_frame(); } extern "C" PERFTOOLS_DLL_DECL void* tc_realloc(void* ptr, size_t size) PERFTOOLS_NOTHROW { if (tcmalloc::IsEmergencyPtr(ptr)) { return tcmalloc::EmergencyRealloc(ptr, size); } if (ptr == NULL) { ptr = do_debug_malloc_or_debug_cpp_alloc(size); MallocHook::InvokeNewHook(ptr, size); return ptr; } if (size == 0) { MallocHook::InvokeDeleteHook(ptr); DebugDeallocate(ptr, MallocBlock::kMallocType, 0); return NULL; } MallocBlock* old = MallocBlock::FromRawPointer(ptr); old->Check(MallocBlock::kMallocType); MallocBlock* p = MallocBlock::Allocate(size, MallocBlock::kMallocType); // If realloc fails we are to leave the old block untouched and // return null if (p == NULL) return NULL; // if ptr was allocated via memalign, then old->data_size() is not // start of user data. So we must be careful to copy only user-data char *old_begin = (char *)old->data_addr(); char *old_end = old_begin + old->data_size(); ssize_t old_ssize = old_end - (char *)ptr; CHECK_CONDITION(old_ssize >= 0); size_t old_size = (size_t)old_ssize; CHECK_CONDITION(old_size <= old->data_size()); memcpy(p->data_addr(), ptr, (old_size < size) ? old_size : size); MallocHook::InvokeDeleteHook(ptr); MallocHook::InvokeNewHook(p->data_addr(), size); DebugDeallocate(ptr, MallocBlock::kMallocType, 0); MALLOC_TRACE("realloc", p->data_size(), p->data_addr()); return p->data_addr(); } extern "C" PERFTOOLS_DLL_DECL void* tc_new(size_t size) { void* ptr = debug_cpp_alloc(size, MallocBlock::kNewType, false); MallocHook::InvokeNewHook(ptr, size); if (ptr == NULL) { RAW_LOG(FATAL, "Unable to allocate %" PRIuS " bytes: new failed.", size); } return ptr; } extern "C" PERFTOOLS_DLL_DECL void* tc_new_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW { void* ptr = debug_cpp_alloc(size, MallocBlock::kNewType, true); MallocHook::InvokeNewHook(ptr, size); return ptr; } extern "C" PERFTOOLS_DLL_DECL void tc_delete(void* p) PERFTOOLS_NOTHROW { MallocHook::InvokeDeleteHook(p); DebugDeallocate(p, MallocBlock::kNewType, 0); force_frame(); } extern "C" PERFTOOLS_DLL_DECL void tc_delete_sized(void* p, size_t size) PERFTOOLS_NOTHROW { MallocHook::InvokeDeleteHook(p); DebugDeallocate(p, MallocBlock::kNewType, size); force_frame(); } // Some STL implementations explicitly invoke this. // It is completely equivalent to a normal delete (delete never throws). extern "C" PERFTOOLS_DLL_DECL void tc_delete_nothrow(void* p, const std::nothrow_t&) PERFTOOLS_NOTHROW { MallocHook::InvokeDeleteHook(p); DebugDeallocate(p, MallocBlock::kNewType, 0); force_frame(); } extern "C" PERFTOOLS_DLL_DECL void* tc_newarray(size_t size) { void* ptr = debug_cpp_alloc(size, MallocBlock::kArrayNewType, false); MallocHook::InvokeNewHook(ptr, size); if (ptr == NULL) { RAW_LOG(FATAL, "Unable to allocate %" PRIuS " bytes: new[] failed.", size); } return ptr; } extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW { void* ptr = debug_cpp_alloc(size, MallocBlock::kArrayNewType, true); MallocHook::InvokeNewHook(ptr, size); return ptr; } extern "C" PERFTOOLS_DLL_DECL void tc_deletearray(void* p) PERFTOOLS_NOTHROW { MallocHook::InvokeDeleteHook(p); DebugDeallocate(p, MallocBlock::kArrayNewType, 0); force_frame(); } extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_sized(void* p, size_t size) PERFTOOLS_NOTHROW { MallocHook::InvokeDeleteHook(p); DebugDeallocate(p, MallocBlock::kArrayNewType, size); force_frame(); } // Some STL implementations explicitly invoke this. // It is completely equivalent to a normal delete (delete never throws). extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_nothrow(void* p, const std::nothrow_t&) PERFTOOLS_NOTHROW { MallocHook::InvokeDeleteHook(p); DebugDeallocate(p, MallocBlock::kArrayNewType, 0); force_frame(); } // This is mostly the same as do_memalign in tcmalloc.cc. static void *do_debug_memalign(size_t alignment, size_t size, int type) { // Allocate >= size bytes aligned on "alignment" boundary // "alignment" is a power of two. void *p = 0; RAW_CHECK((alignment & (alignment-1)) == 0, "must be power of two"); const size_t data_offset = MallocBlock::data_offset(); // Allocate "alignment-1" extra bytes to ensure alignment is possible, and // a further data_offset bytes for an additional fake header. size_t extra_bytes = data_offset + alignment - 1; if (size + extra_bytes < size) return NULL; // Overflow p = DebugAllocate(size + extra_bytes, type); if (p != 0) { intptr_t orig_p = reinterpret_cast<intptr_t>(p); // Leave data_offset bytes for fake header, and round up to meet // alignment. p = reinterpret_cast<void *>(RoundUp(orig_p + data_offset, alignment)); // Create a fake header block with an offset_ that points back to the // real header. FromRawPointer uses this value. MallocBlock *fake_hdr = reinterpret_cast<MallocBlock *>( reinterpret_cast<char *>(p) - data_offset); // offset_ is distance between real and fake headers. // p is now end of fake header (beginning of client area), // and orig_p is the end of the real header, so offset_ // is their difference. // // Note that other fields of fake_hdr are initialized with // kMagicUninitializedByte fake_hdr->set_offset(reinterpret_cast<intptr_t>(p) - orig_p); } return p; } struct memalign_retry_data { size_t align; size_t size; int type; }; static void *retry_debug_memalign(void *arg) { memalign_retry_data *data = static_cast<memalign_retry_data *>(arg); return do_debug_memalign(data->align, data->size, data->type); } ATTRIBUTE_ALWAYS_INLINE inline void* do_debug_memalign_or_debug_cpp_memalign(size_t align, size_t size, int type, bool from_operator, bool nothrow) { void* p = do_debug_memalign(align, size, type); if (p != NULL) { return p; } struct memalign_retry_data data; data.align = align; data.size = size; data.type = type; return handle_oom(retry_debug_memalign, &data, from_operator, nothrow); } extern "C" PERFTOOLS_DLL_DECL void* tc_memalign(size_t align, size_t size) PERFTOOLS_NOTHROW { void *p = do_debug_memalign_or_debug_cpp_memalign(align, size, MallocBlock::kMallocType, false, true); MallocHook::InvokeNewHook(p, size); return p; } // Implementation taken from tcmalloc/tcmalloc.cc extern "C" PERFTOOLS_DLL_DECL int tc_posix_memalign(void** result_ptr, size_t align, size_t size) PERFTOOLS_NOTHROW { if (((align % sizeof(void*)) != 0) || ((align & (align - 1)) != 0) || (align == 0)) { return EINVAL; } void* result = do_debug_memalign_or_debug_cpp_memalign(align, size, MallocBlock::kMallocType, false, true); MallocHook::InvokeNewHook(result, size); if (result == NULL) { return ENOMEM; } else { *result_ptr = result; return 0; } } extern "C" PERFTOOLS_DLL_DECL void* tc_valloc(size_t size) PERFTOOLS_NOTHROW { // Allocate >= size bytes starting on a page boundary void *p = do_debug_memalign_or_debug_cpp_memalign(getpagesize(), size, MallocBlock::kMallocType, false, true); MallocHook::InvokeNewHook(p, size); return p; } extern "C" PERFTOOLS_DLL_DECL void* tc_pvalloc(size_t size) PERFTOOLS_NOTHROW { // Round size up to a multiple of pages // then allocate memory on a page boundary int pagesize = getpagesize(); size = RoundUp(size, pagesize); if (size == 0) { // pvalloc(0) should allocate one page, according to size = pagesize; // http://man.free4web.biz/man3/libmpatrol.3.html } void *p = do_debug_memalign_or_debug_cpp_memalign(pagesize, size, MallocBlock::kMallocType, false, true); MallocHook::InvokeNewHook(p, size); return p; } #if defined(ENABLE_ALIGNED_NEW_DELETE) extern "C" PERFTOOLS_DLL_DECL void* tc_new_aligned(size_t size, std::align_val_t align) { void* result = do_debug_memalign_or_debug_cpp_memalign(static_cast<size_t>(align), size, MallocBlock::kNewType, true, false); MallocHook::InvokeNewHook(result, size); return result; } extern "C" PERFTOOLS_DLL_DECL void* tc_new_aligned_nothrow(size_t size, std::align_val_t align, const std::nothrow_t&) PERFTOOLS_NOTHROW { void* result = do_debug_memalign_or_debug_cpp_memalign(static_cast<size_t>(align), size, MallocBlock::kNewType, true, true); MallocHook::InvokeNewHook(result, size); return result; } extern "C" PERFTOOLS_DLL_DECL void tc_delete_aligned(void* p, std::align_val_t) PERFTOOLS_NOTHROW { tc_delete(p); } extern "C" PERFTOOLS_DLL_DECL void tc_delete_sized_aligned(void* p, size_t size, std::align_val_t align) PERFTOOLS_NOTHROW { // Reproduce actual size calculation done by do_debug_memalign const size_t alignment = static_cast<size_t>(align); const size_t data_offset = MallocBlock::data_offset(); const size_t extra_bytes = data_offset + alignment - 1; tc_delete_sized(p, size + extra_bytes); } extern "C" PERFTOOLS_DLL_DECL void tc_delete_aligned_nothrow(void* p, std::align_val_t, const std::nothrow_t&) PERFTOOLS_NOTHROW { tc_delete(p); } extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_aligned(size_t size, std::align_val_t align) { void* result = do_debug_memalign_or_debug_cpp_memalign(static_cast<size_t>(align), size, MallocBlock::kArrayNewType, true, false); MallocHook::InvokeNewHook(result, size); return result; } extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_aligned_nothrow(size_t size, std::align_val_t align, const std::nothrow_t& nt) PERFTOOLS_NOTHROW { void* result = do_debug_memalign_or_debug_cpp_memalign(static_cast<size_t>(align), size, MallocBlock::kArrayNewType, true, true); MallocHook::InvokeNewHook(result, size); return result; } extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_aligned(void* p, std::align_val_t) PERFTOOLS_NOTHROW { tc_deletearray(p); } extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_sized_aligned(void* p, size_t size, std::align_val_t align) PERFTOOLS_NOTHROW { // Reproduce actual size calculation done by do_debug_memalign const size_t alignment = static_cast<size_t>(align); const size_t data_offset = MallocBlock::data_offset(); const size_t extra_bytes = data_offset + alignment - 1; tc_deletearray_sized(p, size + extra_bytes); } extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_aligned_nothrow(void* p, std::align_val_t, const std::nothrow_t&) PERFTOOLS_NOTHROW { tc_deletearray(p); } #endif // defined(ENABLE_ALIGNED_NEW_DELETE) // malloc_stats just falls through to the base implementation. extern "C" PERFTOOLS_DLL_DECL void tc_malloc_stats(void) PERFTOOLS_NOTHROW { do_malloc_stats(); } extern "C" PERFTOOLS_DLL_DECL int tc_mallopt(int cmd, int value) PERFTOOLS_NOTHROW { return do_mallopt(cmd, value); } #ifdef HAVE_STRUCT_MALLINFO extern "C" PERFTOOLS_DLL_DECL struct mallinfo tc_mallinfo(void) PERFTOOLS_NOTHROW { return do_mallinfo(); } #endif extern "C" PERFTOOLS_DLL_DECL size_t tc_malloc_size(void* ptr) PERFTOOLS_NOTHROW { return MallocExtension::instance()->GetAllocatedSize(ptr); } extern "C" PERFTOOLS_DLL_DECL void* tc_malloc_skip_new_handler(size_t size) PERFTOOLS_NOTHROW { void* result = DebugAllocate(size, MallocBlock::kMallocType); MallocHook::InvokeNewHook(result, size); return result; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/getpc.h
.h
8,071
196
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein // // This is an internal header file used by profiler.cc. It defines // the single (inline) function GetPC. GetPC is used in a signal // handler to figure out the instruction that was being executed when // the signal-handler was triggered. // // To get this, we use the ucontext_t argument to the signal-handler // callback, which holds the full context of what was going on when // the signal triggered. How to get from a ucontext_t to a Program // Counter is OS-dependent. #ifndef BASE_GETPC_H_ #define BASE_GETPC_H_ #include "config.h" // On many linux systems, we may need _GNU_SOURCE to get access to // the defined constants that define the register we want to see (eg // REG_EIP). Note this #define must come first! #define _GNU_SOURCE 1 // If #define _GNU_SOURCE causes problems, this might work instead. // It will cause problems for FreeBSD though!, because it turns off // the needed __BSD_VISIBLE. //#define _XOPEN_SOURCE 500 #include <string.h> // for memcmp #ifdef HAVE_ASM_PTRACE_H #include <asm/ptrace.h> #endif #if defined(HAVE_SYS_UCONTEXT_H) #include <sys/ucontext.h> #elif defined(HAVE_UCONTEXT_H) #include <ucontext.h> // for ucontext_t (and also mcontext_t) #elif defined(HAVE_CYGWIN_SIGNAL_H) #include <cygwin/signal.h> typedef ucontext ucontext_t; #endif // Take the example where function Foo() calls function Bar(). For // many architectures, Bar() is responsible for setting up and tearing // down its own stack frame. In that case, it's possible for the // interrupt to happen when execution is in Bar(), but the stack frame // is not properly set up (either before it's done being set up, or // after it's been torn down but before Bar() returns). In those // cases, the stack trace cannot see the caller function anymore. // // GetPC can try to identify this situation, on architectures where it // might occur, and unwind the current function call in that case to // avoid false edges in the profile graph (that is, edges that appear // to show a call skipping over a function). To do this, we hard-code // in the asm instructions we might see when setting up or tearing // down a stack frame. // // This is difficult to get right: the instructions depend on the // processor, the compiler ABI, and even the optimization level. This // is a best effort patch -- if we fail to detect such a situation, or // mess up the PC, nothing happens; the returned PC is not used for // any further processing. struct CallUnrollInfo { // Offset from (e)ip register where this instruction sequence // should be matched. Interpreted as bytes. Offset 0 is the next // instruction to execute. Be extra careful with negative offsets in // architectures of variable instruction length (like x86) - it is // not that easy as taking an offset to step one instruction back! int pc_offset; // The actual instruction bytes. Feel free to make it larger if you // need a longer sequence. unsigned char ins[16]; // How many bytes to match from ins array? int ins_size; // The offset from the stack pointer (e)sp where to look for the // call return address. Interpreted as bytes. int return_sp_offset; }; // The dereferences needed to get the PC from a struct ucontext were // determined at configure time, and stored in the macro // PC_FROM_UCONTEXT in config.h. The only thing we need to do here, // then, is to do the magic call-unrolling for systems that support it. // -- Special case 1: linux x86, for which we have CallUnrollInfo #if defined(__linux) && defined(__i386) && defined(__GNUC__) static const CallUnrollInfo callunrollinfo[] = { // Entry to a function: push %ebp; mov %esp,%ebp // Top-of-stack contains the caller IP. { 0, {0x55, 0x89, 0xe5}, 3, 0 }, // Entry to a function, second instruction: push %ebp; mov %esp,%ebp // Top-of-stack contains the old frame, caller IP is +4. { -1, {0x55, 0x89, 0xe5}, 3, 4 }, // Return from a function: RET. // Top-of-stack contains the caller IP. { 0, {0xc3}, 1, 0 } }; inline void* GetPC(const ucontext_t& signal_ucontext) { // See comment above struct CallUnrollInfo. Only try instruction // flow matching if both eip and esp looks reasonable. const int eip = signal_ucontext.uc_mcontext.gregs[REG_EIP]; const int esp = signal_ucontext.uc_mcontext.gregs[REG_ESP]; if ((eip & 0xffff0000) != 0 && (~eip & 0xffff0000) != 0 && (esp & 0xffff0000) != 0) { char* eip_char = reinterpret_cast<char*>(eip); for (int i = 0; i < sizeof(callunrollinfo)/sizeof(*callunrollinfo); ++i) { if (!memcmp(eip_char + callunrollinfo[i].pc_offset, callunrollinfo[i].ins, callunrollinfo[i].ins_size)) { // We have a match. void **retaddr = (void**)(esp + callunrollinfo[i].return_sp_offset); return *retaddr; } } } return (void*)eip; } // Special case #2: Windows, which has to do something totally different. #elif defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW32__) // If this is ever implemented, probably the way to do it is to have // profiler.cc use a high-precision timer via timeSetEvent: // http://msdn2.microsoft.com/en-us/library/ms712713.aspx // We'd use it in mode TIME_CALLBACK_FUNCTION/TIME_PERIODIC. // The callback function would be something like prof_handler, but // alas the arguments are different: no ucontext_t! I don't know // how we'd get the PC (using StackWalk64?) // http://msdn2.microsoft.com/en-us/library/ms680650.aspx #include "base/logging.h" // for RAW_LOG #ifndef HAVE_CYGWIN_SIGNAL_H typedef int ucontext_t; #endif inline void* GetPC(const struct ucontext_t& signal_ucontext) { RAW_LOG(ERROR, "GetPC is not yet implemented on Windows\n"); return NULL; } // Normal cases. If this doesn't compile, it's probably because // PC_FROM_UCONTEXT is the empty string. You need to figure out // the right value for your system, and add it to the list in // configure.ac (or set it manually in your config.h). #else inline void* GetPC(const ucontext_t& signal_ucontext) { #if defined(__s390__) && !defined(__s390x__) // Mask out the AMODE31 bit from the PC recorded in the context. return (void*)((unsigned long)signal_ucontext.PC_FROM_UCONTEXT & 0x7fffffffUL); #else return (void*)signal_ucontext.PC_FROM_UCONTEXT; // defined in config.h #endif } #endif #endif // BASE_GETPC_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stack_trace_table.h
.h
2,858
86
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Andrew Fikes // // Utility class for coalescing sampled stack traces. Not thread-safe. #ifndef TCMALLOC_STACK_TRACE_TABLE_H_ #define TCMALLOC_STACK_TRACE_TABLE_H_ #include <config.h> #ifdef HAVE_STDINT_H #include <stdint.h> // for uintptr_t #endif #include "common.h" #include "page_heap_allocator.h" namespace tcmalloc { class PERFTOOLS_DLL_DECL StackTraceTable { public: // REQUIRES: L < pageheap_lock StackTraceTable(); ~StackTraceTable(); // Adds stack trace "t" to table. // // REQUIRES: L >= pageheap_lock void AddTrace(const StackTrace& t); // Returns stack traces formatted per MallocExtension guidelines. // May return NULL on error. Clears state before returning. // // REQUIRES: L < pageheap_lock void** ReadStackTracesAndClear(); // Exposed for PageHeapAllocator // For testing int depth_total() const { return depth_total_; } int bucket_total() const { return bucket_total_; } private: struct Entry { Entry* next; StackTrace trace; }; bool error_; int depth_total_; int bucket_total_; Entry* head_; STLPageHeapAllocator<Entry, void> allocator_; }; } // namespace tcmalloc #endif // TCMALLOC_STACK_TRACE_TABLE_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/memory_region_map.h
.h
17,567
417
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- /* Copyright (c) 2006, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Maxim Lifantsev */ #ifndef BASE_MEMORY_REGION_MAP_H_ #define BASE_MEMORY_REGION_MAP_H_ #include <config.h> #ifdef HAVE_PTHREAD #include <pthread.h> #endif #include <stddef.h> #include <set> #include "base/stl_allocator.h" #include "base/spinlock.h" #include "base/thread_annotations.h" #include "base/low_level_alloc.h" #include "heap-profile-stats.h" // TODO(maxim): add a unittest: // execute a bunch of mmaps and compare memory map what strace logs // execute a bunch of mmap/munmup and compare memory map with // own accounting of what those mmaps generated // Thread-safe class to collect and query the map of all memory regions // in a process that have been created with mmap, munmap, mremap, sbrk. // For each memory region, we keep track of (and provide to users) // the stack trace that allocated that memory region. // The recorded stack trace depth is bounded by // a user-supplied max_stack_depth parameter of Init(). // After initialization with Init() // (which can happened even before global object constructor execution) // we collect the map by installing and monitoring MallocHook-s // to mmap, munmap, mremap, sbrk. // At any time one can query this map via provided interface. // For more details on the design of MemoryRegionMap // see the comment at the top of our .cc file. class MemoryRegionMap { private: // Max call stack recording depth supported by Init(). Set it to be // high enough for all our clients. Note: we do not define storage // for this (doing that requires special handling in windows), so // don't take the address of it! static const int kMaxStackDepth = 32; // Size of the hash table of buckets. A structure of the bucket table is // described in heap-profile-stats.h. static const int kHashTableSize = 179999; public: // interface ================================================================ // Every client of MemoryRegionMap must call Init() before first use, // and Shutdown() after last use. This allows us to reference count // this (singleton) class properly. MemoryRegionMap assumes it's the // only client of MallocHooks, so a client can only register other // MallocHooks after calling Init() and must unregister them before // calling Shutdown(). // Initialize this module to record memory allocation stack traces. // Stack traces that have more than "max_stack_depth" frames // are automatically shrunk to "max_stack_depth" when they are recorded. // Init() can be called more than once w/o harm, largest max_stack_depth // will be the effective one. // When "use_buckets" is true, then counts of mmap and munmap sizes will be // recorded with each stack trace. If Init() is called more than once, then // counting will be effective after any call contained "use_buckets" of true. // It will install mmap, munmap, mremap, sbrk hooks // and initialize arena_ and our hook and locks, hence one can use // MemoryRegionMap::Lock()/Unlock() to manage the locks. // Uses Lock/Unlock inside. static void Init(int max_stack_depth, bool use_buckets); // Try to shutdown this module undoing what Init() did. // Returns true iff could do full shutdown (or it was not attempted). // Full shutdown is attempted when the number of Shutdown() calls equals // the number of Init() calls. static bool Shutdown(); // Return true if MemoryRegionMap is initialized and recording, i.e. when // then number of Init() calls are more than the number of Shutdown() calls. static bool IsRecordingLocked(); // Locks to protect our internal data structures. // These also protect use of arena_ if our Init() has been done. // The lock is recursive. static void Lock() EXCLUSIVE_LOCK_FUNCTION(lock_); static void Unlock() UNLOCK_FUNCTION(lock_); // Returns true when the lock is held by this thread (for use in RAW_CHECK-s). static bool LockIsHeld(); // Locker object that acquires the MemoryRegionMap::Lock // for the duration of its lifetime (a C++ scope). class LockHolder { public: LockHolder() { Lock(); } ~LockHolder() { Unlock(); } private: DISALLOW_COPY_AND_ASSIGN(LockHolder); }; // A memory region that we know about through malloc_hook-s. // This is essentially an interface through which MemoryRegionMap // exports the collected data to its clients. Thread-compatible. struct Region { uintptr_t start_addr; // region start address uintptr_t end_addr; // region end address int call_stack_depth; // number of caller stack frames that we saved const void* call_stack[kMaxStackDepth]; // caller address stack array // filled to call_stack_depth size bool is_stack; // does this region contain a thread's stack: // a user of MemoryRegionMap supplies this info // Convenience accessor for call_stack[0], // i.e. (the program counter of) the immediate caller // of this region's allocation function, // but it also returns NULL when call_stack_depth is 0, // i.e whe we weren't able to get the call stack. // This usually happens in recursive calls, when the stack-unwinder // calls mmap() which in turn calls the stack-unwinder. uintptr_t caller() const { return reinterpret_cast<uintptr_t>(call_stack_depth >= 1 ? call_stack[0] : NULL); } // Return true iff this region overlaps region x. bool Overlaps(const Region& x) const { return start_addr < x.end_addr && end_addr > x.start_addr; } private: // helpers for MemoryRegionMap friend class MemoryRegionMap; // The ways we create Region-s: void Create(const void* start, size_t size) { start_addr = reinterpret_cast<uintptr_t>(start); end_addr = start_addr + size; is_stack = false; // not a stack till marked such call_stack_depth = 0; AssertIsConsistent(); } void set_call_stack_depth(int depth) { RAW_DCHECK(call_stack_depth == 0, ""); // only one such set is allowed call_stack_depth = depth; AssertIsConsistent(); } // The ways we modify Region-s: void set_is_stack() { is_stack = true; } void set_start_addr(uintptr_t addr) { start_addr = addr; AssertIsConsistent(); } void set_end_addr(uintptr_t addr) { end_addr = addr; AssertIsConsistent(); } // Verifies that *this contains consistent data, crashes if not the case. void AssertIsConsistent() const { RAW_DCHECK(start_addr < end_addr, ""); RAW_DCHECK(call_stack_depth >= 0 && call_stack_depth <= kMaxStackDepth, ""); } // Post-default construction helper to make a Region suitable // for searching in RegionSet regions_. void SetRegionSetKey(uintptr_t addr) { // make sure *this has no usable data: if (DEBUG_MODE) memset(this, 0xFF, sizeof(*this)); end_addr = addr; } // Note: call_stack[kMaxStackDepth] as a member lets us make Region // a simple self-contained struct with correctly behaving bit-vise copying. // This simplifies the code of this module but wastes some memory: // in most-often use case of this module (leak checking) // only one call_stack element out of kMaxStackDepth is actually needed. // Making the storage for call_stack variable-sized, // substantially complicates memory management for the Region-s: // as they need to be created and manipulated for some time // w/o any memory allocations, yet are also given out to the users. }; // Find the region that covers addr and write its data into *result if found, // in which case *result gets filled so that it stays fully functional // even when the underlying region gets removed from MemoryRegionMap. // Returns success. Uses Lock/Unlock inside. static bool FindRegion(uintptr_t addr, Region* result); // Find the region that contains stack_top, mark that region as // a stack region, and write its data into *result if found, // in which case *result gets filled so that it stays fully functional // even when the underlying region gets removed from MemoryRegionMap. // Returns success. Uses Lock/Unlock inside. static bool FindAndMarkStackRegion(uintptr_t stack_top, Region* result); // Iterate over the buckets which store mmap and munmap counts per stack // trace. It calls "callback" for each bucket, and passes "arg" to it. template<class Type> static void IterateBuckets(void (*callback)(const HeapProfileBucket*, Type), Type arg); // Get the bucket whose caller stack trace is "key". The stack trace is // used to a depth of "depth" at most. The requested bucket is created if // needed. // The bucket table is described in heap-profile-stats.h. static HeapProfileBucket* GetBucket(int depth, const void* const key[]); private: // our internal types ============================================== // Region comparator for sorting with STL struct RegionCmp { bool operator()(const Region& x, const Region& y) const { return x.end_addr < y.end_addr; } }; // We allocate STL objects in our own arena. struct MyAllocator { static void *Allocate(size_t n) { return LowLevelAlloc::AllocWithArena(n, arena_); } static void Free(const void *p, size_t /* n */) { LowLevelAlloc::Free(const_cast<void*>(p)); } }; // Set of the memory regions typedef std::set<Region, RegionCmp, STL_Allocator<Region, MyAllocator> > RegionSet; public: // more in-depth interface ========================================== // STL iterator with values of Region typedef RegionSet::const_iterator RegionIterator; // Return the begin/end iterators to all the regions. // These need Lock/Unlock protection around their whole usage (loop). // Even when the same thread causes modifications during such a loop // (which are permitted due to recursive locking) // the loop iterator will still be valid as long as its region // has not been deleted, but EndRegionLocked should be // re-evaluated whenever the set of regions has changed. static RegionIterator BeginRegionLocked(); static RegionIterator EndRegionLocked(); // Return the accumulated sizes of mapped and unmapped regions. static int64 MapSize() { return map_size_; } static int64 UnmapSize() { return unmap_size_; } // Effectively private type from our .cc ================================= // public to let us declare global objects: union RegionSetRep; private: // representation =========================================================== // Counter of clients of this module that have called Init(). static int client_count_; // Maximal number of caller stack frames to save (>= 0). static int max_stack_depth_; // Arena used for our allocations in regions_. static LowLevelAlloc::Arena* arena_; // Set of the mmap/sbrk/mremap-ed memory regions // To be accessed *only* when Lock() is held. // Hence we protect the non-recursive lock used inside of arena_ // with our recursive Lock(). This lets a user prevent deadlocks // when threads are stopped by TCMalloc_ListAllProcessThreads at random spots // simply by acquiring our recursive Lock() before that. static RegionSet* regions_; // Lock to protect regions_ and buckets_ variables and the data behind. static SpinLock lock_; // Lock to protect the recursive lock itself. static SpinLock owner_lock_; // Recursion count for the recursive lock. static int recursion_count_; // The thread id of the thread that's inside the recursive lock. static pthread_t lock_owner_tid_; // Total size of all mapped pages so far static int64 map_size_; // Total size of all unmapped pages so far static int64 unmap_size_; // Bucket hash table which is described in heap-profile-stats.h. static HeapProfileBucket** bucket_table_ GUARDED_BY(lock_); static int num_buckets_ GUARDED_BY(lock_); // The following members are local to MemoryRegionMap::GetBucket() // and MemoryRegionMap::HandleSavedBucketsLocked() // and are file-level to ensure that they are initialized at load time. // // These are used as temporary storage to break the infinite cycle of mmap // calling our hook which (sometimes) causes mmap. It must be a static // fixed-size array. The size 20 is just an expected value for safety. // The details are described in memory_region_map.cc. // Number of unprocessed bucket inserts. static int saved_buckets_count_ GUARDED_BY(lock_); // Unprocessed inserts (must be big enough to hold all mmaps that can be // caused by a GetBucket call). // Bucket has no constructor, so that c-tor execution does not interfere // with the any-time use of the static memory behind saved_buckets. static HeapProfileBucket saved_buckets_[20] GUARDED_BY(lock_); static const void* saved_buckets_keys_[20][kMaxStackDepth] GUARDED_BY(lock_); // helpers ================================================================== // Helper for FindRegion and FindAndMarkStackRegion: // returns the region covering 'addr' or NULL; assumes our lock_ is held. static const Region* DoFindRegionLocked(uintptr_t addr); // Verifying wrapper around regions_->insert(region) // To be called to do InsertRegionLocked's work only! inline static void DoInsertRegionLocked(const Region& region); // Handle regions saved by InsertRegionLocked into a tmp static array // by calling insert_func on them. inline static void HandleSavedRegionsLocked( void (*insert_func)(const Region& region)); // Restore buckets saved in a tmp static array by GetBucket to the bucket // table where all buckets eventually should be. static void RestoreSavedBucketsLocked(); // Initialize RegionSet regions_. inline static void InitRegionSetLocked(); // Wrapper around DoInsertRegionLocked // that handles the case of recursive allocator calls. inline static void InsertRegionLocked(const Region& region); // Record addition of a memory region at address "start" of size "size" // (called from our mmap/mremap/sbrk hooks). static void RecordRegionAddition(const void* start, size_t size); // Record deletion of a memory region at address "start" of size "size" // (called from our munmap/mremap/sbrk hooks). static void RecordRegionRemoval(const void* start, size_t size); // Record deletion of a memory region of size "size" in a bucket whose // caller stack trace is "key". The stack trace is used to a depth of // "depth" at most. static void RecordRegionRemovalInBucket(int depth, const void* const key[], size_t size); // Hooks for MallocHook static void MmapHook(const void* result, const void* start, size_t size, int prot, int flags, int fd, off_t offset); static void MunmapHook(const void* ptr, size_t size); static void MremapHook(const void* result, const void* old_addr, size_t old_size, size_t new_size, int flags, const void* new_addr); static void SbrkHook(const void* result, ptrdiff_t increment); // Log all memory regions; Useful for debugging only. // Assumes Lock() is held static void LogAllLocked(); DISALLOW_COPY_AND_ASSIGN(MemoryRegionMap); }; template <class Type> void MemoryRegionMap::IterateBuckets( void (*callback)(const HeapProfileBucket*, Type), Type callback_arg) { for (int index = 0; index < kHashTableSize; index++) { for (HeapProfileBucket* bucket = bucket_table_[index]; bucket != NULL; bucket = bucket->next) { callback(bucket, callback_arg); } } } #endif // BASE_MEMORY_REGION_MAP_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/memfs_malloc.cc
.cc
10,291
280
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Arun Sharma // // A tcmalloc system allocator that uses a memory based filesystem such as // tmpfs or hugetlbfs // // Since these only exist on linux, we only register this allocator there. #ifdef __linux #include <config.h> #include <errno.h> // for errno, EINVAL #include <inttypes.h> // for PRId64 #include <limits.h> // for PATH_MAX #include <stddef.h> // for size_t, NULL #ifdef HAVE_STDINT_H #include <stdint.h> // for int64_t, uintptr_t #endif #include <stdio.h> // for snprintf #include <stdlib.h> // for mkstemp #include <string.h> // for strerror #include <sys/mman.h> // for mmap, MAP_FAILED, etc #include <sys/statfs.h> // for fstatfs, statfs #include <unistd.h> // for ftruncate, off_t, unlink #include <new> // for operator new #include <string> #include <gperftools/malloc_extension.h> #include "base/basictypes.h" #include "base/googleinit.h" #include "base/sysinfo.h" #include "internal_logging.h" // TODO(sanjay): Move the code below into the tcmalloc namespace using tcmalloc::kLog; using tcmalloc::kCrash; using tcmalloc::Log; using std::string; DEFINE_string(memfs_malloc_path, EnvToString("TCMALLOC_MEMFS_MALLOC_PATH", ""), "Path where hugetlbfs or tmpfs is mounted. The caller is " "responsible for ensuring that the path is unique and does " "not conflict with another process"); DEFINE_int64(memfs_malloc_limit_mb, EnvToInt("TCMALLOC_MEMFS_LIMIT_MB", 0), "Limit total allocation size to the " "specified number of MiB. 0 == no limit."); DEFINE_bool(memfs_malloc_abort_on_fail, EnvToBool("TCMALLOC_MEMFS_ABORT_ON_FAIL", false), "abort() whenever memfs_malloc fails to satisfy an allocation " "for any reason."); DEFINE_bool(memfs_malloc_ignore_mmap_fail, EnvToBool("TCMALLOC_MEMFS_IGNORE_MMAP_FAIL", false), "Ignore failures from mmap"); DEFINE_bool(memfs_malloc_map_private, EnvToBool("TCMALLOC_MEMFS_MAP_PRIVATE", false), "Use MAP_PRIVATE with mmap"); DEFINE_bool(memfs_malloc_disable_fallback, EnvToBool("TCMALLOC_MEMFS_DISABLE_FALLBACK", false), "If we run out of hugepage memory don't fallback to default " "allocator."); // Hugetlbfs based allocator for tcmalloc class HugetlbSysAllocator: public SysAllocator { public: explicit HugetlbSysAllocator(SysAllocator* fallback) : failed_(true), // To disable allocator until Initialize() is called. big_page_size_(0), hugetlb_fd_(-1), hugetlb_base_(0), fallback_(fallback) { } void* Alloc(size_t size, size_t *actual_size, size_t alignment); bool Initialize(); bool failed_; // Whether failed to allocate memory. private: void* AllocInternal(size_t size, size_t *actual_size, size_t alignment); int64 big_page_size_; int hugetlb_fd_; // file descriptor for hugetlb off_t hugetlb_base_; SysAllocator* fallback_; // Default system allocator to fall back to. }; static union { char buf[sizeof(HugetlbSysAllocator)]; void *ptr; } hugetlb_space; // No locking needed here since we assume that tcmalloc calls // us with an internal lock held (see tcmalloc/system-alloc.cc). void* HugetlbSysAllocator::Alloc(size_t size, size_t *actual_size, size_t alignment) { if (!FLAGS_memfs_malloc_disable_fallback && failed_) { return fallback_->Alloc(size, actual_size, alignment); } // We don't respond to allocation requests smaller than big_page_size_ unless // the caller is ok to take more than they asked for. Used by MetaDataAlloc. if (!FLAGS_memfs_malloc_disable_fallback && actual_size == NULL && size < big_page_size_) { return fallback_->Alloc(size, actual_size, alignment); } // Enforce huge page alignment. Be careful to deal with overflow. size_t new_alignment = alignment; if (new_alignment < big_page_size_) new_alignment = big_page_size_; size_t aligned_size = ((size + new_alignment - 1) / new_alignment) * new_alignment; if (!FLAGS_memfs_malloc_disable_fallback && aligned_size < size) { return fallback_->Alloc(size, actual_size, alignment); } void* result = AllocInternal(aligned_size, actual_size, new_alignment); if (result != NULL) { return result; } else if (FLAGS_memfs_malloc_disable_fallback) { return NULL; } Log(kLog, __FILE__, __LINE__, "HugetlbSysAllocator: (failed, allocated)", failed_, hugetlb_base_); if (FLAGS_memfs_malloc_abort_on_fail) { Log(kCrash, __FILE__, __LINE__, "memfs_malloc_abort_on_fail is set"); } return fallback_->Alloc(size, actual_size, alignment); } void* HugetlbSysAllocator::AllocInternal(size_t size, size_t* actual_size, size_t alignment) { // Ask for extra memory if alignment > pagesize size_t extra = 0; if (alignment > big_page_size_) { extra = alignment - big_page_size_; } // Test if this allocation would put us over the limit. off_t limit = FLAGS_memfs_malloc_limit_mb*1024*1024; if (limit > 0 && hugetlb_base_ + size + extra > limit) { // Disable the allocator when there's less than one page left. if (limit - hugetlb_base_ < big_page_size_) { Log(kLog, __FILE__, __LINE__, "reached memfs_malloc_limit_mb"); failed_ = true; } else { Log(kLog, __FILE__, __LINE__, "alloc too large (size, bytes left)", size, limit-hugetlb_base_); } return NULL; } // This is not needed for hugetlbfs, but needed for tmpfs. Annoyingly // hugetlbfs returns EINVAL for ftruncate. int ret = ftruncate(hugetlb_fd_, hugetlb_base_ + size + extra); if (ret != 0 && errno != EINVAL) { Log(kLog, __FILE__, __LINE__, "ftruncate failed", strerror(errno)); failed_ = true; return NULL; } // Note: size + extra does not overflow since: // size + alignment < (1<<NBITS). // and extra <= alignment // therefore size + extra < (1<<NBITS) void *result; result = mmap(0, size + extra, PROT_WRITE|PROT_READ, FLAGS_memfs_malloc_map_private ? MAP_PRIVATE : MAP_SHARED, hugetlb_fd_, hugetlb_base_); if (result == reinterpret_cast<void*>(MAP_FAILED)) { if (!FLAGS_memfs_malloc_ignore_mmap_fail) { Log(kLog, __FILE__, __LINE__, "mmap failed (size, error)", size + extra, strerror(errno)); failed_ = true; } return NULL; } uintptr_t ptr = reinterpret_cast<uintptr_t>(result); // Adjust the return memory so it is aligned size_t adjust = 0; if ((ptr & (alignment - 1)) != 0) { adjust = alignment - (ptr & (alignment - 1)); } ptr += adjust; hugetlb_base_ += (size + extra); if (actual_size) { *actual_size = size + extra - adjust; } return reinterpret_cast<void*>(ptr); } bool HugetlbSysAllocator::Initialize() { char path[PATH_MAX]; const int pathlen = FLAGS_memfs_malloc_path.size(); if (pathlen + 8 > sizeof(path)) { Log(kCrash, __FILE__, __LINE__, "XX fatal: memfs_malloc_path too long"); return false; } memcpy(path, FLAGS_memfs_malloc_path.data(), pathlen); memcpy(path + pathlen, ".XXXXXX", 8); // Also copies terminating \0 int hugetlb_fd = mkstemp(path); if (hugetlb_fd == -1) { Log(kLog, __FILE__, __LINE__, "warning: unable to create memfs_malloc_path", path, strerror(errno)); return false; } // Cleanup memory on process exit if (unlink(path) == -1) { Log(kCrash, __FILE__, __LINE__, "fatal: error unlinking memfs_malloc_path", path, strerror(errno)); return false; } // Use fstatfs to figure out the default page size for memfs struct statfs sfs; if (fstatfs(hugetlb_fd, &sfs) == -1) { Log(kCrash, __FILE__, __LINE__, "fatal: error fstatfs of memfs_malloc_path", strerror(errno)); return false; } int64 page_size = sfs.f_bsize; hugetlb_fd_ = hugetlb_fd; big_page_size_ = page_size; failed_ = false; return true; } REGISTER_MODULE_INITIALIZER(memfs_malloc, { if (FLAGS_memfs_malloc_path.length()) { SysAllocator* alloc = MallocExtension::instance()->GetSystemAllocator(); HugetlbSysAllocator* hp = new (hugetlb_space.buf) HugetlbSysAllocator(alloc); if (hp->Initialize()) { MallocExtension::instance()->SetSystemAllocator(hp); } } }); #endif /* ifdef __linux */
Unknown
3D
mcellteam/mcell
libs/gperftools/src/maybe_emergency_malloc.h
.h
2,219
56
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2014, gperftools Contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MAYBE_EMERGENCY_MALLOC_H #define MAYBE_EMERGENCY_MALLOC_H #include "config.h" #ifdef ENABLE_EMERGENCY_MALLOC #include "emergency_malloc.h" #else namespace tcmalloc { static inline void *EmergencyMalloc(size_t size) {return NULL;} static inline void EmergencyFree(void *p) {} static inline void *EmergencyCalloc(size_t n, size_t elem_size) {return NULL;} static inline void *EmergencyRealloc(void *old_ptr, size_t new_size) {return NULL;} static inline bool IsEmergencyPtr(const void *_ptr) { return false; } } #endif // ENABLE_EMERGENCY_MALLOC #endif
Unknown
3D
mcellteam/mcell
libs/gperftools/src/profile-handler.cc
.cc
18,692
585
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // Nabeel Mian // // Implements management of profile timers and the corresponding signal handler. #include "config.h" #include "profile-handler.h" #if !(defined(__CYGWIN__) || defined(__CYGWIN32__)) #include <stdio.h> #include <errno.h> #include <sys/time.h> #include <list> #include <string> #if HAVE_LINUX_SIGEV_THREAD_ID // for timer_{create,settime} and associated typedefs & constants #include <time.h> // for sys_gettid #include "base/linux_syscall_support.h" // for perftools_pthread_key_create #include "maybe_threads.h" #endif #include "base/dynamic_annotations.h" #include "base/googleinit.h" #include "base/logging.h" #include "base/spinlock.h" #include "maybe_threads.h" using std::list; using std::string; // This structure is used by ProfileHandlerRegisterCallback and // ProfileHandlerUnregisterCallback as a handle to a registered callback. struct ProfileHandlerToken { // Sets the callback and associated arg. ProfileHandlerToken(ProfileHandlerCallback cb, void* cb_arg) : callback(cb), callback_arg(cb_arg) { } // Callback function to be invoked on receiving a profile timer interrupt. ProfileHandlerCallback callback; // Argument for the callback function. void* callback_arg; }; // Blocks a signal from being delivered to the current thread while the object // is alive. Unblocks it upon destruction. class ScopedSignalBlocker { public: ScopedSignalBlocker(int signo) { sigemptyset(&sig_set_); sigaddset(&sig_set_, signo); RAW_CHECK(sigprocmask(SIG_BLOCK, &sig_set_, NULL) == 0, "sigprocmask (block)"); } ~ScopedSignalBlocker() { RAW_CHECK(sigprocmask(SIG_UNBLOCK, &sig_set_, NULL) == 0, "sigprocmask (unblock)"); } private: sigset_t sig_set_; }; // This class manages profile timers and associated signal handler. This is a // a singleton. class ProfileHandler { public: // Registers the current thread with the profile handler. void RegisterThread(); // Registers a callback routine to receive profile timer ticks. The returned // token is to be used when unregistering this callback and must not be // deleted by the caller. ProfileHandlerToken* RegisterCallback(ProfileHandlerCallback callback, void* callback_arg); // Unregisters a previously registered callback. Expects the token returned // by the corresponding RegisterCallback routine. void UnregisterCallback(ProfileHandlerToken* token) NO_THREAD_SAFETY_ANALYSIS; // Unregisters all the callbacks and stops the timer(s). void Reset(); // Gets the current state of profile handler. void GetState(ProfileHandlerState* state); // Initializes and returns the ProfileHandler singleton. static ProfileHandler* Instance(); private: ProfileHandler(); ~ProfileHandler(); // Largest allowed frequency. static const int32 kMaxFrequency = 4000; // Default frequency. static const int32 kDefaultFrequency = 100; // ProfileHandler singleton. static ProfileHandler* instance_; // pthread_once_t for one time initialization of ProfileHandler singleton. static pthread_once_t once_; // Initializes the ProfileHandler singleton via GoogleOnceInit. static void Init(); // Timer state as configured previously. bool timer_running_; // The number of profiling signal interrupts received. int64 interrupts_ GUARDED_BY(signal_lock_); // Profiling signal interrupt frequency, read-only after construction. int32 frequency_; // ITIMER_PROF (which uses SIGPROF), or ITIMER_REAL (which uses SIGALRM). // Translated into an equivalent choice of clock if per_thread_timer_enabled_ // is true. int timer_type_; // Signal number for timer signal. int signal_number_; // Counts the number of callbacks registered. int32 callback_count_ GUARDED_BY(control_lock_); // Is profiling allowed at all? bool allowed_; // Must be false if HAVE_LINUX_SIGEV_THREAD_ID is not defined. bool per_thread_timer_enabled_; #ifdef HAVE_LINUX_SIGEV_THREAD_ID // this is used to destroy per-thread profiling timers on thread // termination pthread_key_t thread_timer_key; #endif // This lock serializes the registration of threads and protects the // callbacks_ list below. // Locking order: // In the context of a signal handler, acquire signal_lock_ to walk the // callback list. Otherwise, acquire control_lock_, disable the signal // handler and then acquire signal_lock_. SpinLock control_lock_ ACQUIRED_BEFORE(signal_lock_); SpinLock signal_lock_; // Holds the list of registered callbacks. We expect the list to be pretty // small. Currently, the cpu profiler (base/profiler) and thread module // (base/thread.h) are the only two components registering callbacks. // Following are the locking requirements for callbacks_: // For read-write access outside the SIGPROF handler: // - Acquire control_lock_ // - Disable SIGPROF handler. // - Acquire signal_lock_ // For read-only access in the context of SIGPROF handler // (Read-write access is *not allowed* in the SIGPROF handler) // - Acquire signal_lock_ // For read-only access outside SIGPROF handler: // - Acquire control_lock_ typedef list<ProfileHandlerToken*> CallbackList; typedef CallbackList::iterator CallbackIterator; CallbackList callbacks_ GUARDED_BY(signal_lock_); // Starts or stops the interval timer. // Will ignore any requests to enable or disable when // per_thread_timer_enabled_ is true. void UpdateTimer(bool enable) EXCLUSIVE_LOCKS_REQUIRED(signal_lock_); // Returns true if the handler is not being used by something else. // This checks the kernel's signal handler table. bool IsSignalHandlerAvailable(); // Signal handler. Iterates over and calls all the registered callbacks. static void SignalHandler(int sig, siginfo_t* sinfo, void* ucontext); DISALLOW_COPY_AND_ASSIGN(ProfileHandler); }; ProfileHandler* ProfileHandler::instance_ = NULL; pthread_once_t ProfileHandler::once_ = PTHREAD_ONCE_INIT; const int32 ProfileHandler::kMaxFrequency; const int32 ProfileHandler::kDefaultFrequency; // If we are LD_PRELOAD-ed against a non-pthreads app, then these functions // won't be defined. We declare them here, for that case (with weak linkage) // which will cause the non-definition to resolve to NULL. We can then check // for NULL or not in Instance. extern "C" { int pthread_once(pthread_once_t *, void (*)(void)) ATTRIBUTE_WEAK; int pthread_kill(pthread_t thread_id, int signo) ATTRIBUTE_WEAK; #if HAVE_LINUX_SIGEV_THREAD_ID int timer_create(clockid_t clockid, struct sigevent* evp, timer_t* timerid) ATTRIBUTE_WEAK; int timer_delete(timer_t timerid) ATTRIBUTE_WEAK; int timer_settime(timer_t timerid, int flags, const struct itimerspec* value, struct itimerspec* ovalue) ATTRIBUTE_WEAK; #endif } #if HAVE_LINUX_SIGEV_THREAD_ID struct timer_id_holder { timer_t timerid; timer_id_holder(timer_t _timerid) : timerid(_timerid) {} }; extern "C" { static void ThreadTimerDestructor(void *arg) { if (!arg) { return; } timer_id_holder *holder = static_cast<timer_id_holder *>(arg); timer_delete(holder->timerid); delete holder; } } static void CreateThreadTimerKey(pthread_key_t *pkey) { int rv = perftools_pthread_key_create(pkey, ThreadTimerDestructor); if (rv) { RAW_LOG(FATAL, "aborting due to pthread_key_create error: %s", strerror(rv)); } } static void StartLinuxThreadTimer(int timer_type, int signal_number, int32 frequency, pthread_key_t timer_key) { int rv; struct sigevent sevp; timer_t timerid; struct itimerspec its; memset(&sevp, 0, sizeof(sevp)); sevp.sigev_notify = SIGEV_THREAD_ID; sevp._sigev_un._tid = sys_gettid(); sevp.sigev_signo = signal_number; clockid_t clock = CLOCK_THREAD_CPUTIME_ID; if (timer_type == ITIMER_REAL) { clock = CLOCK_MONOTONIC; } rv = timer_create(clock, &sevp, &timerid); if (rv) { RAW_LOG(FATAL, "aborting due to timer_create error: %s", strerror(errno)); } timer_id_holder *holder = new timer_id_holder(timerid); rv = perftools_pthread_setspecific(timer_key, holder); if (rv) { RAW_LOG(FATAL, "aborting due to pthread_setspecific error: %s", strerror(rv)); } its.it_interval.tv_sec = 0; its.it_interval.tv_nsec = 1000000000 / frequency; its.it_value = its.it_interval; rv = timer_settime(timerid, 0, &its, 0); if (rv) { RAW_LOG(FATAL, "aborting due to timer_settime error: %s", strerror(errno)); } } #endif void ProfileHandler::Init() { instance_ = new ProfileHandler(); } ProfileHandler* ProfileHandler::Instance() { if (pthread_once) { pthread_once(&once_, Init); } if (instance_ == NULL) { // This will be true on systems that don't link in pthreads, // including on FreeBSD where pthread_once has a non-zero address // (but doesn't do anything) even when pthreads isn't linked in. Init(); assert(instance_ != NULL); } return instance_; } ProfileHandler::ProfileHandler() : timer_running_(false), interrupts_(0), callback_count_(0), allowed_(true), per_thread_timer_enabled_(false) { SpinLockHolder cl(&control_lock_); timer_type_ = (getenv("CPUPROFILE_REALTIME") ? ITIMER_REAL : ITIMER_PROF); signal_number_ = (timer_type_ == ITIMER_PROF ? SIGPROF : SIGALRM); // Get frequency of interrupts (if specified) char junk; const char* fr = getenv("CPUPROFILE_FREQUENCY"); if (fr != NULL && (sscanf(fr, "%u%c", &frequency_, &junk) == 1) && (frequency_ > 0)) { // Limit to kMaxFrequency frequency_ = (frequency_ > kMaxFrequency) ? kMaxFrequency : frequency_; } else { frequency_ = kDefaultFrequency; } if (!allowed_) { return; } #if HAVE_LINUX_SIGEV_THREAD_ID // Do this early because we might be overriding signal number. const char *per_thread = getenv("CPUPROFILE_PER_THREAD_TIMERS"); const char *signal_number = getenv("CPUPROFILE_TIMER_SIGNAL"); if (per_thread || signal_number) { if (timer_create && pthread_once) { CreateThreadTimerKey(&thread_timer_key); per_thread_timer_enabled_ = true; // Override signal number if requested. if (signal_number) { signal_number_ = strtol(signal_number, NULL, 0); } } else { RAW_LOG(INFO, "Ignoring CPUPROFILE_PER_THREAD_TIMERS and\n" " CPUPROFILE_TIMER_SIGNAL due to lack of timer_create().\n" " Preload or link to librt.so for this to work"); } } #endif // If something else is using the signal handler, // assume it has priority over us and stop. if (!IsSignalHandlerAvailable()) { RAW_LOG(INFO, "Disabling profiler because signal %d handler is already in use.", signal_number_); allowed_ = false; return; } // Install the signal handler. struct sigaction sa; sa.sa_sigaction = SignalHandler; sa.sa_flags = SA_RESTART | SA_SIGINFO; sigemptyset(&sa.sa_mask); RAW_CHECK(sigaction(signal_number_, &sa, NULL) == 0, "sigprof (enable)"); } ProfileHandler::~ProfileHandler() { Reset(); #ifdef HAVE_LINUX_SIGEV_THREAD_ID if (per_thread_timer_enabled_) { perftools_pthread_key_delete(thread_timer_key); } #endif } void ProfileHandler::RegisterThread() { SpinLockHolder cl(&control_lock_); if (!allowed_) { return; } // Record the thread identifier and start the timer if profiling is on. ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); #if HAVE_LINUX_SIGEV_THREAD_ID if (per_thread_timer_enabled_) { StartLinuxThreadTimer(timer_type_, signal_number_, frequency_, thread_timer_key); return; } #endif UpdateTimer(callback_count_ > 0); } ProfileHandlerToken* ProfileHandler::RegisterCallback( ProfileHandlerCallback callback, void* callback_arg) { ProfileHandlerToken* token = new ProfileHandlerToken(callback, callback_arg); SpinLockHolder cl(&control_lock_); { ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); callbacks_.push_back(token); ++callback_count_; UpdateTimer(true); } return token; } void ProfileHandler::UnregisterCallback(ProfileHandlerToken* token) { SpinLockHolder cl(&control_lock_); for (CallbackIterator it = callbacks_.begin(); it != callbacks_.end(); ++it) { if ((*it) == token) { RAW_CHECK(callback_count_ > 0, "Invalid callback count"); { ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); delete *it; callbacks_.erase(it); --callback_count_; if (callback_count_ == 0) UpdateTimer(false); } return; } } // Unknown token. RAW_LOG(FATAL, "Invalid token"); } void ProfileHandler::Reset() { SpinLockHolder cl(&control_lock_); { ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); CallbackIterator it = callbacks_.begin(); while (it != callbacks_.end()) { CallbackIterator tmp = it; ++it; delete *tmp; callbacks_.erase(tmp); } callback_count_ = 0; UpdateTimer(false); } } void ProfileHandler::GetState(ProfileHandlerState* state) { SpinLockHolder cl(&control_lock_); { ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); // Protects interrupts_. state->interrupts = interrupts_; } state->frequency = frequency_; state->callback_count = callback_count_; state->allowed = allowed_; } void ProfileHandler::UpdateTimer(bool enable) { if (per_thread_timer_enabled_) { // Ignore any attempts to disable it because that's not supported, and it's // always enabled so enabling is always a NOP. return; } if (enable == timer_running_) { return; } timer_running_ = enable; struct itimerval timer; static const int kMillion = 1000000; int interval_usec = enable ? kMillion / frequency_ : 0; timer.it_interval.tv_sec = interval_usec / kMillion; timer.it_interval.tv_usec = interval_usec % kMillion; timer.it_value = timer.it_interval; setitimer(timer_type_, &timer, 0); } bool ProfileHandler::IsSignalHandlerAvailable() { struct sigaction sa; RAW_CHECK(sigaction(signal_number_, NULL, &sa) == 0, "is-signal-handler avail"); // We only take over the handler if the current one is unset. // It must be SIG_IGN or SIG_DFL, not some other function. // SIG_IGN must be allowed because when profiling is allowed but // not actively in use, this code keeps the handler set to SIG_IGN. // That setting will be inherited across fork+exec. In order for // any child to be able to use profiling, SIG_IGN must be treated // as available. return sa.sa_handler == SIG_IGN || sa.sa_handler == SIG_DFL; } void ProfileHandler::SignalHandler(int sig, siginfo_t* sinfo, void* ucontext) { int saved_errno = errno; // At this moment, instance_ must be initialized because the handler is // enabled in RegisterThread or RegisterCallback only after // ProfileHandler::Instance runs. ProfileHandler* instance = ANNOTATE_UNPROTECTED_READ(instance_); RAW_CHECK(instance != NULL, "ProfileHandler is not initialized"); { SpinLockHolder sl(&instance->signal_lock_); ++instance->interrupts_; for (CallbackIterator it = instance->callbacks_.begin(); it != instance->callbacks_.end(); ++it) { (*it)->callback(sig, sinfo, ucontext, (*it)->callback_arg); } } errno = saved_errno; } // This module initializer registers the main thread, so it must be // executed in the context of the main thread. REGISTER_MODULE_INITIALIZER(profile_main, ProfileHandlerRegisterThread()); void ProfileHandlerRegisterThread() { ProfileHandler::Instance()->RegisterThread(); } ProfileHandlerToken* ProfileHandlerRegisterCallback( ProfileHandlerCallback callback, void* callback_arg) { return ProfileHandler::Instance()->RegisterCallback(callback, callback_arg); } void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token) { ProfileHandler::Instance()->UnregisterCallback(token); } void ProfileHandlerReset() { return ProfileHandler::Instance()->Reset(); } void ProfileHandlerGetState(ProfileHandlerState* state) { ProfileHandler::Instance()->GetState(state); } #else // OS_CYGWIN // ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't // work as well for profiling, and also interferes with alarm(). Because of // these issues, unless a specific need is identified, profiler support is // disabled under Cygwin. void ProfileHandlerRegisterThread() { } ProfileHandlerToken* ProfileHandlerRegisterCallback( ProfileHandlerCallback callback, void* callback_arg) { return NULL; } void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token) { } void ProfileHandlerReset() { } void ProfileHandlerGetState(ProfileHandlerState* state) { } #endif // OS_CYGWIN
Unknown
3D
mcellteam/mcell
libs/gperftools/src/raw_printer.cc
.cc
2,535
73
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: sanjay@google.com (Sanjay Ghemawat) #include <config.h> #include <stdarg.h> #include <stdio.h> #include "raw_printer.h" #include "base/logging.h" namespace base { RawPrinter::RawPrinter(char* buf, int length) : base_(buf), ptr_(buf), limit_(buf + length - 1) { RAW_DCHECK(length > 0, ""); *ptr_ = '\0'; *limit_ = '\0'; } void RawPrinter::Printf(const char* format, ...) { if (limit_ > ptr_) { va_list ap; va_start(ap, format); int avail = limit_ - ptr_; // We pass avail+1 to vsnprintf() since that routine needs room // to store the trailing \0. const int r = perftools_vsnprintf(ptr_, avail+1, format, ap); va_end(ap); if (r < 0) { // Perhaps an old glibc that returns -1 on truncation? ptr_ = limit_; } else if (r > avail) { // Truncation ptr_ = limit_; } else { ptr_ += r; } } } }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_libgcc-inl.h
.h
3,976
112
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2016, gperftools Contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This file implements backtrace capturing via libgcc's // _Unwind_Backtrace. This generally works almost always. It will fail // sometimes when we're trying to capture backtrace from signal // handler (i.e. in cpu profiler) while some C++ code is throwing // exception. #ifndef BASE_STACKTRACE_LIBGCC_INL_H_ #define BASE_STACKTRACE_LIBGCC_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: extern "C" { #include <assert.h> #include <string.h> // for memset() } #include <unwind.h> #include "gperftools/stacktrace.h" struct libgcc_backtrace_data { void **array; int skip; int pos; int limit; }; static _Unwind_Reason_Code libgcc_backtrace_helper(struct _Unwind_Context *ctx, void *_data) { libgcc_backtrace_data *data = reinterpret_cast<libgcc_backtrace_data *>(_data); if (data->skip > 0) { data->skip--; return _URC_NO_REASON; } if (data->pos < data->limit) { void *ip = reinterpret_cast<void *>(_Unwind_GetIP(ctx));; data->array[data->pos++] = ip; } return _URC_NO_REASON; } #endif // BASE_STACKTRACE_LIBGCC_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) static int GET_STACK_TRACE_OR_FRAMES { libgcc_backtrace_data data; data.array = result; // we're also skipping current and parent's frame data.skip = skip_count + 2; data.pos = 0; data.limit = max_depth; _Unwind_Backtrace(libgcc_backtrace_helper, &data); if (data.pos > 1 && data.array[data.pos - 1] == NULL) --data.pos; #if IS_STACK_FRAMES // No implementation for finding out the stack frame sizes. memset(sizes, 0, sizeof(*sizes) * data.pos); #endif return data.pos; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/addressmap-inl.h
.h
15,984
423
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // // A fast map from addresses to values. Assumes that addresses are // clustered. The main use is intended to be for heap-profiling. // May be too memory-hungry for other uses. // // We use a user-defined allocator/de-allocator so that we can use // this data structure during heap-profiling. // // IMPLEMENTATION DETAIL: // // Some default definitions/parameters: // * Block -- aligned 128-byte region of the address space // * Cluster -- aligned 1-MB region of the address space // * Block-ID -- block-number within a cluster // * Cluster-ID -- Starting address of cluster divided by cluster size // // We use a three-level map to represent the state: // 1. A hash-table maps from a cluster-ID to the data for that cluster. // 2. For each non-empty cluster we keep an array indexed by // block-ID tht points to the first entry in the linked-list // for the block. // 3. At the bottom, we keep a singly-linked list of all // entries in a block (for non-empty blocks). // // hash table // +-------------+ // | id->cluster |---> ... // | ... | // | id->cluster |---> Cluster // +-------------+ +-------+ Data for one block // | nil | +------------------------------------+ // | ----+---|->[addr/value]-->[addr/value]-->... | // | nil | +------------------------------------+ // | ----+--> ... // | nil | // | ... | // +-------+ // // Note that we require zero-bytes of overhead for completely empty // clusters. The minimum space requirement for a cluster is the size // of the hash-table entry plus a pointer value for each block in // the cluster. Empty blocks impose no extra space requirement. // // The cost of a lookup is: // a. A hash-table lookup to find the cluster // b. An array access in the cluster structure // c. A traversal over the linked-list for a block #ifndef BASE_ADDRESSMAP_INL_H_ #define BASE_ADDRESSMAP_INL_H_ #include "config.h" #include <stddef.h> #include <string.h> #if defined HAVE_STDINT_H #include <stdint.h> // to get uint16_t (ISO naming madness) #elif defined HAVE_INTTYPES_H #include <inttypes.h> // another place uint16_t might be defined #else #include <sys/types.h> // our last best hope #endif // This class is thread-unsafe -- that is, instances of this class can // not be accessed concurrently by multiple threads -- because the // callback function for Iterate() may mutate contained values. If the // callback functions you pass do not mutate their Value* argument, // AddressMap can be treated as thread-compatible -- that is, it's // safe for multiple threads to call "const" methods on this class, // but not safe for one thread to call const methods on this class // while another thread is calling non-const methods on the class. template <class Value> class AddressMap { public: typedef void* (*Allocator)(size_t size); typedef void (*DeAllocator)(void* ptr); typedef const void* Key; // Create an AddressMap that uses the specified allocator/deallocator. // The allocator/deallocator should behave like malloc/free. // For instance, the allocator does not need to return initialized memory. AddressMap(Allocator alloc, DeAllocator dealloc); ~AddressMap(); // If the map contains an entry for "key", return it. Else return NULL. inline const Value* Find(Key key) const; inline Value* FindMutable(Key key); // Insert <key,value> into the map. Any old value associated // with key is forgotten. void Insert(Key key, Value value); // Remove any entry for key in the map. If an entry was found // and removed, stores the associated value in "*removed_value" // and returns true. Else returns false. bool FindAndRemove(Key key, Value* removed_value); // Similar to Find but we assume that keys are addresses of non-overlapping // memory ranges whose sizes are given by size_func. // If the map contains a range into which "key" points // (at its start or inside of it, but not at the end), // return the address of the associated value // and store its key in "*res_key". // Else return NULL. // max_size specifies largest range size possibly in existence now. typedef size_t (*ValueSizeFunc)(const Value& v); const Value* FindInside(ValueSizeFunc size_func, size_t max_size, Key key, Key* res_key); // Iterate over the address map calling 'callback' // for all stored key-value pairs and passing 'arg' to it. // We don't use full Closure/Callback machinery not to add // unnecessary dependencies to this class with low-level uses. template<class Type> inline void Iterate(void (*callback)(Key, Value*, Type), Type arg) const; private: typedef uintptr_t Number; // The implementation assumes that addresses inserted into the map // will be clustered. We take advantage of this fact by splitting // up the address-space into blocks and using a linked-list entry // for each block. // Size of each block. There is one linked-list for each block, so // do not make the block-size too big. Oterwise, a lot of time // will be spent traversing linked lists. static const int kBlockBits = 7; static const int kBlockSize = 1 << kBlockBits; // Entry kept in per-block linked-list struct Entry { Entry* next; Key key; Value value; }; // We further group a sequence of consecutive blocks into a cluster. // The data for a cluster is represented as a dense array of // linked-lists, one list per contained block. static const int kClusterBits = 13; static const Number kClusterSize = 1 << (kBlockBits + kClusterBits); static const int kClusterBlocks = 1 << kClusterBits; // We use a simple chaining hash-table to represent the clusters. struct Cluster { Cluster* next; // Next cluster in hash table chain Number id; // Cluster ID Entry* blocks[kClusterBlocks]; // Per-block linked-lists }; // Number of hash-table entries. With the block-size/cluster-size // defined above, each cluster covers 1 MB, so an 4K entry // hash-table will give an average hash-chain length of 1 for 4GB of // in-use memory. static const int kHashBits = 12; static const int kHashSize = 1 << 12; // Number of entry objects allocated at a time static const int ALLOC_COUNT = 64; Cluster** hashtable_; // The hash-table Entry* free_; // Free list of unused Entry objects // Multiplicative hash function: // The value "kHashMultiplier" is the bottom 32 bits of // int((sqrt(5)-1)/2 * 2^32) // This is a good multiplier as suggested in CLR, Knuth. The hash // value is taken to be the top "k" bits of the bottom 32 bits // of the muliplied value. static const uint32_t kHashMultiplier = 2654435769u; static int HashInt(Number x) { // Multiply by a constant and take the top bits of the result. const uint32_t m = static_cast<uint32_t>(x) * kHashMultiplier; return static_cast<int>(m >> (32 - kHashBits)); } // Find cluster object for specified address. If not found // and "create" is true, create the object. If not found // and "create" is false, return NULL. // // This method is bitwise-const if create is false. Cluster* FindCluster(Number address, bool create) { // Look in hashtable const Number cluster_id = address >> (kBlockBits + kClusterBits); const int h = HashInt(cluster_id); for (Cluster* c = hashtable_[h]; c != NULL; c = c->next) { if (c->id == cluster_id) { return c; } } // Create cluster if necessary if (create) { Cluster* c = New<Cluster>(1); c->id = cluster_id; c->next = hashtable_[h]; hashtable_[h] = c; return c; } return NULL; } // Return the block ID for an address within its cluster static int BlockID(Number address) { return (address >> kBlockBits) & (kClusterBlocks - 1); } //-------------------------------------------------------------- // Memory management -- we keep all objects we allocate linked // together in a singly linked list so we can get rid of them // when we are all done. Furthermore, we allow the client to // pass in custom memory allocator/deallocator routines. //-------------------------------------------------------------- struct Object { Object* next; // The real data starts here }; Allocator alloc_; // The allocator DeAllocator dealloc_; // The deallocator Object* allocated_; // List of allocated objects // Allocates a zeroed array of T with length "num". Also inserts // the allocated block into a linked list so it can be deallocated // when we are all done. template <class T> T* New(int num) { void* ptr = (*alloc_)(sizeof(Object) + num*sizeof(T)); memset(ptr, 0, sizeof(Object) + num*sizeof(T)); Object* obj = reinterpret_cast<Object*>(ptr); obj->next = allocated_; allocated_ = obj; return reinterpret_cast<T*>(reinterpret_cast<Object*>(ptr) + 1); } }; // More implementation details follow: template <class Value> AddressMap<Value>::AddressMap(Allocator alloc, DeAllocator dealloc) : free_(NULL), alloc_(alloc), dealloc_(dealloc), allocated_(NULL) { hashtable_ = New<Cluster*>(kHashSize); } template <class Value> AddressMap<Value>::~AddressMap() { // De-allocate all of the objects we allocated for (Object* obj = allocated_; obj != NULL; /**/) { Object* next = obj->next; (*dealloc_)(obj); obj = next; } } template <class Value> inline const Value* AddressMap<Value>::Find(Key key) const { return const_cast<AddressMap*>(this)->FindMutable(key); } template <class Value> inline Value* AddressMap<Value>::FindMutable(Key key) { const Number num = reinterpret_cast<Number>(key); const Cluster* const c = FindCluster(num, false/*do not create*/); if (c != NULL) { for (Entry* e = c->blocks[BlockID(num)]; e != NULL; e = e->next) { if (e->key == key) { return &e->value; } } } return NULL; } template <class Value> void AddressMap<Value>::Insert(Key key, Value value) { const Number num = reinterpret_cast<Number>(key); Cluster* const c = FindCluster(num, true/*create*/); // Look in linked-list for this block const int block = BlockID(num); for (Entry* e = c->blocks[block]; e != NULL; e = e->next) { if (e->key == key) { e->value = value; return; } } // Create entry if (free_ == NULL) { // Allocate a new batch of entries and add to free-list Entry* array = New<Entry>(ALLOC_COUNT); for (int i = 0; i < ALLOC_COUNT-1; i++) { array[i].next = &array[i+1]; } array[ALLOC_COUNT-1].next = free_; free_ = &array[0]; } Entry* e = free_; free_ = e->next; e->key = key; e->value = value; e->next = c->blocks[block]; c->blocks[block] = e; } template <class Value> bool AddressMap<Value>::FindAndRemove(Key key, Value* removed_value) { const Number num = reinterpret_cast<Number>(key); Cluster* const c = FindCluster(num, false/*do not create*/); if (c != NULL) { for (Entry** p = &c->blocks[BlockID(num)]; *p != NULL; p = &(*p)->next) { Entry* e = *p; if (e->key == key) { *removed_value = e->value; *p = e->next; // Remove e from linked-list e->next = free_; // Add e to free-list free_ = e; return true; } } } return false; } template <class Value> const Value* AddressMap<Value>::FindInside(ValueSizeFunc size_func, size_t max_size, Key key, Key* res_key) { const Number key_num = reinterpret_cast<Number>(key); Number num = key_num; // we'll move this to move back through the clusters while (1) { const Cluster* c = FindCluster(num, false/*do not create*/); if (c != NULL) { while (1) { const int block = BlockID(num); bool had_smaller_key = false; for (const Entry* e = c->blocks[block]; e != NULL; e = e->next) { const Number e_num = reinterpret_cast<Number>(e->key); if (e_num <= key_num) { if (e_num == key_num || // to handle 0-sized ranges key_num < e_num + (*size_func)(e->value)) { *res_key = e->key; return &e->value; } had_smaller_key = true; } } if (had_smaller_key) return NULL; // got a range before 'key' // and it did not contain 'key' if (block == 0) break; // try address-wise previous block num |= kBlockSize - 1; // start at the last addr of prev block num -= kBlockSize; if (key_num - num > max_size) return NULL; } } if (num < kClusterSize) return NULL; // first cluster // go to address-wise previous cluster to try num |= kClusterSize - 1; // start at the last block of previous cluster num -= kClusterSize; if (key_num - num > max_size) return NULL; // Having max_size to limit the search is crucial: else // we have to traverse a lot of empty clusters (or blocks). // We can avoid needing max_size if we put clusters into // a search tree, but performance suffers considerably // if we use this approach by using stl::set. } } template <class Value> template <class Type> inline void AddressMap<Value>::Iterate(void (*callback)(Key, Value*, Type), Type arg) const { // We could optimize this by traversing only non-empty clusters and/or blocks // but it does not speed up heap-checker noticeably. for (int h = 0; h < kHashSize; ++h) { for (const Cluster* c = hashtable_[h]; c != NULL; c = c->next) { for (int b = 0; b < kClusterBlocks; ++b) { for (Entry* e = c->blocks[b]; e != NULL; e = e->next) { callback(e->key, &e->value, arg); } } } } } #endif // BASE_ADDRESSMAP_INL_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stack_trace_table.cc
.cc
3,898
124
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Andrew Fikes #include <config.h> #include "stack_trace_table.h" #include <string.h> // for NULL, memset #include "base/spinlock.h" // for SpinLockHolder #include "common.h" // for StackTrace #include "internal_logging.h" // for ASSERT, Log #include "page_heap_allocator.h" // for PageHeapAllocator #include "static_vars.h" // for Static namespace tcmalloc { StackTraceTable::StackTraceTable() : error_(false), depth_total_(0), bucket_total_(0), head_(nullptr) { } StackTraceTable::~StackTraceTable() { ASSERT(head_ == nullptr); } void StackTraceTable::AddTrace(const StackTrace& t) { if (error_) { return; } depth_total_ += t.depth; bucket_total_++; Entry* entry = allocator_.allocate(1); if (entry == nullptr) { Log(kLog, __FILE__, __LINE__, "tcmalloc: could not allocate bucket", sizeof(*entry)); error_ = true; } else { entry->trace = t; entry->next = head_; head_ = entry; } } void** StackTraceTable::ReadStackTracesAndClear() { void** out = nullptr; const int out_len = bucket_total_ * 3 + depth_total_ + 1; if (!error_) { // Allocate output array out = new (std::nothrow_t{}) void*[out_len]; if (out == nullptr) { Log(kLog, __FILE__, __LINE__, "tcmalloc: allocation failed for stack traces", out_len * sizeof(*out)); } } if (out) { // Fill output array int idx = 0; Entry* entry = head_; while (entry != NULL) { out[idx++] = reinterpret_cast<void*>(uintptr_t{1}); // count out[idx++] = reinterpret_cast<void*>(entry->trace.size); // cumulative size out[idx++] = reinterpret_cast<void*>(entry->trace.depth); for (int d = 0; d < entry->trace.depth; ++d) { out[idx++] = entry->trace.stack[d]; } entry = entry->next; } out[idx++] = NULL; ASSERT(idx == out_len); } // Clear state error_ = false; depth_total_ = 0; bucket_total_ = 0; SpinLockHolder h(Static::pageheap_lock()); Entry* entry = head_; while (entry != nullptr) { Entry* next = entry->next; allocator_.deallocate(entry, 1); entry = next; } head_ = nullptr; return out; } } // namespace tcmalloc
Unknown
3D
mcellteam/mcell
libs/gperftools/src/profiledata.cc
.cc
9,410
333
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // --- // Author: Sanjay Ghemawat // Chris Demetriou (refactoring) // // Collect profiling data. #include <config.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <sys/time.h> #include <string.h> #include <fcntl.h> #include "profiledata.h" #include "base/logging.h" #include "base/sysinfo.h" // All of these are initialized in profiledata.h. const int ProfileData::kMaxStackDepth; const int ProfileData::kAssociativity; const int ProfileData::kBuckets; const int ProfileData::kBufferLength; ProfileData::Options::Options() : frequency_(1) { } // This function is safe to call from asynchronous signals (but is not // re-entrant). However, that's not part of its public interface. void ProfileData::Evict(const Entry& entry) { const int d = entry.depth; const int nslots = d + 2; // Number of slots needed in eviction buffer if (num_evicted_ + nslots > kBufferLength) { FlushEvicted(); assert(num_evicted_ == 0); assert(nslots <= kBufferLength); } evict_[num_evicted_++] = entry.count; evict_[num_evicted_++] = d; memcpy(&evict_[num_evicted_], entry.stack, d * sizeof(Slot)); num_evicted_ += d; } ProfileData::ProfileData() : hash_(0), evict_(0), num_evicted_(0), out_(-1), count_(0), evictions_(0), total_bytes_(0), fname_(0), start_time_(0) { } bool ProfileData::Start(const char* fname, const ProfileData::Options& options) { if (enabled()) { return false; } // Open output file and initialize various data structures int fd = open(fname, O_CREAT | O_WRONLY | O_TRUNC, 0666); if (fd < 0) { // Can't open outfile for write return false; } start_time_ = time(NULL); fname_ = strdup(fname); // Reset counters num_evicted_ = 0; count_ = 0; evictions_ = 0; total_bytes_ = 0; hash_ = new Bucket[kBuckets]; evict_ = new Slot[kBufferLength]; memset(hash_, 0, sizeof(hash_[0]) * kBuckets); // Record special entries evict_[num_evicted_++] = 0; // count for header evict_[num_evicted_++] = 3; // depth for header evict_[num_evicted_++] = 0; // Version number CHECK_NE(0, options.frequency()); int period = 1000000 / options.frequency(); evict_[num_evicted_++] = period; // Period (microseconds) evict_[num_evicted_++] = 0; // Padding out_ = fd; return true; } ProfileData::~ProfileData() { Stop(); } // Dump /proc/maps data to fd. Copied from heap-profile-table.cc. #define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR) static void FDWrite(int fd, const char* buf, size_t len) { while (len > 0) { ssize_t r; NO_INTR(r = write(fd, buf, len)); RAW_CHECK(r >= 0, "write failed"); buf += r; len -= r; } } static void DumpProcSelfMaps(int fd) { ProcMapsIterator::Buffer iterbuf; ProcMapsIterator it(0, &iterbuf); // 0 means "current pid" uint64 start, end, offset; int64 inode; char *flags, *filename; ProcMapsIterator::Buffer linebuf; while (it.Next(&start, &end, &flags, &offset, &inode, &filename)) { int written = it.FormatLine(linebuf.buf_, sizeof(linebuf.buf_), start, end, flags, offset, inode, filename, 0); FDWrite(fd, linebuf.buf_, written); } } void ProfileData::Stop() { if (!enabled()) { return; } // Move data from hash table to eviction buffer for (int b = 0; b < kBuckets; b++) { Bucket* bucket = &hash_[b]; for (int a = 0; a < kAssociativity; a++) { if (bucket->entry[a].count > 0) { Evict(bucket->entry[a]); } } } if (num_evicted_ + 3 > kBufferLength) { // Ensure there is enough room for end of data marker FlushEvicted(); } // Write end of data marker evict_[num_evicted_++] = 0; // count evict_[num_evicted_++] = 1; // depth evict_[num_evicted_++] = 0; // end of data marker FlushEvicted(); // Dump "/proc/self/maps" so we get list of mapped shared libraries DumpProcSelfMaps(out_); Reset(); fprintf(stderr, "PROFILE: interrupts/evictions/bytes = %d/%d/%" PRIuS "\n", count_, evictions_, total_bytes_); } void ProfileData::Reset() { if (!enabled()) { return; } // Don't reset count_, evictions_, or total_bytes_ here. They're used // by Stop to print information about the profile after reset, and are // cleared by Start when starting a new profile. close(out_); delete[] hash_; hash_ = 0; delete[] evict_; evict_ = 0; num_evicted_ = 0; free(fname_); fname_ = 0; start_time_ = 0; out_ = -1; } // This function is safe to call from asynchronous signals (but is not // re-entrant). However, that's not part of its public interface. void ProfileData::GetCurrentState(State* state) const { if (enabled()) { state->enabled = true; state->start_time = start_time_; state->samples_gathered = count_; int buf_size = sizeof(state->profile_name); strncpy(state->profile_name, fname_, buf_size); state->profile_name[buf_size-1] = '\0'; } else { state->enabled = false; state->start_time = 0; state->samples_gathered = 0; state->profile_name[0] = '\0'; } } // This function is safe to call from asynchronous signals (but is not // re-entrant). However, that's not part of its public interface. void ProfileData::FlushTable() { if (!enabled()) { return; } // Move data from hash table to eviction buffer for (int b = 0; b < kBuckets; b++) { Bucket* bucket = &hash_[b]; for (int a = 0; a < kAssociativity; a++) { if (bucket->entry[a].count > 0) { Evict(bucket->entry[a]); bucket->entry[a].depth = 0; bucket->entry[a].count = 0; } } } // Write out all pending data FlushEvicted(); } void ProfileData::Add(int depth, const void* const* stack) { if (!enabled()) { return; } if (depth > kMaxStackDepth) depth = kMaxStackDepth; RAW_CHECK(depth > 0, "ProfileData::Add depth <= 0"); // Make hash-value Slot h = 0; for (int i = 0; i < depth; i++) { Slot slot = reinterpret_cast<Slot>(stack[i]); h = (h << 8) | (h >> (8*(sizeof(h)-1))); h += (slot * 31) + (slot * 7) + (slot * 3); } count_++; // See if table already has an entry for this trace bool done = false; Bucket* bucket = &hash_[h % kBuckets]; for (int a = 0; a < kAssociativity; a++) { Entry* e = &bucket->entry[a]; if (e->depth == depth) { bool match = true; for (int i = 0; i < depth; i++) { if (e->stack[i] != reinterpret_cast<Slot>(stack[i])) { match = false; break; } } if (match) { e->count++; done = true; break; } } } if (!done) { // Evict entry with smallest count Entry* e = &bucket->entry[0]; for (int a = 1; a < kAssociativity; a++) { if (bucket->entry[a].count < e->count) { e = &bucket->entry[a]; } } if (e->count > 0) { evictions_++; Evict(*e); } // Use the newly evicted entry e->depth = depth; e->count = 1; for (int i = 0; i < depth; i++) { e->stack[i] = reinterpret_cast<Slot>(stack[i]); } } } // This function is safe to call from asynchronous signals (but is not // re-entrant). However, that's not part of its public interface. void ProfileData::FlushEvicted() { if (num_evicted_ > 0) { const char* buf = reinterpret_cast<char*>(evict_); size_t bytes = sizeof(evict_[0]) * num_evicted_; total_bytes_ += bytes; FDWrite(out_, buf, bytes); } num_evicted_ = 0; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_generic-inl.h
.h
3,416
85
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // // Portable implementation - just use glibc // // Note: The glibc implementation may cause a call to malloc. // This can cause a deadlock in HeapProfiler. #ifndef BASE_STACKTRACE_GENERIC_INL_H_ #define BASE_STACKTRACE_GENERIC_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include <execinfo.h> #include <string.h> #include "gperftools/stacktrace.h" #endif // BASE_STACKTRACE_GENERIC_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) static int GET_STACK_TRACE_OR_FRAMES { static const int kStackLength = 64; void * stack[kStackLength]; int size; size = backtrace(stack, kStackLength); skip_count += 2; // we want to skip the current and it's parent frame as well int result_count = size - skip_count; if (result_count < 0) result_count = 0; if (result_count > max_depth) result_count = max_depth; for (int i = 0; i < result_count; i++) result[i] = stack[i + skip_count]; #if IS_STACK_FRAMES // No implementation for finding out the stack frame sizes yet. memset(sizes, 0, sizeof(*sizes) * result_count); #endif return result_count; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/emergency_malloc.cc
.cc
6,434
170
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2014, gperftools Contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "config.h" #include "emergency_malloc.h" #include <errno.h> // for ENOMEM, errno #include <string.h> // for memset #include "base/basictypes.h" #include "base/logging.h" #include "base/low_level_alloc.h" #include "base/spinlock.h" #include "internal_logging.h" namespace tcmalloc { __attribute__ ((visibility("internal"))) char *emergency_arena_start; __attribute__ ((visibility("internal"))) uintptr_t emergency_arena_start_shifted; static CACHELINE_ALIGNED SpinLock emergency_malloc_lock(base::LINKER_INITIALIZED); static char *emergency_arena_end; static LowLevelAlloc::Arena *emergency_arena; class EmergencyArenaPagesAllocator : public LowLevelAlloc::PagesAllocator { ~EmergencyArenaPagesAllocator() {} void *MapPages(int32 flags, size_t size) { char *new_end = emergency_arena_end + size; if (new_end > emergency_arena_start + kEmergencyArenaSize) { RAW_LOG(FATAL, "Unable to allocate %" PRIuS " bytes in emergency zone.", size); } char *rv = emergency_arena_end; emergency_arena_end = new_end; return static_cast<void *>(rv); } void UnMapPages(int32 flags, void *addr, size_t size) { RAW_LOG(FATAL, "UnMapPages is not implemented for emergency arena"); } }; static union { char bytes[sizeof(EmergencyArenaPagesAllocator)]; void *ptr; } pages_allocator_place; static void InitEmergencyMalloc(void) { const int32 flags = LowLevelAlloc::kAsyncSignalSafe; void *arena = LowLevelAlloc::GetDefaultPagesAllocator()->MapPages(flags, kEmergencyArenaSize * 2); uintptr_t arena_ptr = reinterpret_cast<uintptr_t>(arena); uintptr_t ptr = (arena_ptr + kEmergencyArenaSize - 1) & ~(kEmergencyArenaSize-1); emergency_arena_end = emergency_arena_start = reinterpret_cast<char *>(ptr); EmergencyArenaPagesAllocator *allocator = new (pages_allocator_place.bytes) EmergencyArenaPagesAllocator(); emergency_arena = LowLevelAlloc::NewArenaWithCustomAlloc(0, LowLevelAlloc::DefaultArena(), allocator); emergency_arena_start_shifted = reinterpret_cast<uintptr_t>(emergency_arena_start) >> kEmergencyArenaShift; uintptr_t head_unmap_size = ptr - arena_ptr; CHECK_CONDITION(head_unmap_size < kEmergencyArenaSize); if (head_unmap_size != 0) { LowLevelAlloc::GetDefaultPagesAllocator()->UnMapPages(flags, arena, ptr - arena_ptr); } uintptr_t tail_unmap_size = kEmergencyArenaSize - head_unmap_size; void *tail_start = reinterpret_cast<void *>(arena_ptr + head_unmap_size + kEmergencyArenaSize); LowLevelAlloc::GetDefaultPagesAllocator()->UnMapPages(flags, tail_start, tail_unmap_size); } PERFTOOLS_DLL_DECL void *EmergencyMalloc(size_t size) { SpinLockHolder l(&emergency_malloc_lock); if (emergency_arena_start == NULL) { InitEmergencyMalloc(); CHECK_CONDITION(emergency_arena_start != NULL); } void *rv = LowLevelAlloc::AllocWithArena(size, emergency_arena); if (rv == NULL) { errno = ENOMEM; } return rv; } PERFTOOLS_DLL_DECL void EmergencyFree(void *p) { SpinLockHolder l(&emergency_malloc_lock); if (emergency_arena_start == NULL) { InitEmergencyMalloc(); CHECK_CONDITION(emergency_arena_start != NULL); free(p); return; } CHECK_CONDITION(emergency_arena_start); LowLevelAlloc::Free(p); } PERFTOOLS_DLL_DECL void *EmergencyRealloc(void *_old_ptr, size_t new_size) { if (_old_ptr == NULL) { return EmergencyMalloc(new_size); } if (new_size == 0) { EmergencyFree(_old_ptr); return NULL; } SpinLockHolder l(&emergency_malloc_lock); CHECK_CONDITION(emergency_arena_start); char *old_ptr = static_cast<char *>(_old_ptr); CHECK_CONDITION(old_ptr <= emergency_arena_end); CHECK_CONDITION(emergency_arena_start <= old_ptr); // NOTE: we don't know previous size of old_ptr chunk. So instead // of trying to figure out right size of copied memory, we just // copy largest possible size. We don't care about being slow. size_t old_ptr_size = emergency_arena_end - old_ptr; size_t copy_size = (new_size < old_ptr_size) ? new_size : old_ptr_size; void *new_ptr = LowLevelAlloc::AllocWithArena(new_size, emergency_arena); if (new_ptr == NULL) { errno = ENOMEM; return NULL; } memcpy(new_ptr, old_ptr, copy_size); LowLevelAlloc::Free(old_ptr); return new_ptr; } PERFTOOLS_DLL_DECL void *EmergencyCalloc(size_t n, size_t elem_size) { // Overflow check const size_t size = n * elem_size; if (elem_size != 0 && size / elem_size != n) return NULL; void *rv = EmergencyMalloc(size); if (rv != NULL) { memset(rv, 0, size); } return rv; } };
Unknown
3D
mcellteam/mcell
libs/gperftools/src/system-alloc.cc
.cc
18,880
556
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat #include <config.h> #include <errno.h> // for EAGAIN, errno #include <fcntl.h> // for open, O_RDWR #include <stddef.h> // for size_t, NULL, ptrdiff_t #if defined HAVE_STDINT_H #include <stdint.h> // for uintptr_t, intptr_t #elif defined HAVE_INTTYPES_H #include <inttypes.h> #else #include <sys/types.h> #endif #ifdef HAVE_MMAP #include <sys/mman.h> // for munmap, mmap, MADV_DONTNEED, etc #endif #ifdef HAVE_UNISTD_H #include <unistd.h> // for sbrk, getpagesize, off_t #endif #include <new> // for operator new #include <gperftools/malloc_extension.h> #include "base/basictypes.h" #include "base/commandlineflags.h" #include "base/spinlock.h" // for SpinLockHolder, SpinLock, etc #include "common.h" #include "internal_logging.h" // On systems (like freebsd) that don't define MAP_ANONYMOUS, use the old // form of the name instead. #ifndef MAP_ANONYMOUS # define MAP_ANONYMOUS MAP_ANON #endif // Linux added support for MADV_FREE in 4.5 but we aren't ready to use it // yet. Among other things, using compile-time detection leads to poor // results when compiling on a system with MADV_FREE and running on a // system without it. See https://github.com/gperftools/gperftools/issues/780. #if defined(__linux__) && defined(MADV_FREE) && !defined(TCMALLOC_USE_MADV_FREE) # undef MADV_FREE #endif // MADV_FREE is specifically designed for use by malloc(), but only // FreeBSD supports it; in linux we fall back to the somewhat inferior // MADV_DONTNEED. #if !defined(MADV_FREE) && defined(MADV_DONTNEED) # define MADV_FREE MADV_DONTNEED #endif // Solaris has a bug where it doesn't declare madvise() for C++. // http://www.opensolaris.org/jive/thread.jspa?threadID=21035&tstart=0 #if defined(__sun) && defined(__SVR4) # include <sys/types.h> // for caddr_t extern "C" { extern int madvise(caddr_t, size_t, int); } #endif // Set kDebugMode mode so that we can have use C++ conditionals // instead of preprocessor conditionals. #ifdef NDEBUG static const bool kDebugMode = false; #else static const bool kDebugMode = true; #endif // TODO(sanjay): Move the code below into the tcmalloc namespace using tcmalloc::kLog; using tcmalloc::Log; // Check that no bit is set at position ADDRESS_BITS or higher. static bool CheckAddressBits(uintptr_t ptr) { bool always_ok = (kAddressBits == 8 * sizeof(void*)); // this is a bit insane but otherwise we get compiler warning about // shifting right by word size even if this code is dead :( int shift_bits = always_ok ? 0 : kAddressBits; return always_ok || ((ptr >> shift_bits) == 0); } COMPILE_ASSERT(kAddressBits <= 8 * sizeof(void*), address_bits_larger_than_pointer_size); static SpinLock spinlock(SpinLock::LINKER_INITIALIZED); #if defined(HAVE_MMAP) || defined(MADV_FREE) // Page size is initialized on demand (only needed for mmap-based allocators) static size_t pagesize = 0; #endif // The current system allocator SysAllocator* tcmalloc_sys_alloc = NULL; // Number of bytes taken from system. size_t TCMalloc_SystemTaken = 0; // Configuration parameters. DEFINE_int32(malloc_devmem_start, EnvToInt("TCMALLOC_DEVMEM_START", 0), "Physical memory starting location in MB for /dev/mem allocation." " Setting this to 0 disables /dev/mem allocation"); DEFINE_int32(malloc_devmem_limit, EnvToInt("TCMALLOC_DEVMEM_LIMIT", 0), "Physical memory limit location in MB for /dev/mem allocation." " Setting this to 0 means no limit."); DEFINE_bool(malloc_skip_sbrk, EnvToBool("TCMALLOC_SKIP_SBRK", false), "Whether sbrk can be used to obtain memory."); DEFINE_bool(malloc_skip_mmap, EnvToBool("TCMALLOC_SKIP_MMAP", false), "Whether mmap can be used to obtain memory."); DEFINE_bool(malloc_disable_memory_release, EnvToBool("TCMALLOC_DISABLE_MEMORY_RELEASE", false), "Whether MADV_FREE/MADV_DONTNEED should be used" " to return unused memory to the system."); // static allocators class SbrkSysAllocator : public SysAllocator { public: SbrkSysAllocator() : SysAllocator() { } void* Alloc(size_t size, size_t *actual_size, size_t alignment); }; static union { char buf[sizeof(SbrkSysAllocator)]; void *ptr; } sbrk_space; class MmapSysAllocator : public SysAllocator { public: MmapSysAllocator() : SysAllocator() { } void* Alloc(size_t size, size_t *actual_size, size_t alignment); }; static union { char buf[sizeof(MmapSysAllocator)]; void *ptr; } mmap_space; class DevMemSysAllocator : public SysAllocator { public: DevMemSysAllocator() : SysAllocator() { } void* Alloc(size_t size, size_t *actual_size, size_t alignment); }; class DefaultSysAllocator : public SysAllocator { public: DefaultSysAllocator() : SysAllocator() { for (int i = 0; i < kMaxAllocators; i++) { failed_[i] = true; allocs_[i] = NULL; names_[i] = NULL; } } void SetChildAllocator(SysAllocator* alloc, unsigned int index, const char* name) { if (index < kMaxAllocators && alloc != NULL) { allocs_[index] = alloc; failed_[index] = false; names_[index] = name; } } void* Alloc(size_t size, size_t *actual_size, size_t alignment); private: static const int kMaxAllocators = 2; bool failed_[kMaxAllocators]; SysAllocator* allocs_[kMaxAllocators]; const char* names_[kMaxAllocators]; }; static union { char buf[sizeof(DefaultSysAllocator)]; void *ptr; } default_space; static const char sbrk_name[] = "SbrkSysAllocator"; static const char mmap_name[] = "MmapSysAllocator"; void* SbrkSysAllocator::Alloc(size_t size, size_t *actual_size, size_t alignment) { #if !defined(HAVE_SBRK) || defined(__UCLIBC__) return NULL; #else // Check if we should use sbrk allocation. // FLAGS_malloc_skip_sbrk starts out as false (its uninitialized // state) and eventually gets initialized to the specified value. Note // that this code runs for a while before the flags are initialized. // That means that even if this flag is set to true, some (initial) // memory will be allocated with sbrk before the flag takes effect. if (FLAGS_malloc_skip_sbrk) { return NULL; } // sbrk will release memory if passed a negative number, so we do // a strict check here if (static_cast<ptrdiff_t>(size + alignment) < 0) return NULL; // This doesn't overflow because TCMalloc_SystemAlloc has already // tested for overflow at the alignment boundary. size = ((size + alignment - 1) / alignment) * alignment; // "actual_size" indicates that the bytes from the returned pointer // p up to and including (p + actual_size - 1) have been allocated. if (actual_size) { *actual_size = size; } // Check that we we're not asking for so much more memory that we'd // wrap around the end of the virtual address space. (This seems // like something sbrk() should check for us, and indeed opensolaris // does, but glibc does not: // http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/lib/libc/port/sys/sbrk.c?a=true // http://sourceware.org/cgi-bin/cvsweb.cgi/~checkout~/libc/misc/sbrk.c?rev=1.1.2.1&content-type=text/plain&cvsroot=glibc // Without this check, sbrk may succeed when it ought to fail.) if (reinterpret_cast<intptr_t>(sbrk(0)) + size < size) { return NULL; } void* result = sbrk(size); if (result == reinterpret_cast<void*>(-1)) { return NULL; } // Is it aligned? uintptr_t ptr = reinterpret_cast<uintptr_t>(result); if ((ptr & (alignment-1)) == 0) return result; // Try to get more memory for alignment size_t extra = alignment - (ptr & (alignment-1)); void* r2 = sbrk(extra); if (reinterpret_cast<uintptr_t>(r2) == (ptr + size)) { // Contiguous with previous result return reinterpret_cast<void*>(ptr + extra); } // Give up and ask for "size + alignment - 1" bytes so // that we can find an aligned region within it. result = sbrk(size + alignment - 1); if (result == reinterpret_cast<void*>(-1)) { return NULL; } ptr = reinterpret_cast<uintptr_t>(result); if ((ptr & (alignment-1)) != 0) { ptr += alignment - (ptr & (alignment-1)); } return reinterpret_cast<void*>(ptr); #endif // HAVE_SBRK } void* MmapSysAllocator::Alloc(size_t size, size_t *actual_size, size_t alignment) { #ifndef HAVE_MMAP return NULL; #else // Check if we should use mmap allocation. // FLAGS_malloc_skip_mmap starts out as false (its uninitialized // state) and eventually gets initialized to the specified value. Note // that this code runs for a while before the flags are initialized. // Chances are we never get here before the flags are initialized since // sbrk is used until the heap is exhausted (before mmap is used). if (FLAGS_malloc_skip_mmap) { return NULL; } // Enforce page alignment if (pagesize == 0) pagesize = getpagesize(); if (alignment < pagesize) alignment = pagesize; size_t aligned_size = ((size + alignment - 1) / alignment) * alignment; if (aligned_size < size) { return NULL; } size = aligned_size; // "actual_size" indicates that the bytes from the returned pointer // p up to and including (p + actual_size - 1) have been allocated. if (actual_size) { *actual_size = size; } // Ask for extra memory if alignment > pagesize size_t extra = 0; if (alignment > pagesize) { extra = alignment - pagesize; } // Note: size + extra does not overflow since: // size + alignment < (1<<NBITS). // and extra <= alignment // therefore size + extra < (1<<NBITS) void* result = mmap(NULL, size + extra, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (result == reinterpret_cast<void*>(MAP_FAILED)) { return NULL; } // Adjust the return memory so it is aligned uintptr_t ptr = reinterpret_cast<uintptr_t>(result); size_t adjust = 0; if ((ptr & (alignment - 1)) != 0) { adjust = alignment - (ptr & (alignment - 1)); } // Return the unused memory to the system if (adjust > 0) { munmap(reinterpret_cast<void*>(ptr), adjust); } if (adjust < extra) { munmap(reinterpret_cast<void*>(ptr + adjust + size), extra - adjust); } ptr += adjust; return reinterpret_cast<void*>(ptr); #endif // HAVE_MMAP } void* DevMemSysAllocator::Alloc(size_t size, size_t *actual_size, size_t alignment) { #ifndef HAVE_MMAP return NULL; #else static bool initialized = false; static off_t physmem_base; // next physical memory address to allocate static off_t physmem_limit; // maximum physical address allowed static int physmem_fd; // file descriptor for /dev/mem // Check if we should use /dev/mem allocation. Note that it may take // a while to get this flag initialized, so meanwhile we fall back to // the next allocator. (It looks like 7MB gets allocated before // this flag gets initialized -khr.) if (FLAGS_malloc_devmem_start == 0) { // NOTE: not a devmem_failure - we'd like TCMalloc_SystemAlloc to // try us again next time. return NULL; } if (!initialized) { physmem_fd = open("/dev/mem", O_RDWR); if (physmem_fd < 0) { return NULL; } physmem_base = FLAGS_malloc_devmem_start*1024LL*1024LL; physmem_limit = FLAGS_malloc_devmem_limit*1024LL*1024LL; initialized = true; } // Enforce page alignment if (pagesize == 0) pagesize = getpagesize(); if (alignment < pagesize) alignment = pagesize; size_t aligned_size = ((size + alignment - 1) / alignment) * alignment; if (aligned_size < size) { return NULL; } size = aligned_size; // "actual_size" indicates that the bytes from the returned pointer // p up to and including (p + actual_size - 1) have been allocated. if (actual_size) { *actual_size = size; } // Ask for extra memory if alignment > pagesize size_t extra = 0; if (alignment > pagesize) { extra = alignment - pagesize; } // check to see if we have any memory left if (physmem_limit != 0 && ((size + extra) > (physmem_limit - physmem_base))) { return NULL; } // Note: size + extra does not overflow since: // size + alignment < (1<<NBITS). // and extra <= alignment // therefore size + extra < (1<<NBITS) void *result = mmap(0, size + extra, PROT_WRITE|PROT_READ, MAP_SHARED, physmem_fd, physmem_base); if (result == reinterpret_cast<void*>(MAP_FAILED)) { return NULL; } uintptr_t ptr = reinterpret_cast<uintptr_t>(result); // Adjust the return memory so it is aligned size_t adjust = 0; if ((ptr & (alignment - 1)) != 0) { adjust = alignment - (ptr & (alignment - 1)); } // Return the unused virtual memory to the system if (adjust > 0) { munmap(reinterpret_cast<void*>(ptr), adjust); } if (adjust < extra) { munmap(reinterpret_cast<void*>(ptr + adjust + size), extra - adjust); } ptr += adjust; physmem_base += adjust + size; return reinterpret_cast<void*>(ptr); #endif // HAVE_MMAP } void* DefaultSysAllocator::Alloc(size_t size, size_t *actual_size, size_t alignment) { for (int i = 0; i < kMaxAllocators; i++) { if (!failed_[i] && allocs_[i] != NULL) { void* result = allocs_[i]->Alloc(size, actual_size, alignment); if (result != NULL) { return result; } failed_[i] = true; } } // After both failed, reset "failed_" to false so that a single failed // allocation won't make the allocator never work again. for (int i = 0; i < kMaxAllocators; i++) { failed_[i] = false; } return NULL; } ATTRIBUTE_WEAK ATTRIBUTE_NOINLINE SysAllocator *tc_get_sysalloc_override(SysAllocator *def) { return def; } static bool system_alloc_inited = false; void InitSystemAllocators(void) { MmapSysAllocator *mmap = new (mmap_space.buf) MmapSysAllocator(); SbrkSysAllocator *sbrk = new (sbrk_space.buf) SbrkSysAllocator(); // In 64-bit debug mode, place the mmap allocator first since it // allocates pointers that do not fit in 32 bits and therefore gives // us better testing of code's 64-bit correctness. It also leads to // less false negatives in heap-checking code. (Numbers are less // likely to look like pointers and therefore the conservative gc in // the heap-checker is less likely to misinterpret a number as a // pointer). DefaultSysAllocator *sdef = new (default_space.buf) DefaultSysAllocator(); if (kDebugMode && sizeof(void*) > 4) { sdef->SetChildAllocator(mmap, 0, mmap_name); sdef->SetChildAllocator(sbrk, 1, sbrk_name); } else { sdef->SetChildAllocator(sbrk, 0, sbrk_name); sdef->SetChildAllocator(mmap, 1, mmap_name); } tcmalloc_sys_alloc = tc_get_sysalloc_override(sdef); } void* TCMalloc_SystemAlloc(size_t size, size_t *actual_size, size_t alignment) { // Discard requests that overflow if (size + alignment < size) return NULL; SpinLockHolder lock_holder(&spinlock); if (!system_alloc_inited) { InitSystemAllocators(); system_alloc_inited = true; } // Enforce minimum alignment if (alignment < sizeof(MemoryAligner)) alignment = sizeof(MemoryAligner); size_t actual_size_storage; if (actual_size == NULL) { actual_size = &actual_size_storage; } void* result = tcmalloc_sys_alloc->Alloc(size, actual_size, alignment); if (result != NULL) { CHECK_CONDITION( CheckAddressBits(reinterpret_cast<uintptr_t>(result) + *actual_size - 1)); TCMalloc_SystemTaken += *actual_size; } return result; } bool TCMalloc_SystemRelease(void* start, size_t length) { #ifdef MADV_FREE if (FLAGS_malloc_devmem_start) { // It's not safe to use MADV_FREE/MADV_DONTNEED if we've been // mapping /dev/mem for heap memory. return false; } if (FLAGS_malloc_disable_memory_release) return false; if (pagesize == 0) pagesize = getpagesize(); const size_t pagemask = pagesize - 1; size_t new_start = reinterpret_cast<size_t>(start); size_t end = new_start + length; size_t new_end = end; // Round up the starting address and round down the ending address // to be page aligned: new_start = (new_start + pagesize - 1) & ~pagemask; new_end = new_end & ~pagemask; ASSERT((new_start & pagemask) == 0); ASSERT((new_end & pagemask) == 0); ASSERT(new_start >= reinterpret_cast<size_t>(start)); ASSERT(new_end <= end); if (new_end > new_start) { int result; do { result = madvise(reinterpret_cast<char*>(new_start), new_end - new_start, MADV_FREE); } while (result == -1 && errno == EAGAIN); return result != -1; } #endif return false; } void TCMalloc_SystemCommit(void* start, size_t length) { // Nothing to do here. TCMalloc_SystemRelease does not alter pages // such that they need to be re-committed before they can be used by the // application. }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/symbolize.h
.h
3,204
85
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein #ifndef TCMALLOC_SYMBOLIZE_H_ #define TCMALLOC_SYMBOLIZE_H_ #include "config.h" #ifdef HAVE_STDINT_H #include <stdint.h> // for uintptr_t #endif #include <stddef.h> // for NULL #include <map> using std::map; // SymbolTable encapsulates the address operations necessary for stack trace // symbolization. A common use-case is to Add() the addresses from one or // several stack traces to a table, call Symbolize() once and use GetSymbol() // to get the symbol names for pretty-printing the stack traces. class SymbolTable { public: SymbolTable() : symbol_buffer_(NULL) {} ~SymbolTable() { delete[] symbol_buffer_; } // Adds an address to the table. This may overwrite a currently known symbol // name, so Add() should not generally be called after Symbolize(). void Add(const void* addr); // Returns the symbol name for addr, if the given address was added before // the last successful call to Symbolize(). Otherwise may return an empty // c-string. const char* GetSymbol(const void* addr); // Obtains the symbol names for the addresses stored in the table and returns // the number of addresses actually symbolized. int Symbolize(); private: typedef map<const void*, const char*> SymbolMap; // An average size of memory allocated for a stack trace symbol. static const int kSymbolSize = 1024; // Map from addresses to symbol names. SymbolMap symbolization_table_; // Pointer to the buffer that stores the symbol names. char *symbol_buffer_; }; #endif // TCMALLOC_SYMBOLIZE_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/getenv_safe.h
.h
2,808
64
/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- * Copyright (c) 2014, gperftools Contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GETENV_SAFE_H #define GETENV_SAFE_H #ifdef __cplusplus extern "C" { #endif /* * This getenv function is safe to call before the C runtime is initialized. * On Windows, it utilizes GetEnvironmentVariable() and on unix it uses * /proc/self/environ instead calling getenv(). It's intended to be used in * routines that run before main(), when the state required for getenv() may * not be set up yet. In particular, errno isn't set up until relatively late * (after the pthreads library has a chance to make it threadsafe), and * getenv() doesn't work until then. * On some platforms, this call will utilize the same, static buffer for * repeated GetenvBeforeMain() calls. Callers should not expect pointers from * this routine to be long lived. * Note that on unix, /proc only has the environment at the time the * application was started, so this routine ignores setenv() calls/etc. Also * note it only reads the first 16K of the environment. * * NOTE: this is version of GetenvBeforeMain that's usable from * C. Implementation is in sysinfo.cc */ const char* TCMallocGetenvSafe(const char* name); #ifdef __cplusplus } #endif #endif
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_impl_setup-inl.h
.h
3,717
95
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // NOTE: this is NOT to be #include-d normally. It's internal // implementation detail of stacktrace.cc // // Copyright (c) 2014, gperftools Contributors. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Aliaksey Kandratsenka <alk@tut.by> // // based on stacktrace.cc and stacktrace_config.h by Sanjay Ghemawat // and Paul Pluzhnikov from Google Inc #define SIS_CONCAT2(a, b) a##b #define SIS_CONCAT(a, b) SIS_CONCAT2(a,b) #define SIS_STRINGIFY(a) SIS_STRINGIFY2(a) #define SIS_STRINGIFY2(a) #a #define IS_STACK_FRAMES 0 #define IS_WITH_CONTEXT 0 #define GET_STACK_TRACE_OR_FRAMES \ SIS_CONCAT(GetStackTrace_, GST_SUFFIX)(void **result, int max_depth, int skip_count) #include STACKTRACE_INL_HEADER #undef IS_STACK_FRAMES #undef IS_WITH_CONTEXT #undef GET_STACK_TRACE_OR_FRAMES #define IS_STACK_FRAMES 1 #define IS_WITH_CONTEXT 0 #define GET_STACK_TRACE_OR_FRAMES \ SIS_CONCAT(GetStackFrames_, GST_SUFFIX)(void **result, int *sizes, int max_depth, int skip_count) #include STACKTRACE_INL_HEADER #undef IS_STACK_FRAMES #undef IS_WITH_CONTEXT #undef GET_STACK_TRACE_OR_FRAMES #define IS_STACK_FRAMES 0 #define IS_WITH_CONTEXT 1 #define GET_STACK_TRACE_OR_FRAMES \ SIS_CONCAT(GetStackTraceWithContext_, GST_SUFFIX)(void **result, int max_depth, \ int skip_count, const void *ucp) #include STACKTRACE_INL_HEADER #undef IS_STACK_FRAMES #undef IS_WITH_CONTEXT #undef GET_STACK_TRACE_OR_FRAMES #define IS_STACK_FRAMES 1 #define IS_WITH_CONTEXT 1 #define GET_STACK_TRACE_OR_FRAMES \ SIS_CONCAT(GetStackFramesWithContext_, GST_SUFFIX)(void **result, int *sizes, int max_depth, \ int skip_count, const void *ucp) #include STACKTRACE_INL_HEADER #undef IS_STACK_FRAMES #undef IS_WITH_CONTEXT #undef GET_STACK_TRACE_OR_FRAMES static GetStackImplementation SIS_CONCAT(impl__,GST_SUFFIX) = { SIS_CONCAT(GetStackFrames_, GST_SUFFIX), SIS_CONCAT(GetStackFramesWithContext_, GST_SUFFIX), SIS_CONCAT(GetStackTrace_, GST_SUFFIX), SIS_CONCAT(GetStackTraceWithContext_, GST_SUFFIX), SIS_STRINGIFY(GST_SUFFIX) }; #undef SIS_CONCAT2 #undef SIS_CONCAT
Unknown
3D
mcellteam/mcell
libs/gperftools/src/libc_override_glibc.h
.h
4,218
93
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein <opensource@google.com> // // Used to override malloc routines on systems that are using glibc. #ifndef TCMALLOC_LIBC_OVERRIDE_GLIBC_INL_H_ #define TCMALLOC_LIBC_OVERRIDE_GLIBC_INL_H_ #include <config.h> #include <features.h> // for __GLIBC__ #include <gperftools/tcmalloc.h> #ifndef __GLIBC__ # error libc_override_glibc.h is for glibc distributions only. #endif // In glibc, the memory-allocation methods are weak symbols, so we can // just override them with our own. If we're using gcc, we can use // __attribute__((alias)) to do the overriding easily (exception: // Mach-O, which doesn't support aliases). Otherwise we have to use a // function call. #if !defined(__GNUC__) || defined(__MACH__) // This also defines ReplaceSystemAlloc(). # include "libc_override_redefine.h" // defines functions malloc()/etc #else // #if !defined(__GNUC__) || defined(__MACH__) // If we get here, we're a gcc system, so do all the overriding we do // with gcc. This does the overriding of all the 'normal' memory // allocation. This also defines ReplaceSystemAlloc(). # include "libc_override_gcc_and_weak.h" // We also have to do some glibc-specific overriding. Some library // routines on RedHat 9 allocate memory using malloc() and free it // using __libc_free() (or vice-versa). Since we provide our own // implementations of malloc/free, we need to make sure that the // __libc_XXX variants (defined as part of glibc) also point to the // same implementations. Since it only matters for redhat, we // do it inside the gcc #ifdef, since redhat uses gcc. // TODO(csilvers): only do this if we detect we're an old enough glibc? #define ALIAS(tc_fn) __attribute__ ((alias (#tc_fn))) extern "C" { void* __libc_malloc(size_t size) ALIAS(tc_malloc); void __libc_free(void* ptr) ALIAS(tc_free); void* __libc_realloc(void* ptr, size_t size) ALIAS(tc_realloc); void* __libc_calloc(size_t n, size_t size) ALIAS(tc_calloc); void __libc_cfree(void* ptr) ALIAS(tc_cfree); void* __libc_memalign(size_t align, size_t s) ALIAS(tc_memalign); void* __libc_valloc(size_t size) ALIAS(tc_valloc); void* __libc_pvalloc(size_t size) ALIAS(tc_pvalloc); int __posix_memalign(void** r, size_t a, size_t s) ALIAS(tc_posix_memalign); } // extern "C" #undef ALIAS #endif // #if defined(__GNUC__) && !defined(__MACH__) // No need to write ReplaceSystemAlloc(); one of the #includes above // did it for us. #endif // TCMALLOC_LIBC_OVERRIDE_GLIBC_INL_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/common.h
.h
12,224
310
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> // // Common definitions for tcmalloc code. #ifndef TCMALLOC_COMMON_H_ #define TCMALLOC_COMMON_H_ #include "config.h" #include <stddef.h> // for size_t #ifdef HAVE_STDINT_H #include <stdint.h> // for uintptr_t, uint64_t #endif #include "internal_logging.h" // for ASSERT, etc #include "base/basictypes.h" // for LIKELY, etc // Type that can hold a page number typedef uintptr_t PageID; // Type that can hold the length of a run of pages typedef uintptr_t Length; //------------------------------------------------------------------- // Configuration //------------------------------------------------------------------- #if defined(TCMALLOC_ALIGN_8BYTES) // Unless we force to use 8 bytes alignment we use an alignment of // at least 16 bytes to statisfy requirements for some SSE types. // Keep in mind when using the 16 bytes alignment you can have a space // waste due alignment of 25%. (eg malloc of 24 bytes will get 32 bytes) static const size_t kMinAlign = 8; #else static const size_t kMinAlign = 16; #endif // Using large pages speeds up the execution at a cost of larger memory use. // Deallocation may speed up by a factor as the page map gets 8x smaller, so // lookups in the page map result in fewer L2 cache misses, which translates to // speedup for application/platform combinations with high L2 cache pressure. // As the number of size classes increases with large pages, we increase // the thread cache allowance to avoid passing more free ranges to and from // central lists. Also, larger pages are less likely to get freed. // These two factors cause a bounded increase in memory use. #if defined(TCMALLOC_PAGE_SIZE_SHIFT) static const size_t kPageShift = TCMALLOC_PAGE_SIZE_SHIFT; #else static const size_t kPageShift = 13; #endif static const size_t kClassSizesMax = 128; static const size_t kMaxThreadCacheSize = 4 << 20; static const size_t kPageSize = 1 << kPageShift; static const size_t kMaxSize = 256 * 1024; static const size_t kAlignment = 8; // For all span-lengths <= kMaxPages we keep an exact-size list in PageHeap. static const size_t kMaxPages = 1 << (20 - kPageShift); // Default bound on the total amount of thread caches. #ifdef TCMALLOC_SMALL_BUT_SLOW // Make the overall thread cache no bigger than that of a single thread // for the small memory footprint case. static const size_t kDefaultOverallThreadCacheSize = kMaxThreadCacheSize; #else static const size_t kDefaultOverallThreadCacheSize = 8u * kMaxThreadCacheSize; #endif // Lower bound on the per-thread cache sizes static const size_t kMinThreadCacheSize = kMaxSize * 2; // The number of bytes one ThreadCache will steal from another when // the first ThreadCache is forced to Scavenge(), delaying the // next call to Scavenge for this thread. static const size_t kStealAmount = 1 << 16; // The number of times that a deallocation can cause a freelist to // go over its max_length() before shrinking max_length(). static const int kMaxOverages = 3; // Maximum length we allow a per-thread free-list to have before we // move objects from it into the corresponding central free-list. We // want this big to avoid locking the central free-list too often. It // should not hurt to make this list somewhat big because the // scavenging code will shrink it down when its contents are not in use. static const int kMaxDynamicFreeListLength = 8192; static const Length kMaxValidPages = (~static_cast<Length>(0)) >> kPageShift; #if __aarch64__ || __x86_64__ || _M_AMD64 || _M_ARM64 // All current x86_64 processors only look at the lower 48 bits in // virtual to physical address translation. The top 16 are all same as // bit 47. And bit 47 value 1 reserved for kernel-space addresses in // practice. So it is actually 47 usable bits from malloc // perspective. This lets us use faster two level page maps on this // architecture. // // There is very similar story on 64-bit arms except it has full 48 // bits for user-space. Because of that, and because in principle OSes // can start giving some of highest-bit-set addresses to user-space, // we don't bother to limit x86 to 47 bits. // // As of now there are published plans to add more bits to x86-64 // virtual address space, but since 48 bits has been norm for long // time and lots of software is relying on it, it will be opt-in from // OS perspective. So we can keep doing "48 bits" at least for now. static const int kAddressBits = (sizeof(void*) < 8 ? (8 * sizeof(void*)) : 48); #else // mipsen and ppcs have more general hardware so we have to support // full 64-bits of addresses. static const int kAddressBits = 8 * sizeof(void*); #endif namespace tcmalloc { // Convert byte size into pages. This won't overflow, but may return // an unreasonably large value if bytes is huge enough. inline Length pages(size_t bytes) { return (bytes >> kPageShift) + ((bytes & (kPageSize - 1)) > 0 ? 1 : 0); } // For larger allocation sizes, we use larger memory alignments to // reduce the number of size classes. int AlignmentForSize(size_t size); // Size-class information + mapping class SizeMap { private: //------------------------------------------------------------------- // Mapping from size to size_class and vice versa //------------------------------------------------------------------- // Sizes <= 1024 have an alignment >= 8. So for such sizes we have an // array indexed by ceil(size/8). Sizes > 1024 have an alignment >= 128. // So for these larger sizes we have an array indexed by ceil(size/128). // // We flatten both logical arrays into one physical array and use // arithmetic to compute an appropriate index. The constants used by // ClassIndex() were selected to make the flattening work. // // Examples: // Size Expression Index // ------------------------------------------------------- // 0 (0 + 7) / 8 0 // 1 (1 + 7) / 8 1 // ... // 1024 (1024 + 7) / 8 128 // 1025 (1025 + 127 + (120<<7)) / 128 129 // ... // 32768 (32768 + 127 + (120<<7)) / 128 376 static const int kMaxSmallSize = 1024; static const size_t kClassArraySize = ((kMaxSize + 127 + (120 << 7)) >> 7) + 1; unsigned char class_array_[kClassArraySize]; static inline size_t SmallSizeClass(size_t s) { return (static_cast<uint32_t>(s) + 7) >> 3; } static inline size_t LargeSizeClass(size_t s) { return (static_cast<uint32_t>(s) + 127 + (120 << 7)) >> 7; } // If size is no more than kMaxSize, compute index of the // class_array[] entry for it, putting the class index in output // parameter idx and returning true. Otherwise return false. static inline bool ATTRIBUTE_ALWAYS_INLINE ClassIndexMaybe(size_t s, uint32* idx) { if (PREDICT_TRUE(s <= kMaxSmallSize)) { *idx = (static_cast<uint32>(s) + 7) >> 3; return true; } else if (s <= kMaxSize) { *idx = (static_cast<uint32>(s) + 127 + (120 << 7)) >> 7; return true; } return false; } // Compute index of the class_array[] entry for a given size static inline size_t ClassIndex(size_t s) { // Use unsigned arithmetic to avoid unnecessary sign extensions. ASSERT(0 <= s); ASSERT(s <= kMaxSize); if (PREDICT_TRUE(s <= kMaxSmallSize)) { return SmallSizeClass(s); } else { return LargeSizeClass(s); } } // Number of objects to move between a per-thread list and a central // list in one shot. We want this to be not too small so we can // amortize the lock overhead for accessing the central list. Making // it too big may temporarily cause unnecessary memory wastage in the // per-thread free list until the scavenger cleans up the list. int num_objects_to_move_[kClassSizesMax]; int NumMoveSize(size_t size); // Mapping from size class to max size storable in that class int32 class_to_size_[kClassSizesMax]; // Mapping from size class to number of pages to allocate at a time size_t class_to_pages_[kClassSizesMax]; public: size_t num_size_classes; // Constructor should do nothing since we rely on explicit Init() // call, which may or may not be called before the constructor runs. SizeMap() { } // Initialize the mapping arrays void Init(); inline int SizeClass(size_t size) { return class_array_[ClassIndex(size)]; } // Check if size is small enough to be representable by a size // class, and if it is, put matching size class into *cl. Returns // true iff matching size class was found. inline bool ATTRIBUTE_ALWAYS_INLINE GetSizeClass(size_t size, uint32* cl) { uint32 idx; if (!ClassIndexMaybe(size, &idx)) { return false; } *cl = class_array_[idx]; return true; } // Get the byte-size for a specified class inline int32 ATTRIBUTE_ALWAYS_INLINE ByteSizeForClass(uint32 cl) { return class_to_size_[cl]; } // Mapping from size class to max size storable in that class inline int32 class_to_size(uint32 cl) { return class_to_size_[cl]; } // Mapping from size class to number of pages to allocate at a time inline size_t class_to_pages(uint32 cl) { return class_to_pages_[cl]; } // Number of objects to move between a per-thread list and a central // list in one shot. We want this to be not too small so we can // amortize the lock overhead for accessing the central list. Making // it too big may temporarily cause unnecessary memory wastage in the // per-thread free list until the scavenger cleans up the list. inline int num_objects_to_move(uint32 cl) { return num_objects_to_move_[cl]; } }; // Allocates "bytes" worth of memory and returns it. Increments // metadata_system_bytes appropriately. May return NULL if allocation // fails. Requires pageheap_lock is held. void* MetaDataAlloc(size_t bytes); // Returns the total number of bytes allocated from the system. // Requires pageheap_lock is held. uint64_t metadata_system_bytes(); // size/depth are made the same size as a pointer so that some generic // code below can conveniently cast them back and forth to void*. static const int kMaxStackDepth = 31; struct StackTrace { uintptr_t size; // Size of object uintptr_t depth; // Number of PC values stored in array below void* stack[kMaxStackDepth]; }; } // namespace tcmalloc #endif // TCMALLOC_COMMON_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/tcmalloc.h
.h
3,011
71
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein <opensource@google.com> // // Some obscure memory-allocation routines may not be declared on all // systems. In those cases, we'll just declare them ourselves. // This file is meant to be used only internally, for unittests. #include <config.h> #ifndef _XOPEN_SOURCE # define _XOPEN_SOURCE 600 // for posix_memalign #endif #include <stdlib.h> // for posix_memalign // FreeBSD has malloc.h, but complains if you use it #if defined(HAVE_MALLOC_H) && !defined(__FreeBSD__) #include <malloc.h> // for memalign, valloc, pvalloc #endif // __THROW is defined in glibc systems. It means, counter-intuitively, // "This function will never throw an exception." It's an optional // optimization tool, but we may need to use it to match glibc prototypes. #ifndef __THROW // I guess we're not on a glibc system # define __THROW // __THROW is just an optimization, so ok to make it "" #endif #if !HAVE_CFREE_SYMBOL extern "C" void cfree(void* ptr) __THROW; #endif #if !HAVE_DECL_POSIX_MEMALIGN extern "C" int posix_memalign(void** ptr, size_t align, size_t size) __THROW; #endif #if !HAVE_DECL_MEMALIGN extern "C" void* memalign(size_t __alignment, size_t __size) __THROW; #endif #if !HAVE_DECL_VALLOC extern "C" void* valloc(size_t __size) __THROW; #endif #if !HAVE_DECL_PVALLOC extern "C" void* pvalloc(size_t __size) __THROW; #endif
Unknown
3D
mcellteam/mcell
libs/gperftools/src/page_heap.cc
.cc
25,233
727
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #include <config.h> #ifdef HAVE_INTTYPES_H #include <inttypes.h> // for PRIuPTR #endif #include <errno.h> // for ENOMEM, errno #include <gperftools/malloc_extension.h> // for MallocRange, etc #include "base/basictypes.h" #include "base/commandlineflags.h" #include "internal_logging.h" // for ASSERT, TCMalloc_Printer, etc #include "page_heap_allocator.h" // for PageHeapAllocator #include "static_vars.h" // for Static #include "system-alloc.h" // for TCMalloc_SystemAlloc, etc DEFINE_double(tcmalloc_release_rate, EnvToDouble("TCMALLOC_RELEASE_RATE", 1.0), "Rate at which we release unused memory to the system. " "Zero means we never release memory back to the system. " "Increase this flag to return memory faster; decrease it " "to return memory slower. Reasonable rates are in the " "range [0,10]"); DEFINE_int64(tcmalloc_heap_limit_mb, EnvToInt("TCMALLOC_HEAP_LIMIT_MB", 0), "Limit total size of the process heap to the " "specified number of MiB. " "When we approach the limit the memory is released " "to the system more aggressively (more minor page faults). " "Zero means to allocate as long as system allows."); namespace tcmalloc { PageHeap::PageHeap() : pagemap_(MetaDataAlloc), scavenge_counter_(0), // Start scavenging at kMaxPages list release_index_(kMaxPages), aggressive_decommit_(false) { COMPILE_ASSERT(kClassSizesMax <= (1 << PageMapCache::kValuebits), valuebits); for (int i = 0; i < kMaxPages; i++) { DLL_Init(&free_[i].normal); DLL_Init(&free_[i].returned); } } Span* PageHeap::SearchFreeAndLargeLists(Length n) { ASSERT(Check()); ASSERT(n > 0); // Find first size >= n that has a non-empty list for (Length s = n; s <= kMaxPages; s++) { Span* ll = &free_[s - 1].normal; // If we're lucky, ll is non-empty, meaning it has a suitable span. if (!DLL_IsEmpty(ll)) { ASSERT(ll->next->location == Span::ON_NORMAL_FREELIST); return Carve(ll->next, n); } // Alternatively, maybe there's a usable returned span. ll = &free_[s - 1].returned; if (!DLL_IsEmpty(ll)) { // We did not call EnsureLimit before, to avoid releasing the span // that will be taken immediately back. // Calling EnsureLimit here is not very expensive, as it fails only if // there is no more normal spans (and it fails efficiently) // or SystemRelease does not work (there is probably no returned spans). if (EnsureLimit(n)) { // ll may have became empty due to coalescing if (!DLL_IsEmpty(ll)) { ASSERT(ll->next->location == Span::ON_RETURNED_FREELIST); return Carve(ll->next, n); } } } } // No luck in free lists, our last chance is in a larger class. return AllocLarge(n); // May be NULL } static const size_t kForcedCoalesceInterval = 128*1024*1024; Span* PageHeap::New(Length n) { ASSERT(Check()); ASSERT(n > 0); Span* result = SearchFreeAndLargeLists(n); if (result != NULL) return result; if (stats_.free_bytes != 0 && stats_.unmapped_bytes != 0 && stats_.free_bytes + stats_.unmapped_bytes >= stats_.system_bytes / 4 && (stats_.system_bytes / kForcedCoalesceInterval != (stats_.system_bytes + (n << kPageShift)) / kForcedCoalesceInterval)) { // We're about to grow heap, but there are lots of free pages. // tcmalloc's design decision to keep unmapped and free spans // separately and never coalesce them means that sometimes there // can be free pages span of sufficient size, but it consists of // "segments" of different type so page heap search cannot find // it. In order to prevent growing heap and wasting memory in such // case we're going to unmap all free pages. So that all free // spans are maximally coalesced. // // We're also limiting 'rate' of going into this path to be at // most once per 128 megs of heap growth. Otherwise programs that // grow heap frequently (and that means by small amount) could be // penalized with higher count of minor page faults. // // See also large_heap_fragmentation_unittest.cc and // https://code.google.com/p/gperftools/issues/detail?id=368 ReleaseAtLeastNPages(static_cast<Length>(0x7fffffff)); // then try again. If we are forced to grow heap because of large // spans fragmentation and not because of problem described above, // then at the very least we've just unmapped free but // insufficiently big large spans back to OS. So in case of really // unlucky memory fragmentation we'll be consuming virtual address // space, but not real memory result = SearchFreeAndLargeLists(n); if (result != NULL) return result; } // Grow the heap and try again. if (!GrowHeap(n)) { ASSERT(stats_.unmapped_bytes+ stats_.committed_bytes==stats_.system_bytes); ASSERT(Check()); // underlying SysAllocator likely set ENOMEM but we can get here // due to EnsureLimit so we set it here too. // // Setting errno to ENOMEM here allows us to avoid dealing with it // in fast-path. errno = ENOMEM; return NULL; } return SearchFreeAndLargeLists(n); } Span* PageHeap::AllocLarge(Length n) { Span *best = NULL; Span *best_normal = NULL; // Create a Span to use as an upper bound. Span bound; bound.start = 0; bound.length = n; // First search the NORMAL spans.. SpanSet::iterator place = large_normal_.upper_bound(SpanPtrWithLength(&bound)); if (place != large_normal_.end()) { best = place->span; best_normal = best; ASSERT(best->location == Span::ON_NORMAL_FREELIST); } // Try to find better fit from RETURNED spans. place = large_returned_.upper_bound(SpanPtrWithLength(&bound)); if (place != large_returned_.end()) { Span *c = place->span; ASSERT(c->location == Span::ON_RETURNED_FREELIST); if (best_normal == NULL || c->length < best->length || (c->length == best->length && c->start < best->start)) best = place->span; } if (best == best_normal) { return best == NULL ? NULL : Carve(best, n); } // best comes from RETURNED set. if (EnsureLimit(n, false)) { return Carve(best, n); } if (EnsureLimit(n, true)) { // best could have been destroyed by coalescing. // best_normal is not a best-fit, and it could be destroyed as well. // We retry, the limit is already ensured: return AllocLarge(n); } // If best_normal existed, EnsureLimit would succeeded: ASSERT(best_normal == NULL); // We are not allowed to take best from returned list. return NULL; } Span* PageHeap::Split(Span* span, Length n) { ASSERT(0 < n); ASSERT(n < span->length); ASSERT(span->location == Span::IN_USE); ASSERT(span->sizeclass == 0); Event(span, 'T', n); const int extra = span->length - n; Span* leftover = NewSpan(span->start + n, extra); ASSERT(leftover->location == Span::IN_USE); Event(leftover, 'U', extra); RecordSpan(leftover); pagemap_.set(span->start + n - 1, span); // Update map from pageid to span span->length = n; return leftover; } void PageHeap::CommitSpan(Span* span) { ++stats_.commit_count; TCMalloc_SystemCommit(reinterpret_cast<void*>(span->start << kPageShift), static_cast<size_t>(span->length << kPageShift)); stats_.committed_bytes += span->length << kPageShift; stats_.total_commit_bytes += (span->length << kPageShift); } bool PageHeap::DecommitSpan(Span* span) { ++stats_.decommit_count; bool rv = TCMalloc_SystemRelease(reinterpret_cast<void*>(span->start << kPageShift), static_cast<size_t>(span->length << kPageShift)); if (rv) { stats_.committed_bytes -= span->length << kPageShift; stats_.total_decommit_bytes += (span->length << kPageShift); } return rv; } Span* PageHeap::Carve(Span* span, Length n) { ASSERT(n > 0); ASSERT(span->location != Span::IN_USE); const int old_location = span->location; RemoveFromFreeList(span); span->location = Span::IN_USE; Event(span, 'A', n); const int extra = span->length - n; ASSERT(extra >= 0); if (extra > 0) { Span* leftover = NewSpan(span->start + n, extra); leftover->location = old_location; Event(leftover, 'S', extra); RecordSpan(leftover); // The previous span of |leftover| was just splitted -- no need to // coalesce them. The next span of |leftover| was not previously coalesced // with |span|, i.e. is NULL or has got location other than |old_location|. #ifndef NDEBUG const PageID p = leftover->start; const Length len = leftover->length; Span* next = GetDescriptor(p+len); ASSERT (next == NULL || next->location == Span::IN_USE || next->location != leftover->location); #endif PrependToFreeList(leftover); // Skip coalescing - no candidates possible span->length = n; pagemap_.set(span->start + n - 1, span); } ASSERT(Check()); if (old_location == Span::ON_RETURNED_FREELIST) { // We need to recommit this address space. CommitSpan(span); } ASSERT(span->location == Span::IN_USE); ASSERT(span->length == n); ASSERT(stats_.unmapped_bytes+ stats_.committed_bytes==stats_.system_bytes); return span; } void PageHeap::Delete(Span* span) { ASSERT(Check()); ASSERT(span->location == Span::IN_USE); ASSERT(span->length > 0); ASSERT(GetDescriptor(span->start) == span); ASSERT(GetDescriptor(span->start + span->length - 1) == span); const Length n = span->length; span->sizeclass = 0; span->sample = 0; span->location = Span::ON_NORMAL_FREELIST; Event(span, 'D', span->length); MergeIntoFreeList(span); // Coalesces if possible IncrementalScavenge(n); ASSERT(stats_.unmapped_bytes+ stats_.committed_bytes==stats_.system_bytes); ASSERT(Check()); } // Given span we're about to free and other span (still on free list), // checks if 'other' span is mergable with 'span'. If it is, removes // other span from free list, performs aggressive decommit if // necessary and returns 'other' span. Otherwise 'other' span cannot // be merged and is left untouched. In that case NULL is returned. Span* PageHeap::CheckAndHandlePreMerge(Span* span, Span* other) { if (other == NULL) { return other; } // if we're in aggressive decommit mode and span is decommitted, // then we try to decommit adjacent span. if (aggressive_decommit_ && other->location == Span::ON_NORMAL_FREELIST && span->location == Span::ON_RETURNED_FREELIST) { bool worked = DecommitSpan(other); if (!worked) { return NULL; } } else if (other->location != span->location) { return NULL; } RemoveFromFreeList(other); return other; } void PageHeap::MergeIntoFreeList(Span* span) { ASSERT(span->location != Span::IN_USE); // Coalesce -- we guarantee that "p" != 0, so no bounds checking // necessary. We do not bother resetting the stale pagemap // entries for the pieces we are merging together because we only // care about the pagemap entries for the boundaries. // // Note: depending on aggressive_decommit_ mode we allow only // similar spans to be coalesced. // // The following applies if aggressive_decommit_ is enabled: // // TODO(jar): "Always decommit" causes some extra calls to commit when we are // called in GrowHeap() during an allocation :-/. We need to eval the cost of // that oscillation, and possibly do something to reduce it. // TODO(jar): We need a better strategy for deciding to commit, or decommit, // based on memory usage and free heap sizes. const PageID p = span->start; const Length n = span->length; if (aggressive_decommit_ && span->location == Span::ON_NORMAL_FREELIST) { if (DecommitSpan(span)) { span->location = Span::ON_RETURNED_FREELIST; } } Span* prev = CheckAndHandlePreMerge(span, GetDescriptor(p-1)); if (prev != NULL) { // Merge preceding span into this span ASSERT(prev->start + prev->length == p); const Length len = prev->length; DeleteSpan(prev); span->start -= len; span->length += len; pagemap_.set(span->start, span); Event(span, 'L', len); } Span* next = CheckAndHandlePreMerge(span, GetDescriptor(p+n)); if (next != NULL) { // Merge next span into this span ASSERT(next->start == p+n); const Length len = next->length; DeleteSpan(next); span->length += len; pagemap_.set(span->start + span->length - 1, span); Event(span, 'R', len); } PrependToFreeList(span); } void PageHeap::PrependToFreeList(Span* span) { ASSERT(span->location != Span::IN_USE); if (span->location == Span::ON_NORMAL_FREELIST) stats_.free_bytes += (span->length << kPageShift); else stats_.unmapped_bytes += (span->length << kPageShift); if (span->length > kMaxPages) { SpanSet *set = &large_normal_; if (span->location == Span::ON_RETURNED_FREELIST) set = &large_returned_; std::pair<SpanSet::iterator, bool> p = set->insert(SpanPtrWithLength(span)); ASSERT(p.second); // We never have duplicates since span->start is unique. span->SetSpanSetIterator(p.first); return; } SpanList* list = &free_[span->length - 1]; if (span->location == Span::ON_NORMAL_FREELIST) { DLL_Prepend(&list->normal, span); } else { DLL_Prepend(&list->returned, span); } } void PageHeap::RemoveFromFreeList(Span* span) { ASSERT(span->location != Span::IN_USE); if (span->location == Span::ON_NORMAL_FREELIST) { stats_.free_bytes -= (span->length << kPageShift); } else { stats_.unmapped_bytes -= (span->length << kPageShift); } if (span->length > kMaxPages) { SpanSet *set = &large_normal_; if (span->location == Span::ON_RETURNED_FREELIST) set = &large_returned_; SpanSet::iterator iter = span->ExtractSpanSetIterator(); ASSERT(iter->span == span); ASSERT(set->find(SpanPtrWithLength(span)) == iter); set->erase(iter); } else { DLL_Remove(span); } } void PageHeap::IncrementalScavenge(Length n) { // Fast path; not yet time to release memory scavenge_counter_ -= n; if (scavenge_counter_ >= 0) return; // Not yet time to scavenge const double rate = FLAGS_tcmalloc_release_rate; if (rate <= 1e-6) { // Tiny release rate means that releasing is disabled. scavenge_counter_ = kDefaultReleaseDelay; return; } ++stats_.scavenge_count; Length released_pages = ReleaseAtLeastNPages(1); if (released_pages == 0) { // Nothing to scavenge, delay for a while. scavenge_counter_ = kDefaultReleaseDelay; } else { // Compute how long to wait until we return memory. // FLAGS_tcmalloc_release_rate==1 means wait for 1000 pages // after releasing one page. const double mult = 1000.0 / rate; double wait = mult * static_cast<double>(released_pages); if (wait > kMaxReleaseDelay) { // Avoid overflow and bound to reasonable range. wait = kMaxReleaseDelay; } scavenge_counter_ = static_cast<int64_t>(wait); } } Length PageHeap::ReleaseSpan(Span* s) { ASSERT(s->location == Span::ON_NORMAL_FREELIST); if (DecommitSpan(s)) { RemoveFromFreeList(s); const Length n = s->length; s->location = Span::ON_RETURNED_FREELIST; MergeIntoFreeList(s); // Coalesces if possible. return n; } return 0; } Length PageHeap::ReleaseAtLeastNPages(Length num_pages) { Length released_pages = 0; // Round robin through the lists of free spans, releasing a // span from each list. Stop after releasing at least num_pages // or when there is nothing more to release. while (released_pages < num_pages && stats_.free_bytes > 0) { for (int i = 0; i < kMaxPages+1 && released_pages < num_pages; i++, release_index_++) { Span *s; if (release_index_ > kMaxPages) release_index_ = 0; if (release_index_ == kMaxPages) { if (large_normal_.empty()) { continue; } s = (large_normal_.begin())->span; } else { SpanList* slist = &free_[release_index_]; if (DLL_IsEmpty(&slist->normal)) { continue; } s = slist->normal.prev; } // TODO(todd) if the remaining number of pages to release // is significantly smaller than s->length, and s is on the // large freelist, should we carve s instead of releasing? // the whole thing? Length released_len = ReleaseSpan(s); // Some systems do not support release if (released_len == 0) return released_pages; released_pages += released_len; } } return released_pages; } bool PageHeap::EnsureLimit(Length n, bool withRelease) { Length limit = (FLAGS_tcmalloc_heap_limit_mb*1024*1024) >> kPageShift; if (limit == 0) return true; //there is no limit // We do not use stats_.system_bytes because it does not take // MetaDataAllocs into account. Length takenPages = TCMalloc_SystemTaken >> kPageShift; //XXX takenPages may be slightly bigger than limit for two reasons: //* MetaDataAllocs ignore the limit (it is not easy to handle // out of memory there) //* sys_alloc may round allocation up to huge page size, // although smaller limit was ensured ASSERT(takenPages >= stats_.unmapped_bytes >> kPageShift); takenPages -= stats_.unmapped_bytes >> kPageShift; if (takenPages + n > limit && withRelease) { takenPages -= ReleaseAtLeastNPages(takenPages + n - limit); } return takenPages + n <= limit; } void PageHeap::RegisterSizeClass(Span* span, uint32 sc) { // Associate span object with all interior pages as well ASSERT(span->location == Span::IN_USE); ASSERT(GetDescriptor(span->start) == span); ASSERT(GetDescriptor(span->start+span->length-1) == span); Event(span, 'C', sc); span->sizeclass = sc; for (Length i = 1; i < span->length-1; i++) { pagemap_.set(span->start+i, span); } } void PageHeap::GetSmallSpanStats(SmallSpanStats* result) { for (int i = 0; i < kMaxPages; i++) { result->normal_length[i] = DLL_Length(&free_[i].normal); result->returned_length[i] = DLL_Length(&free_[i].returned); } } void PageHeap::GetLargeSpanStats(LargeSpanStats* result) { result->spans = 0; result->normal_pages = 0; result->returned_pages = 0; for (SpanSet::iterator it = large_normal_.begin(); it != large_normal_.end(); ++it) { result->normal_pages += it->length; result->spans++; } for (SpanSet::iterator it = large_returned_.begin(); it != large_returned_.end(); ++it) { result->returned_pages += it->length; result->spans++; } } bool PageHeap::GetNextRange(PageID start, base::MallocRange* r) { Span* span = reinterpret_cast<Span*>(pagemap_.Next(start)); if (span == NULL) { return false; } r->address = span->start << kPageShift; r->length = span->length << kPageShift; r->fraction = 0; switch (span->location) { case Span::IN_USE: r->type = base::MallocRange::INUSE; r->fraction = 1; if (span->sizeclass > 0) { // Only some of the objects in this span may be in use. const size_t osize = Static::sizemap()->class_to_size(span->sizeclass); r->fraction = (1.0 * osize * span->refcount) / r->length; } break; case Span::ON_NORMAL_FREELIST: r->type = base::MallocRange::FREE; break; case Span::ON_RETURNED_FREELIST: r->type = base::MallocRange::UNMAPPED; break; default: r->type = base::MallocRange::UNKNOWN; break; } return true; } static void RecordGrowth(size_t growth) { StackTrace* t = Static::stacktrace_allocator()->New(); t->depth = GetStackTrace(t->stack, kMaxStackDepth-1, 3); t->size = growth; t->stack[kMaxStackDepth-1] = reinterpret_cast<void*>(Static::growth_stacks()); Static::set_growth_stacks(t); } bool PageHeap::GrowHeap(Length n) { ASSERT(kMaxPages >= kMinSystemAlloc); if (n > kMaxValidPages) return false; Length ask = (n>kMinSystemAlloc) ? n : static_cast<Length>(kMinSystemAlloc); size_t actual_size; void* ptr = NULL; if (EnsureLimit(ask)) { ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize); } if (ptr == NULL) { if (n < ask) { // Try growing just "n" pages ask = n; if (EnsureLimit(ask)) { ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize); } } if (ptr == NULL) return false; } ask = actual_size >> kPageShift; RecordGrowth(ask << kPageShift); ++stats_.reserve_count; ++stats_.commit_count; uint64_t old_system_bytes = stats_.system_bytes; stats_.system_bytes += (ask << kPageShift); stats_.committed_bytes += (ask << kPageShift); stats_.total_commit_bytes += (ask << kPageShift); stats_.total_reserve_bytes += (ask << kPageShift); const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift; ASSERT(p > 0); // If we have already a lot of pages allocated, just pre allocate a bunch of // memory for the page map. This prevents fragmentation by pagemap metadata // when a program keeps allocating and freeing large blocks. if (old_system_bytes < kPageMapBigAllocationThreshold && stats_.system_bytes >= kPageMapBigAllocationThreshold) { pagemap_.PreallocateMoreMemory(); } // Make sure pagemap_ has entries for all of the new pages. // Plus ensure one before and one after so coalescing code // does not need bounds-checking. if (pagemap_.Ensure(p-1, ask+2)) { // Pretend the new area is allocated and then Delete() it to cause // any necessary coalescing to occur. Span* span = NewSpan(p, ask); RecordSpan(span); Delete(span); ASSERT(stats_.unmapped_bytes+ stats_.committed_bytes==stats_.system_bytes); ASSERT(Check()); return true; } else { // We could not allocate memory within "pagemap_" // TODO: Once we can return memory to the system, return the new span return false; } } bool PageHeap::Check() { return true; } bool PageHeap::CheckExpensive() { bool result = Check(); CheckSet(&large_normal_, kMaxPages + 1, Span::ON_NORMAL_FREELIST); CheckSet(&large_returned_, kMaxPages + 1, Span::ON_RETURNED_FREELIST); for (int s = 1; s <= kMaxPages; s++) { CheckList(&free_[s - 1].normal, s, s, Span::ON_NORMAL_FREELIST); CheckList(&free_[s - 1].returned, s, s, Span::ON_RETURNED_FREELIST); } return result; } bool PageHeap::CheckList(Span* list, Length min_pages, Length max_pages, int freelist) { for (Span* s = list->next; s != list; s = s->next) { CHECK_CONDITION(s->location == freelist); // NORMAL or RETURNED CHECK_CONDITION(s->length >= min_pages); CHECK_CONDITION(s->length <= max_pages); CHECK_CONDITION(GetDescriptor(s->start) == s); CHECK_CONDITION(GetDescriptor(s->start+s->length-1) == s); } return true; } bool PageHeap::CheckSet(SpanSet* spanset, Length min_pages,int freelist) { for (SpanSet::iterator it = spanset->begin(); it != spanset->end(); ++it) { Span* s = it->span; CHECK_CONDITION(s->length == it->length); CHECK_CONDITION(s->location == freelist); // NORMAL or RETURNED CHECK_CONDITION(s->length >= min_pages); CHECK_CONDITION(GetDescriptor(s->start) == s); CHECK_CONDITION(GetDescriptor(s->start+s->length-1) == s); } return true; } } // namespace tcmalloc
Unknown
3D
mcellteam/mcell
libs/gperftools/src/fake_stacktrace_scope.cc
.cc
1,816
40
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2014, gperftools Contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "base/basictypes.h" namespace tcmalloc { ATTRIBUTE_WEAK bool EnterStacktraceScope(void) { return true; } ATTRIBUTE_WEAK void LeaveStacktraceScope(void) { } }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/static_vars.cc
.cc
5,714
153
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Ken Ashcraft <opensource@google.com> #include <config.h> #include "static_vars.h" #include <stddef.h> // for NULL #include <new> // for operator new #ifdef HAVE_PTHREAD #include <pthread.h> // for pthread_atfork #endif #include "internal_logging.h" // for CHECK_CONDITION #include "common.h" #include "sampler.h" // for Sampler #include "getenv_safe.h" // TCMallocGetenvSafe #include "base/googleinit.h" #include "maybe_threads.h" namespace tcmalloc { #if defined(HAVE_FORK) && defined(HAVE_PTHREAD) // These following two functions are registered via pthread_atfork to make // sure the central_cache locks remain in a consisten state in the forked // version of the thread. void CentralCacheLockAll() { Static::pageheap_lock()->Lock(); for (int i = 0; i < Static::num_size_classes(); ++i) Static::central_cache()[i].Lock(); } void CentralCacheUnlockAll() { for (int i = 0; i < Static::num_size_classes(); ++i) Static::central_cache()[i].Unlock(); Static::pageheap_lock()->Unlock(); } #endif bool Static::inited_; SpinLock Static::pageheap_lock_(SpinLock::LINKER_INITIALIZED); SizeMap Static::sizemap_; CentralFreeListPadded Static::central_cache_[kClassSizesMax]; PageHeapAllocator<Span> Static::span_allocator_; PageHeapAllocator<StackTrace> Static::stacktrace_allocator_; Span Static::sampled_objects_; StackTrace* Static::growth_stacks_ = NULL; Static::PageHeapStorage Static::pageheap_; void Static::InitStaticVars() { sizemap_.Init(); span_allocator_.Init(); span_allocator_.New(); // Reduce cache conflicts span_allocator_.New(); // Reduce cache conflicts stacktrace_allocator_.Init(); // Do a bit of sanitizing: make sure central_cache is aligned properly CHECK_CONDITION((sizeof(central_cache_[0]) % 64) == 0); for (int i = 0; i < num_size_classes(); ++i) { central_cache_[i].Init(i); } new (&pageheap_.memory) PageHeap; #if defined(ENABLE_AGGRESSIVE_DECOMMIT_BY_DEFAULT) const bool kDefaultAggressiveDecommit = true; #else const bool kDefaultAggressiveDecommit = false; #endif bool aggressive_decommit = tcmalloc::commandlineflags::StringToBool( TCMallocGetenvSafe("TCMALLOC_AGGRESSIVE_DECOMMIT"), kDefaultAggressiveDecommit); pageheap()->SetAggressiveDecommit(aggressive_decommit); inited_ = true; DLL_Init(&sampled_objects_); } void Static::InitLateMaybeRecursive() { #if defined(HAVE_FORK) && defined(HAVE_PTHREAD) \ && !defined(__APPLE__) && !defined(TCMALLOC_NO_ATFORK) // OSX has it's own way of handling atfork in malloc (see // libc_override_osx.h). // // For other OSes we do pthread_atfork even if standard seemingly // discourages pthread_atfork, asking apps to do only // async-signal-safe calls between fork and exec. // // We're deliberately attempting to register atfork handlers as part // of malloc initialization. So very early. This ensures that our // handler is called last and that means fork will try to grab // tcmalloc locks last avoiding possible issues with many other // locks that are held around calls to malloc. I.e. if we don't do // that, fork() grabbing malloc lock before such other lock would be // prone to deadlock, if some other thread holds other lock and // calls malloc. // // We still leave some way of disabling it via // -DTCMALLOC_NO_ATFORK. It looks like on glibc even with fully // static binaries malloc is really initialized very early. But I // can see how combination of static linking and other libc-s could // be less fortunate and allow some early app constructors to run // before malloc is ever called. perftools_pthread_atfork( CentralCacheLockAll, // parent calls before fork CentralCacheUnlockAll, // parent calls after fork CentralCacheUnlockAll); // child calls after fork #endif #ifndef NDEBUG // pthread_atfork above may malloc sometimes. Lets ensure we test // that malloc works from here. free(malloc(1)); #endif } } // namespace tcmalloc
Unknown
3D
mcellteam/mcell
libs/gperftools/src/internal_logging.h
.h
5,101
145
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> // // Internal logging and related utility routines. #ifndef TCMALLOC_INTERNAL_LOGGING_H_ #define TCMALLOC_INTERNAL_LOGGING_H_ #include <config.h> #include <stddef.h> // for size_t #if defined HAVE_STDINT_H #include <stdint.h> #elif defined HAVE_INTTYPES_H #include <inttypes.h> #else #include <sys/types.h> #endif //------------------------------------------------------------------- // Utility routines //------------------------------------------------------------------- // Safe logging helper: we write directly to the stderr file // descriptor and avoid FILE buffering because that may invoke // malloc(). // // Example: // Log(kLog, __FILE__, __LINE__, "error", bytes); namespace tcmalloc { enum LogMode { kLog, // Just print the message kCrash, // Print the message and crash kCrashWithStats // Print the message, some stats, and crash }; class Logger; // A LogItem holds any of the argument types that can be passed to Log() class LogItem { public: LogItem() : tag_(kEnd) { } LogItem(const char* v) : tag_(kStr) { u_.str = v; } LogItem(int v) : tag_(kSigned) { u_.snum = v; } LogItem(long v) : tag_(kSigned) { u_.snum = v; } LogItem(long long v) : tag_(kSigned) { u_.snum = v; } LogItem(unsigned int v) : tag_(kUnsigned) { u_.unum = v; } LogItem(unsigned long v) : tag_(kUnsigned) { u_.unum = v; } LogItem(unsigned long long v) : tag_(kUnsigned) { u_.unum = v; } LogItem(const void* v) : tag_(kPtr) { u_.ptr = v; } private: friend class Logger; enum Tag { kStr, kSigned, kUnsigned, kPtr, kEnd }; Tag tag_; union { const char* str; const void* ptr; int64_t snum; uint64_t unum; } u_; }; extern PERFTOOLS_DLL_DECL void Log(LogMode mode, const char* filename, int line, LogItem a, LogItem b = LogItem(), LogItem c = LogItem(), LogItem d = LogItem()); // Tests can override this function to collect logging messages. extern PERFTOOLS_DLL_DECL void (*log_message_writer)(const char* msg, int length); } // end tcmalloc namespace // Like assert(), but executed even in NDEBUG mode #undef CHECK_CONDITION #define CHECK_CONDITION(cond) \ do { \ if (!(cond)) { \ ::tcmalloc::Log(::tcmalloc::kCrash, __FILE__, __LINE__, #cond); \ } \ } while (0) // Our own version of assert() so we can avoid hanging by trying to do // all kinds of goofy printing while holding the malloc lock. #ifndef NDEBUG #define ASSERT(cond) CHECK_CONDITION(cond) #else #define ASSERT(cond) ((void) 0) #endif // Print into buffer class TCMalloc_Printer { private: char* buf_; // Where should we write next int left_; // Space left in buffer (including space for \0) public: // REQUIRES: "length > 0" TCMalloc_Printer(char* buf, int length) : buf_(buf), left_(length) { buf[0] = '\0'; } void printf(const char* format, ...) #ifdef HAVE___ATTRIBUTE__ __attribute__ ((__format__ (__printf__, 2, 3))) #endif ; }; #endif // TCMALLOC_INTERNAL_LOGGING_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_powerpc-darwin-inl.h
.h
6,968
163
// Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Produce stack trace. ABI documentation reference can be found at: // * PowerPC32 ABI: https://www.power.org/documentation/ // power-architecture-32-bit-abi-supplement-1-0-embeddedlinuxunified/ // * PowerPC64 ABI: // http://www.linux-foundation.org/spec/ELF/ppc64/PPC-elf64abi-1.9.html#STACK #ifndef BASE_STACKTRACE_POWERPC_INL_H_ #define BASE_STACKTRACE_POWERPC_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include <stdint.h> // for uintptr_t #include <stdlib.h> // for NULL #include <gperftools/stacktrace.h> // Given a pointer to a stack frame, locate and return the calling // stackframe, or return NULL if no stackframe can be found. Perform sanity // checks (the strictness of which is controlled by the boolean parameter // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. template<bool STRICT_UNWINDING> static void **NextStackFrame(void **old_sp) { void **new_sp = (void **) *old_sp; // Check that the transition from frame pointer old_sp to frame // pointer new_sp isn't clearly bogus if (STRICT_UNWINDING) { // With the stack growing downwards, older stack frame must be // at a greater address that the current one. if (new_sp <= old_sp) return NULL; // Assume stack frames larger than 100,000 bytes are bogus. if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return NULL; } else { // In the non-strict mode, allow discontiguous stack frames. // (alternate-signal-stacks for example). if (new_sp == old_sp) return NULL; // And allow frames upto about 1MB. if ((new_sp > old_sp) && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return NULL; } if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return NULL; return new_sp; } // This ensures that GetStackTrace stes up the Link Register properly. void StacktracePowerPCDummyFunction() __attribute__((noinline)); void StacktracePowerPCDummyFunction() { __asm__ volatile(""); } #endif // BASE_STACKTRACE_POWERPC_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) int GET_STACK_TRACE_OR_FRAMES { void **sp; // Apple OS X uses an old version of gnu as -- both Darwin 7.9.0 (Panther) // and Darwin 8.8.1 (Tiger) use as 1.38. This means we have to use a // different asm syntax. I don't know quite the best way to discriminate // systems using the old as from the new one; I've gone with __APPLE__. // TODO(csilvers): use autoconf instead, to look for 'as --version' == 1 or 2 #ifdef __FreeBSD__ __asm__ volatile ("mr %0,1" : "=r" (sp)); #else __asm__ volatile ("mr %0,r1" : "=r" (sp)); #endif // On PowerPC, the "Link Register" or "Link Record" (LR), is a stack // entry that holds the return address of the subroutine call (what // instruction we run after our function finishes). This is the // same as the stack-pointer of our parent routine, which is what we // want here. While the compiler will always(?) set up LR for // subroutine calls, it may not for leaf functions (such as this one). // This routine forces the compiler (at least gcc) to push it anyway. StacktracePowerPCDummyFunction(); #if IS_STACK_FRAMES // Note we do *not* increment skip_count here for the SYSV ABI. If // we did, the list of stack frames wouldn't properly match up with // the list of return addresses. Note this means the top pc entry // is probably bogus for linux/ppc (and other SYSV-ABI systems). #else // The LR save area is used by the callee, so the top entry is bogus. skip_count++; #endif int n = 0; while (sp && n < max_depth) { // The GetStackFrames routine is called when we are in some // informational context (the failure signal handler for example). // Use the non-strict unwinding rules to produce a stack trace // that is as complete as possible (even if it contains a few // bogus entries in some rare cases). void **next_sp = NextStackFrame<!IS_STACK_FRAMES>(sp); if (skip_count > 0) { skip_count--; } else { // PowerPC has 3 main ABIs, which say where in the stack the // Link Register is. For DARWIN and AIX (used by apple and // linux ppc64), it's in sp[2]. For SYSV (used by linux ppc), // it's in sp[1]. #if defined(__PPC64__) // This check is in case the compiler doesn't define _CALL_AIX/etc. result[n] = *(sp+2); #elif defined(__linux) // This check is in case the compiler doesn't define _CALL_SYSV. result[n] = *(sp+1); #endif #if IS_STACK_FRAMES if (next_sp > sp) { sizes[n] = (uintptr_t)next_sp - (uintptr_t)sp; } else { // A frame-size of 0 is used to indicate unknown frame size. sizes[n] = 0; } #endif n++; } sp = next_sp; } return n; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/sampler.h
.h
9,703
233
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Daniel Ford #ifndef TCMALLOC_SAMPLER_H_ #define TCMALLOC_SAMPLER_H_ #include "config.h" #include <stddef.h> // for size_t #ifdef HAVE_STDINT_H #include <stdint.h> // for uint64_t, uint32_t, int32_t #endif #include <string.h> // for memcpy #include "base/basictypes.h" // for ASSERT #include "internal_logging.h" // for ASSERT #include "static_vars.h" namespace tcmalloc { //------------------------------------------------------------------- // Sampler to decide when to create a sample trace for an allocation // Not thread safe: Each thread should have it's own sampler object. // Caller must use external synchronization if used // from multiple threads. // // With 512K average sample step (the default): // the probability of sampling a 4K allocation is about 0.00778 // the probability of sampling a 1MB allocation is about 0.865 // the probability of sampling a 1GB allocation is about 1.00000 // In general, the probablity of sampling is an allocation of size X // given a flag value of Y (default 1M) is: // 1 - e^(-X/Y) // // With 128K average sample step: // the probability of sampling a 1MB allocation is about 0.99966 // the probability of sampling a 1GB allocation is about 1.0 // (about 1 - 2**(-26)) // With 1M average sample step: // the probability of sampling a 4K allocation is about 0.00390 // the probability of sampling a 1MB allocation is about 0.632 // the probability of sampling a 1GB allocation is about 1.0 // // The sampler works by representing memory as a long stream from // which allocations are taken. Some of the bytes in this stream are // marked and if an allocation includes a marked byte then it is // sampled. Bytes are marked according to a Poisson point process // with each byte being marked independently with probability // p = 1/tcmalloc_sample_parameter. This makes the probability // of sampling an allocation of X bytes equal to the CDF of // a geometric with mean tcmalloc_sample_parameter. (ie. the // probability that at least one byte in the range is marked). This // is accurately given by the CDF of the corresponding exponential // distribution : 1 - e^(-X/tcmalloc_sample_parameter_) // Independence of the byte marking ensures independence of // the sampling of each allocation. // // This scheme is implemented by noting that, starting from any // fixed place, the number of bytes until the next marked byte // is geometrically distributed. This number is recorded as // bytes_until_sample_. Every allocation subtracts from this // number until it is less than 0. When this happens the current // allocation is sampled. // // When an allocation occurs, bytes_until_sample_ is reset to // a new independtly sampled geometric number of bytes. The // memoryless property of the point process means that this may // be taken as the number of bytes after the end of the current // allocation until the next marked byte. This ensures that // very large allocations which would intersect many marked bytes // only result in a single call to PickNextSamplingPoint. //------------------------------------------------------------------- class SamplerTest; class PERFTOOLS_DLL_DECL Sampler { public: constexpr Sampler() {} // Initialize this sampler. void Init(uint64_t seed); // Record allocation of "k" bytes. Return true if no further work // is need, and false if allocation needed to be sampled. bool RecordAllocation(size_t k); // Same as above (but faster), except: // a) REQUIRES(k < std::numeric_limits<ssize_t>::max()) // b) if this returns false, you must call RecordAllocation // to confirm if sampling truly needed. // // The point of this function is to only deal with common case of no // sampling and let caller (which is in malloc fast-path) to // "escalate" to fuller and slower logic only if necessary. bool TryRecordAllocationFast(size_t k); // Generate a geometric with mean 512K (or FLAG_tcmalloc_sample_parameter) ssize_t PickNextSamplingPoint(); // Returns the current sample period static int GetSamplePeriod(); // The following are public for the purposes of testing static uint64_t NextRandom(uint64_t rnd_); // Returns the next prng value // C++03 requires that types stored in TLS be POD. As a result, you must // initialize these members to {0, 0, false} before using this class! // // TODO(ahh): C++11 support will let us make these private. // Bytes until we sample next. // // More specifically when bytes_until_sample_ is X, we can allocate // X bytes without triggering sampling; on the (X+1)th allocated // byte, the containing allocation will be sampled. // // Always non-negative with only very brief exceptions (see // DecrementFast{,Finish}, so casting to size_t is ok. private: friend class SamplerTest; bool RecordAllocationSlow(size_t k); ssize_t bytes_until_sample_{}; uint64_t rnd_{}; // Cheap random number generator bool initialized_{}; }; inline bool Sampler::RecordAllocation(size_t k) { // The first time we enter this function we expect bytes_until_sample_ // to be zero, and we must call SampleAllocationSlow() to ensure // proper initialization of static vars. ASSERT(Static::IsInited() || bytes_until_sample_ == 0); // Note that we have to deal with arbitrarily large values of k // here. Thus we're upcasting bytes_until_sample_ to unsigned rather // than the other way around. And this is why this code cannot be // merged with DecrementFast code below. if (static_cast<size_t>(bytes_until_sample_) < k) { bool result = RecordAllocationSlow(k); ASSERT(Static::IsInited()); return result; } else { bytes_until_sample_ -= k; ASSERT(Static::IsInited()); return true; } } inline bool Sampler::TryRecordAllocationFast(size_t k) { // For efficiency reason, we're testing bytes_until_sample_ after // decrementing it by k. This allows compiler to do sub <reg>, <mem> // followed by conditional jump on sign. But it is correct only if k // is actually smaller than largest ssize_t value. Otherwise // converting k to signed value overflows. // // It would be great for generated code to be sub <reg>, <mem> // followed by conditional jump on 'carry', which would work for // arbitrary values of k, but there seem to be no way to express // that in C++. // // Our API contract explicitly states that only small values of k // are permitted. And thus it makes sense to assert on that. ASSERT(static_cast<ssize_t>(k) >= 0); bytes_until_sample_ -= static_cast<ssize_t>(k); if (PREDICT_FALSE(bytes_until_sample_ < 0)) { // Note, we undo sampling counter update, since we're not actually // handling slow path in the "needs sampling" case (calling // RecordAllocationSlow to reset counter). And we do that in order // to avoid non-tail calls in malloc fast-path. See also comments // on declaration inside Sampler class. // // volatile is used here to improve compiler's choice of // instuctions. We know that this path is very rare and that there // is no need to keep previous value of bytes_until_sample_ in // register. This helps compiler generate slightly more efficient // sub <reg>, <mem> instruction for subtraction above. volatile ssize_t *ptr = const_cast<volatile ssize_t *>(&bytes_until_sample_); *ptr += k; return false; } return true; } // Inline functions which are public for testing purposes // Returns the next prng value. // pRNG is: aX+b mod c with a = 0x5DEECE66D, b = 0xB, c = 1<<48 // This is the lrand64 generator. inline uint64_t Sampler::NextRandom(uint64_t rnd) { const uint64_t prng_mult = 0x5DEECE66DULL; const uint64_t prng_add = 0xB; const uint64_t prng_mod_power = 48; const uint64_t prng_mod_mask = ~((~static_cast<uint64_t>(0)) << prng_mod_power); return (prng_mult * rnd + prng_add) & prng_mod_mask; } } // namespace tcmalloc #endif // TCMALLOC_SAMPLER_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/libc_override_gcc_and_weak.h
.h
9,312
245
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Craig Silverstein <opensource@google.com> // // Used to override malloc routines on systems that define the // memory allocation routines to be weak symbols in their libc // (almost all unix-based systems are like this), on gcc, which // suppports the 'alias' attribute. #ifndef TCMALLOC_LIBC_OVERRIDE_GCC_AND_WEAK_INL_H_ #define TCMALLOC_LIBC_OVERRIDE_GCC_AND_WEAK_INL_H_ #ifdef HAVE_SYS_CDEFS_H #include <sys/cdefs.h> // for __THROW #endif #include <gperftools/tcmalloc.h> #include "getenv_safe.h" // TCMallocGetenvSafe #include "base/commandlineflags.h" #ifndef __THROW // I guess we're not on a glibc-like system # define __THROW // __THROW is just an optimization, so ok to make it "" #endif #ifndef __GNUC__ # error libc_override_gcc_and_weak.h is for gcc distributions only. #endif #define ALIAS(tc_fn) __attribute__ ((alias (#tc_fn), used)) void* operator new(size_t size) CPP_BADALLOC ALIAS(tc_new); void operator delete(void* p) CPP_NOTHROW ALIAS(tc_delete); void* operator new[](size_t size) CPP_BADALLOC ALIAS(tc_newarray); void operator delete[](void* p) CPP_NOTHROW ALIAS(tc_deletearray); void* operator new(size_t size, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_new_nothrow); void* operator new[](size_t size, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_newarray_nothrow); void operator delete(void* p, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_delete_nothrow); void operator delete[](void* p, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_deletearray_nothrow); #if defined(ENABLE_SIZED_DELETE) void operator delete(void *p, size_t size) CPP_NOTHROW ALIAS(tc_delete_sized); void operator delete[](void *p, size_t size) CPP_NOTHROW ALIAS(tc_deletearray_sized); #elif defined(ENABLE_DYNAMIC_SIZED_DELETE) && \ (__GNUC__ * 100 + __GNUC_MINOR__) >= 405 static void delegate_sized_delete(void *p, size_t s) { (operator delete)(p); } static void delegate_sized_deletearray(void *p, size_t s) { (operator delete[])(p); } extern "C" __attribute__((weak)) int tcmalloc_sized_delete_enabled(void); static bool sized_delete_enabled(void) { if (tcmalloc_sized_delete_enabled != 0) { return !!tcmalloc_sized_delete_enabled(); } const char *flag = TCMallocGetenvSafe("TCMALLOC_ENABLE_SIZED_DELETE"); return tcmalloc::commandlineflags::StringToBool(flag, false); } extern "C" { static void *resolve_delete_sized(void) { if (sized_delete_enabled()) { return reinterpret_cast<void *>(tc_delete_sized); } return reinterpret_cast<void *>(delegate_sized_delete); } static void *resolve_deletearray_sized(void) { if (sized_delete_enabled()) { return reinterpret_cast<void *>(tc_deletearray_sized); } return reinterpret_cast<void *>(delegate_sized_deletearray); } } void operator delete(void *p, size_t size) CPP_NOTHROW __attribute__((ifunc("resolve_delete_sized"))); void operator delete[](void *p, size_t size) CPP_NOTHROW __attribute__((ifunc("resolve_deletearray_sized"))); #else /* !ENABLE_SIZED_DELETE && !ENABLE_DYN_SIZED_DELETE */ void operator delete(void *p, size_t size) CPP_NOTHROW ALIAS(tc_delete_sized); void operator delete[](void *p, size_t size) CPP_NOTHROW ALIAS(tc_deletearray_sized); #endif /* !ENABLE_SIZED_DELETE && !ENABLE_DYN_SIZED_DELETE */ #if defined(ENABLE_ALIGNED_NEW_DELETE) void* operator new(size_t size, std::align_val_t al) ALIAS(tc_new_aligned); void operator delete(void* p, std::align_val_t al) CPP_NOTHROW ALIAS(tc_delete_aligned); void* operator new[](size_t size, std::align_val_t al) ALIAS(tc_newarray_aligned); void operator delete[](void* p, std::align_val_t al) CPP_NOTHROW ALIAS(tc_deletearray_aligned); void* operator new(size_t size, std::align_val_t al, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_new_aligned_nothrow); void* operator new[](size_t size, std::align_val_t al, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_newarray_aligned_nothrow); void operator delete(void* p, std::align_val_t al, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_delete_aligned_nothrow); void operator delete[](void* p, std::align_val_t al, const std::nothrow_t& nt) CPP_NOTHROW ALIAS(tc_deletearray_aligned_nothrow); #if defined(ENABLE_SIZED_DELETE) void operator delete(void *p, size_t size, std::align_val_t al) CPP_NOTHROW ALIAS(tc_delete_sized_aligned); void operator delete[](void *p, size_t size, std::align_val_t al) CPP_NOTHROW ALIAS(tc_deletearray_sized_aligned); #else /* defined(ENABLE_SIZED_DELETE) */ #if defined(ENABLE_DYNAMIC_SIZED_DELETE) && \ (__GNUC__ * 100 + __GNUC_MINOR__) >= 405 static void delegate_sized_aligned_delete(void *p, size_t s, std::align_val_t al) { (operator delete)(p, al); } static void delegate_sized_aligned_deletearray(void *p, size_t s, std::align_val_t al) { (operator delete[])(p, al); } extern "C" { static void *resolve_delete_sized_aligned(void) { if (sized_delete_enabled()) { return reinterpret_cast<void *>(tc_delete_sized_aligned); } return reinterpret_cast<void *>(delegate_sized_aligned_delete); } static void *resolve_deletearray_sized_aligned(void) { if (sized_delete_enabled()) { return reinterpret_cast<void *>(tc_deletearray_sized_aligned); } return reinterpret_cast<void *>(delegate_sized_aligned_deletearray); } } void operator delete(void *p, size_t size, std::align_val_t al) CPP_NOTHROW __attribute__((ifunc("resolve_delete_sized_aligned"))); void operator delete[](void *p, size_t size, std::align_val_t al) CPP_NOTHROW __attribute__((ifunc("resolve_deletearray_sized_aligned"))); #else /* defined(ENABLE_DYN_SIZED_DELETE) */ void operator delete(void *p, size_t size, std::align_val_t al) CPP_NOTHROW ALIAS(tc_delete_sized_aligned); void operator delete[](void *p, size_t size, std::align_val_t al) CPP_NOTHROW ALIAS(tc_deletearray_sized_aligned); #endif /* defined(ENABLE_DYN_SIZED_DELETE) */ #endif /* defined(ENABLE_SIZED_DELETE) */ #endif /* defined(ENABLE_ALIGNED_NEW_DELETE) */ extern "C" { void* malloc(size_t size) __THROW ALIAS(tc_malloc); void free(void* ptr) __THROW ALIAS(tc_free); void* realloc(void* ptr, size_t size) __THROW ALIAS(tc_realloc); void* calloc(size_t n, size_t size) __THROW ALIAS(tc_calloc); void cfree(void* ptr) __THROW ALIAS(tc_cfree); void* memalign(size_t align, size_t s) __THROW ALIAS(tc_memalign); void* aligned_alloc(size_t align, size_t s) __THROW ALIAS(tc_memalign); void* valloc(size_t size) __THROW ALIAS(tc_valloc); void* pvalloc(size_t size) __THROW ALIAS(tc_pvalloc); int posix_memalign(void** r, size_t a, size_t s) __THROW ALIAS(tc_posix_memalign); #ifndef __UCLIBC__ void malloc_stats(void) __THROW ALIAS(tc_malloc_stats); #endif int mallopt(int cmd, int value) __THROW ALIAS(tc_mallopt); #ifdef HAVE_STRUCT_MALLINFO struct mallinfo mallinfo(void) __THROW ALIAS(tc_mallinfo); #endif size_t malloc_size(void* p) __THROW ALIAS(tc_malloc_size); #if defined(__ANDROID__) size_t malloc_usable_size(const void* p) __THROW ALIAS(tc_malloc_size); #else size_t malloc_usable_size(void* p) __THROW ALIAS(tc_malloc_size); #endif } // extern "C" #undef ALIAS // No need to do anything at tcmalloc-registration time: we do it all // via overriding weak symbols (at link time). static void ReplaceSystemAlloc() { } #endif // TCMALLOC_LIBC_OVERRIDE_GCC_AND_WEAK_INL_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/emergency_malloc_for_stacktrace.cc
.cc
2,043
49
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2014, gperftools Contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "emergency_malloc.h" #include "thread_cache.h" namespace tcmalloc { bool EnterStacktraceScope(void); void LeaveStacktraceScope(void); } bool tcmalloc::EnterStacktraceScope(void) { if (ThreadCache::IsUseEmergencyMalloc()) { return false; } ThreadCache::SetUseEmergencyMalloc(); return true; } void tcmalloc::LeaveStacktraceScope(void) { ThreadCache::ResetUseEmergencyMalloc(); }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/span.h
.h
6,066
176
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> // // A Span is a contiguous run of pages. #ifndef TCMALLOC_SPAN_H_ #define TCMALLOC_SPAN_H_ #include <config.h> #include <set> #include "common.h" #include "base/logging.h" #include "page_heap_allocator.h" namespace tcmalloc { struct SpanBestFitLess; struct Span; // Store a pointer to a span along with a cached copy of its length. // These are used as set elements to improve the performance of // comparisons during tree traversal: the lengths are inline with the // tree nodes and thus avoid expensive cache misses to dereference // the actual Span objects in most cases. struct SpanPtrWithLength { explicit SpanPtrWithLength(Span* s); Span* span; Length length; }; typedef std::set<SpanPtrWithLength, SpanBestFitLess, STLPageHeapAllocator<SpanPtrWithLength, void> > SpanSet; // Comparator for best-fit search, with address order as a tie-breaker. struct SpanBestFitLess { bool operator()(SpanPtrWithLength a, SpanPtrWithLength b) const; }; // Information kept for a span (a contiguous run of pages). struct Span { PageID start; // Starting page number Length length; // Number of pages in span Span* next; // Used when in link list Span* prev; // Used when in link list union { void* objects; // Linked list of free objects // Span may contain iterator pointing back at SpanSet entry of // this span into set of large spans. It is used to quickly delete // spans from those sets. span_iter_space is space for such // iterator which lifetime is controlled explicitly. char span_iter_space[sizeof(SpanSet::iterator)]; }; unsigned int refcount : 16; // Number of non-free objects unsigned int sizeclass : 8; // Size-class for small objects (or 0) unsigned int location : 2; // Is the span on a freelist, and if so, which? unsigned int sample : 1; // Sampled object? bool has_span_iter : 1; // Iff span_iter_space has valid // iterator. Only for debug builds. // Sets iterator stored in span_iter_space. // Requires has_span_iter == 0. void SetSpanSetIterator(const SpanSet::iterator& iter); // Copies out and destroys iterator stored in span_iter_space. SpanSet::iterator ExtractSpanSetIterator(); #undef SPAN_HISTORY #ifdef SPAN_HISTORY // For debugging, we can keep a log events per span int nexthistory; char history[64]; int value[64]; #endif // What freelist the span is on: IN_USE if on none, or normal or returned enum { IN_USE, ON_NORMAL_FREELIST, ON_RETURNED_FREELIST }; }; #ifdef SPAN_HISTORY void Event(Span* span, char op, int v = 0); #else #define Event(s,o,v) ((void) 0) #endif inline SpanPtrWithLength::SpanPtrWithLength(Span* s) : span(s), length(s->length) { } inline bool SpanBestFitLess::operator()(SpanPtrWithLength a, SpanPtrWithLength b) const { if (a.length < b.length) return true; if (a.length > b.length) return false; return a.span->start < b.span->start; } inline void Span::SetSpanSetIterator(const SpanSet::iterator& iter) { ASSERT(!has_span_iter); has_span_iter = 1; new (span_iter_space) SpanSet::iterator(iter); } inline SpanSet::iterator Span::ExtractSpanSetIterator() { typedef SpanSet::iterator iterator_type; ASSERT(has_span_iter); has_span_iter = 0; iterator_type* this_iter = reinterpret_cast<iterator_type*>(span_iter_space); iterator_type retval = *this_iter; this_iter->~iterator_type(); return retval; } // Allocator/deallocator for spans Span* NewSpan(PageID p, Length len); void DeleteSpan(Span* span); // ------------------------------------------------------------------------- // Doubly linked list of spans. // ------------------------------------------------------------------------- // Initialize *list to an empty list. void DLL_Init(Span* list); // Remove 'span' from the linked list in which it resides, updating the // pointers of adjacent Spans and setting span's next and prev to NULL. void DLL_Remove(Span* span); // Return true iff "list" is empty. inline bool DLL_IsEmpty(const Span* list) { return list->next == list; } // Add span to the front of list. void DLL_Prepend(Span* list, Span* span); // Return the length of the linked list. O(n) int DLL_Length(const Span* list); } // namespace tcmalloc #endif // TCMALLOC_SPAN_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/common.cc
.cc
10,411
292
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <opensource@google.com> #include <stdlib.h> // for getenv and strtol #include "config.h" #include "common.h" #include "system-alloc.h" #include "base/spinlock.h" #include "getenv_safe.h" // TCMallocGetenvSafe namespace tcmalloc { // Define the maximum number of object per classe type to transfer between // thread and central caches. static int32 FLAGS_tcmalloc_transfer_num_objects; static const int32 kDefaultTransferNumObjecs = 32; // The init function is provided to explicit initialize the variable value // from the env. var to avoid C++ global construction that might defer its // initialization after a malloc/new call. static inline void InitTCMallocTransferNumObjects() { if (FLAGS_tcmalloc_transfer_num_objects == 0) { const char *envval = TCMallocGetenvSafe("TCMALLOC_TRANSFER_NUM_OBJ"); FLAGS_tcmalloc_transfer_num_objects = !envval ? kDefaultTransferNumObjecs : strtol(envval, NULL, 10); } } // Note: the following only works for "n"s that fit in 32-bits, but // that is fine since we only use it for small sizes. static inline int LgFloor(size_t n) { int log = 0; for (int i = 4; i >= 0; --i) { int shift = (1 << i); size_t x = n >> shift; if (x != 0) { n = x; log += shift; } } ASSERT(n == 1); return log; } int AlignmentForSize(size_t size) { int alignment = kAlignment; if (size > kMaxSize) { // Cap alignment at kPageSize for large sizes. alignment = kPageSize; } else if (size >= 128) { // Space wasted due to alignment is at most 1/8, i.e., 12.5%. alignment = (1 << LgFloor(size)) / 8; } else if (size >= kMinAlign) { // We need an alignment of at least 16 bytes to satisfy // requirements for some SSE types. alignment = kMinAlign; } // Maximum alignment allowed is page size alignment. if (alignment > kPageSize) { alignment = kPageSize; } CHECK_CONDITION(size < kMinAlign || alignment >= kMinAlign); CHECK_CONDITION((alignment & (alignment - 1)) == 0); return alignment; } int SizeMap::NumMoveSize(size_t size) { if (size == 0) return 0; // Use approx 64k transfers between thread and central caches. int num = static_cast<int>(64.0 * 1024.0 / size); if (num < 2) num = 2; // Avoid bringing too many objects into small object free lists. // If this value is too large: // - We waste memory with extra objects sitting in the thread caches. // - The central freelist holds its lock for too long while // building a linked list of objects, slowing down the allocations // of other threads. // If this value is too small: // - We go to the central freelist too often and we have to acquire // its lock each time. // This value strikes a balance between the constraints above. if (num > FLAGS_tcmalloc_transfer_num_objects) num = FLAGS_tcmalloc_transfer_num_objects; return num; } // Initialize the mapping arrays void SizeMap::Init() { InitTCMallocTransferNumObjects(); // Do some sanity checking on add_amount[]/shift_amount[]/class_array[] if (ClassIndex(0) != 0) { Log(kCrash, __FILE__, __LINE__, "Invalid class index for size 0", ClassIndex(0)); } if (ClassIndex(kMaxSize) >= sizeof(class_array_)) { Log(kCrash, __FILE__, __LINE__, "Invalid class index for kMaxSize", ClassIndex(kMaxSize)); } // Compute the size classes we want to use int sc = 1; // Next size class to assign int alignment = kAlignment; CHECK_CONDITION(kAlignment <= kMinAlign); for (size_t size = kAlignment; size <= kMaxSize; size += alignment) { alignment = AlignmentForSize(size); CHECK_CONDITION((size % alignment) == 0); int blocks_to_move = NumMoveSize(size) / 4; size_t psize = 0; do { psize += kPageSize; // Allocate enough pages so leftover is less than 1/8 of total. // This bounds wasted space to at most 12.5%. while ((psize % size) > (psize >> 3)) { psize += kPageSize; } // Continue to add pages until there are at least as many objects in // the span as are needed when moving objects from the central // freelists and spans to the thread caches. } while ((psize / size) < (blocks_to_move)); const size_t my_pages = psize >> kPageShift; if (sc > 1 && my_pages == class_to_pages_[sc-1]) { // See if we can merge this into the previous class without // increasing the fragmentation of the previous class. const size_t my_objects = (my_pages << kPageShift) / size; const size_t prev_objects = (class_to_pages_[sc-1] << kPageShift) / class_to_size_[sc-1]; if (my_objects == prev_objects) { // Adjust last class to include this size class_to_size_[sc-1] = size; continue; } } // Add new class class_to_pages_[sc] = my_pages; class_to_size_[sc] = size; sc++; } num_size_classes = sc; if (sc > kClassSizesMax) { Log(kCrash, __FILE__, __LINE__, "too many size classes: (found vs. max)", sc, kClassSizesMax); } // Initialize the mapping arrays int next_size = 0; for (int c = 1; c < num_size_classes; c++) { const int max_size_in_class = class_to_size_[c]; for (int s = next_size; s <= max_size_in_class; s += kAlignment) { class_array_[ClassIndex(s)] = c; } next_size = max_size_in_class + kAlignment; } // Double-check sizes just to be safe for (size_t size = 0; size <= kMaxSize;) { const int sc = SizeClass(size); if (sc <= 0 || sc >= num_size_classes) { Log(kCrash, __FILE__, __LINE__, "Bad size class (class, size)", sc, size); } if (sc > 1 && size <= class_to_size_[sc-1]) { Log(kCrash, __FILE__, __LINE__, "Allocating unnecessarily large class (class, size)", sc, size); } const size_t s = class_to_size_[sc]; if (size > s || s == 0) { Log(kCrash, __FILE__, __LINE__, "Bad (class, size, requested)", sc, s, size); } if (size <= kMaxSmallSize) { size += 8; } else { size += 128; } } // Our fast-path aligned allocation functions rely on 'naturally // aligned' sizes to produce aligned addresses. Lets check if that // holds for size classes that we produced. // // I.e. we're checking that // // align = (1 << shift), malloc(i * align) % align == 0, // // for all align values up to kPageSize. for (size_t align = kMinAlign; align <= kPageSize; align <<= 1) { for (size_t size = align; size < kPageSize; size += align) { CHECK_CONDITION(class_to_size_[SizeClass(size)] % align == 0); } } // Initialize the num_objects_to_move array. for (size_t cl = 1; cl < num_size_classes; ++cl) { num_objects_to_move_[cl] = NumMoveSize(ByteSizeForClass(cl)); } } // Metadata allocator -- keeps stats about how many bytes allocated. static uint64_t metadata_system_bytes_ = 0; static const size_t kMetadataAllocChunkSize = 8*1024*1024; // As ThreadCache objects are allocated with MetaDataAlloc, and also // CACHELINE_ALIGNED, we must use the same alignment as TCMalloc_SystemAlloc. static const size_t kMetadataAllignment = sizeof(MemoryAligner); static char *metadata_chunk_alloc_; static size_t metadata_chunk_avail_; static SpinLock metadata_alloc_lock(SpinLock::LINKER_INITIALIZED); void* MetaDataAlloc(size_t bytes) { if (bytes >= kMetadataAllocChunkSize) { void *rv = TCMalloc_SystemAlloc(bytes, NULL, kMetadataAllignment); if (rv != NULL) { metadata_system_bytes_ += bytes; } return rv; } SpinLockHolder h(&metadata_alloc_lock); // the following works by essentially turning address to integer of // log_2 kMetadataAllignment size and negating it. I.e. negated // value + original value gets 0 and that's what we want modulo // kMetadataAllignment. Note, we negate before masking higher bits // off, otherwise we'd have to mask them off after negation anyways. intptr_t alignment = -reinterpret_cast<intptr_t>(metadata_chunk_alloc_) & (kMetadataAllignment-1); if (metadata_chunk_avail_ < bytes + alignment) { size_t real_size; void *ptr = TCMalloc_SystemAlloc(kMetadataAllocChunkSize, &real_size, kMetadataAllignment); if (ptr == NULL) { return NULL; } metadata_chunk_alloc_ = static_cast<char *>(ptr); metadata_chunk_avail_ = real_size; alignment = 0; } void *rv = static_cast<void *>(metadata_chunk_alloc_ + alignment); bytes += alignment; metadata_chunk_alloc_ += bytes; metadata_chunk_avail_ -= bytes; metadata_system_bytes_ += bytes; return rv; } uint64_t metadata_system_bytes() { return metadata_system_bytes_; } } // namespace tcmalloc
Unknown
3D
mcellteam/mcell
libs/gperftools/src/heap-profile-table.cc
.cc
20,866
630
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat // Maxim Lifantsev (refactoring) // #include <config.h> #ifdef HAVE_UNISTD_H #include <unistd.h> // for write() #endif #include <fcntl.h> // for open() #ifdef HAVE_GLOB_H #include <glob.h> #ifndef GLOB_NOMATCH // true on some old cygwins # define GLOB_NOMATCH 0 #endif #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> // for PRIxPTR #endif #ifdef HAVE_POLL_H #include <poll.h> #endif #include <errno.h> #include <stdarg.h> #include <string> #include <map> #include <algorithm> // for sort(), equal(), and copy() #include "heap-profile-table.h" #include "base/logging.h" #include "raw_printer.h" #include "symbolize.h" #include <gperftools/stacktrace.h> #include <gperftools/malloc_hook.h> #include "memory_region_map.h" #include "base/commandlineflags.h" #include "base/logging.h" // for the RawFD I/O commands #include "base/sysinfo.h" using std::sort; using std::equal; using std::copy; using std::string; using std::map; using tcmalloc::FillProcSelfMaps; // from sysinfo.h using tcmalloc::DumpProcSelfMaps; // from sysinfo.h //---------------------------------------------------------------------- DEFINE_bool(cleanup_old_heap_profiles, EnvToBool("HEAP_PROFILE_CLEANUP", true), "At initialization time, delete old heap profiles."); DEFINE_int32(heap_check_max_leaks, EnvToInt("HEAP_CHECK_MAX_LEAKS", 20), "The maximum number of leak reports to print."); //---------------------------------------------------------------------- // header of the dumped heap profile static const char kProfileHeader[] = "heap profile: "; static const char kProcSelfMapsHeader[] = "\nMAPPED_LIBRARIES:\n"; //---------------------------------------------------------------------- const char HeapProfileTable::kFileExt[] = ".heap"; //---------------------------------------------------------------------- static const int kHashTableSize = 179999; // Size for bucket_table_. /*static*/ const int HeapProfileTable::kMaxStackDepth; //---------------------------------------------------------------------- // We strip out different number of stack frames in debug mode // because less inlining happens in that case #ifdef NDEBUG static const int kStripFrames = 2; #else static const int kStripFrames = 3; #endif // For sorting Stats or Buckets by in-use space static bool ByAllocatedSpace(HeapProfileTable::Stats* a, HeapProfileTable::Stats* b) { // Return true iff "a" has more allocated space than "b" return (a->alloc_size - a->free_size) > (b->alloc_size - b->free_size); } //---------------------------------------------------------------------- HeapProfileTable::HeapProfileTable(Allocator alloc, DeAllocator dealloc, bool profile_mmap) : alloc_(alloc), dealloc_(dealloc), profile_mmap_(profile_mmap), bucket_table_(NULL), num_buckets_(0), address_map_(NULL) { // Make a hash table for buckets. const int table_bytes = kHashTableSize * sizeof(*bucket_table_); bucket_table_ = static_cast<Bucket**>(alloc_(table_bytes)); memset(bucket_table_, 0, table_bytes); // Make an allocation map. address_map_ = new(alloc_(sizeof(AllocationMap))) AllocationMap(alloc_, dealloc_); // Initialize. memset(&total_, 0, sizeof(total_)); num_buckets_ = 0; } HeapProfileTable::~HeapProfileTable() { // Free the allocation map. address_map_->~AllocationMap(); dealloc_(address_map_); address_map_ = NULL; // Free the hash table. for (int i = 0; i < kHashTableSize; i++) { for (Bucket* curr = bucket_table_[i]; curr != 0; /**/) { Bucket* bucket = curr; curr = curr->next; dealloc_(bucket->stack); dealloc_(bucket); } } dealloc_(bucket_table_); bucket_table_ = NULL; } HeapProfileTable::Bucket* HeapProfileTable::GetBucket(int depth, const void* const key[]) { // Make hash-value uintptr_t h = 0; for (int i = 0; i < depth; i++) { h += reinterpret_cast<uintptr_t>(key[i]); h += h << 10; h ^= h >> 6; } h += h << 3; h ^= h >> 11; // Lookup stack trace in table unsigned int buck = ((unsigned int) h) % kHashTableSize; for (Bucket* b = bucket_table_[buck]; b != 0; b = b->next) { if ((b->hash == h) && (b->depth == depth) && equal(key, key + depth, b->stack)) { return b; } } // Create new bucket const size_t key_size = sizeof(key[0]) * depth; const void** kcopy = reinterpret_cast<const void**>(alloc_(key_size)); copy(key, key + depth, kcopy); Bucket* b = reinterpret_cast<Bucket*>(alloc_(sizeof(Bucket))); memset(b, 0, sizeof(*b)); b->hash = h; b->depth = depth; b->stack = kcopy; b->next = bucket_table_[buck]; bucket_table_[buck] = b; num_buckets_++; return b; } int HeapProfileTable::GetCallerStackTrace( int skip_count, void* stack[kMaxStackDepth]) { return MallocHook::GetCallerStackTrace( stack, kMaxStackDepth, kStripFrames + skip_count + 1); } void HeapProfileTable::RecordAlloc( const void* ptr, size_t bytes, int stack_depth, const void* const call_stack[]) { Bucket* b = GetBucket(stack_depth, call_stack); b->allocs++; b->alloc_size += bytes; total_.allocs++; total_.alloc_size += bytes; AllocValue v; v.set_bucket(b); // also did set_live(false); set_ignore(false) v.bytes = bytes; address_map_->Insert(ptr, v); } void HeapProfileTable::RecordFree(const void* ptr) { AllocValue v; if (address_map_->FindAndRemove(ptr, &v)) { Bucket* b = v.bucket(); b->frees++; b->free_size += v.bytes; total_.frees++; total_.free_size += v.bytes; } } bool HeapProfileTable::FindAlloc(const void* ptr, size_t* object_size) const { const AllocValue* alloc_value = address_map_->Find(ptr); if (alloc_value != NULL) *object_size = alloc_value->bytes; return alloc_value != NULL; } bool HeapProfileTable::FindAllocDetails(const void* ptr, AllocInfo* info) const { const AllocValue* alloc_value = address_map_->Find(ptr); if (alloc_value != NULL) { info->object_size = alloc_value->bytes; info->call_stack = alloc_value->bucket()->stack; info->stack_depth = alloc_value->bucket()->depth; } return alloc_value != NULL; } bool HeapProfileTable::FindInsideAlloc(const void* ptr, size_t max_size, const void** object_ptr, size_t* object_size) const { const AllocValue* alloc_value = address_map_->FindInside(&AllocValueSize, max_size, ptr, object_ptr); if (alloc_value != NULL) *object_size = alloc_value->bytes; return alloc_value != NULL; } bool HeapProfileTable::MarkAsLive(const void* ptr) { AllocValue* alloc = address_map_->FindMutable(ptr); if (alloc && !alloc->live()) { alloc->set_live(true); return true; } return false; } void HeapProfileTable::MarkAsIgnored(const void* ptr) { AllocValue* alloc = address_map_->FindMutable(ptr); if (alloc) { alloc->set_ignore(true); } } // We'd be happier using snprintfer, but we don't to reduce dependencies. int HeapProfileTable::UnparseBucket(const Bucket& b, char* buf, int buflen, int bufsize, const char* extra, Stats* profile_stats) { if (profile_stats != NULL) { profile_stats->allocs += b.allocs; profile_stats->alloc_size += b.alloc_size; profile_stats->frees += b.frees; profile_stats->free_size += b.free_size; } int printed = snprintf(buf + buflen, bufsize - buflen, "%6d: %8" PRId64 " [%6d: %8" PRId64 "] @%s", b.allocs - b.frees, b.alloc_size - b.free_size, b.allocs, b.alloc_size, extra); // If it looks like the snprintf failed, ignore the fact we printed anything if (printed < 0 || printed >= bufsize - buflen) return buflen; buflen += printed; for (int d = 0; d < b.depth; d++) { printed = snprintf(buf + buflen, bufsize - buflen, " 0x%08" PRIxPTR, reinterpret_cast<uintptr_t>(b.stack[d])); if (printed < 0 || printed >= bufsize - buflen) return buflen; buflen += printed; } printed = snprintf(buf + buflen, bufsize - buflen, "\n"); if (printed < 0 || printed >= bufsize - buflen) return buflen; buflen += printed; return buflen; } HeapProfileTable::Bucket** HeapProfileTable::MakeSortedBucketList() const { Bucket** list = static_cast<Bucket**>(alloc_(sizeof(Bucket) * num_buckets_)); int bucket_count = 0; for (int i = 0; i < kHashTableSize; i++) { for (Bucket* curr = bucket_table_[i]; curr != 0; curr = curr->next) { list[bucket_count++] = curr; } } RAW_DCHECK(bucket_count == num_buckets_, ""); sort(list, list + num_buckets_, ByAllocatedSpace); return list; } void HeapProfileTable::IterateOrderedAllocContexts( AllocContextIterator callback) const { Bucket** list = MakeSortedBucketList(); AllocContextInfo info; for (int i = 0; i < num_buckets_; ++i) { *static_cast<Stats*>(&info) = *static_cast<Stats*>(list[i]); info.stack_depth = list[i]->depth; info.call_stack = list[i]->stack; callback(info); } dealloc_(list); } int HeapProfileTable::FillOrderedProfile(char buf[], int size) const { Bucket** list = MakeSortedBucketList(); // Our file format is "bucket, bucket, ..., bucket, proc_self_maps_info". // In the cases buf is too small, we'd rather leave out the last // buckets than leave out the /proc/self/maps info. To ensure that, // we actually print the /proc/self/maps info first, then move it to // the end of the buffer, then write the bucket info into whatever // is remaining, and then move the maps info one last time to close // any gaps. Whew! int map_length = snprintf(buf, size, "%s", kProcSelfMapsHeader); if (map_length < 0 || map_length >= size) { dealloc_(list); return 0; } bool dummy; // "wrote_all" -- did /proc/self/maps fit in its entirety? map_length += FillProcSelfMaps(buf + map_length, size - map_length, &dummy); RAW_DCHECK(map_length <= size, ""); char* const map_start = buf + size - map_length; // move to end memmove(map_start, buf, map_length); size -= map_length; Stats stats; memset(&stats, 0, sizeof(stats)); int bucket_length = snprintf(buf, size, "%s", kProfileHeader); if (bucket_length < 0 || bucket_length >= size) { dealloc_(list); return 0; } bucket_length = UnparseBucket(total_, buf, bucket_length, size, " heapprofile", &stats); // Dump the mmap list first. if (profile_mmap_) { BufferArgs buffer(buf, bucket_length, size); MemoryRegionMap::IterateBuckets<BufferArgs*>(DumpBucketIterator, &buffer); bucket_length = buffer.buflen; } for (int i = 0; i < num_buckets_; i++) { bucket_length = UnparseBucket(*list[i], buf, bucket_length, size, "", &stats); } RAW_DCHECK(bucket_length < size, ""); dealloc_(list); RAW_DCHECK(buf + bucket_length <= map_start, ""); memmove(buf + bucket_length, map_start, map_length); // close the gap return bucket_length + map_length; } // static void HeapProfileTable::DumpBucketIterator(const Bucket* bucket, BufferArgs* args) { args->buflen = UnparseBucket(*bucket, args->buf, args->buflen, args->bufsize, "", NULL); } inline void HeapProfileTable::DumpNonLiveIterator(const void* ptr, AllocValue* v, const DumpArgs& args) { if (v->live()) { v->set_live(false); return; } if (v->ignore()) { return; } Bucket b; memset(&b, 0, sizeof(b)); b.allocs = 1; b.alloc_size = v->bytes; b.depth = v->bucket()->depth; b.stack = v->bucket()->stack; char buf[1024]; int len = UnparseBucket(b, buf, 0, sizeof(buf), "", args.profile_stats); RawWrite(args.fd, buf, len); } // Callback from NonLiveSnapshot; adds entry to arg->dest // if not the entry is not live and is not present in arg->base. void HeapProfileTable::AddIfNonLive(const void* ptr, AllocValue* v, AddNonLiveArgs* arg) { if (v->live()) { v->set_live(false); } else { if (arg->base != NULL && arg->base->map_.Find(ptr) != NULL) { // Present in arg->base, so do not save } else { arg->dest->Add(ptr, *v); } } } bool HeapProfileTable::WriteProfile(const char* file_name, const Bucket& total, AllocationMap* allocations) { RAW_VLOG(1, "Dumping non-live heap profile to %s", file_name); RawFD fd = RawOpenForWriting(file_name); if (fd == kIllegalRawFD) { RAW_LOG(ERROR, "Failed dumping filtered heap profile to %s", file_name); return false; } RawWrite(fd, kProfileHeader, strlen(kProfileHeader)); char buf[512]; int len = UnparseBucket(total, buf, 0, sizeof(buf), " heapprofile", NULL); RawWrite(fd, buf, len); const DumpArgs args(fd, NULL); allocations->Iterate<const DumpArgs&>(DumpNonLiveIterator, args); RawWrite(fd, kProcSelfMapsHeader, strlen(kProcSelfMapsHeader)); DumpProcSelfMaps(fd); RawClose(fd); return true; } void HeapProfileTable::CleanupOldProfiles(const char* prefix) { if (!FLAGS_cleanup_old_heap_profiles) return; string pattern = string(prefix) + ".*" + kFileExt; #if defined(HAVE_GLOB_H) glob_t g; const int r = glob(pattern.c_str(), GLOB_ERR, NULL, &g); if (r == 0 || r == GLOB_NOMATCH) { const int prefix_length = strlen(prefix); for (int i = 0; i < g.gl_pathc; i++) { const char* fname = g.gl_pathv[i]; if ((strlen(fname) >= prefix_length) && (memcmp(fname, prefix, prefix_length) == 0)) { RAW_VLOG(1, "Removing old heap profile %s", fname); unlink(fname); } } } globfree(&g); #else /* HAVE_GLOB_H */ RAW_LOG(WARNING, "Unable to remove old heap profiles (can't run glob())"); #endif } HeapProfileTable::Snapshot* HeapProfileTable::TakeSnapshot() { Snapshot* s = new (alloc_(sizeof(Snapshot))) Snapshot(alloc_, dealloc_); address_map_->Iterate(AddToSnapshot, s); return s; } void HeapProfileTable::ReleaseSnapshot(Snapshot* s) { s->~Snapshot(); dealloc_(s); } // Callback from TakeSnapshot; adds a single entry to snapshot void HeapProfileTable::AddToSnapshot(const void* ptr, AllocValue* v, Snapshot* snapshot) { snapshot->Add(ptr, *v); } HeapProfileTable::Snapshot* HeapProfileTable::NonLiveSnapshot( Snapshot* base) { RAW_VLOG(2, "NonLiveSnapshot input: %d %d\n", int(total_.allocs - total_.frees), int(total_.alloc_size - total_.free_size)); Snapshot* s = new (alloc_(sizeof(Snapshot))) Snapshot(alloc_, dealloc_); AddNonLiveArgs args; args.dest = s; args.base = base; address_map_->Iterate<AddNonLiveArgs*>(AddIfNonLive, &args); RAW_VLOG(2, "NonLiveSnapshot output: %d %d\n", int(s->total_.allocs - s->total_.frees), int(s->total_.alloc_size - s->total_.free_size)); return s; } // Information kept per unique bucket seen struct HeapProfileTable::Snapshot::Entry { int count; int bytes; Bucket* bucket; Entry() : count(0), bytes(0) { } // Order by decreasing bytes bool operator<(const Entry& x) const { return this->bytes > x.bytes; } }; // State used to generate leak report. We keep a mapping from Bucket pointer // the collected stats for that bucket. struct HeapProfileTable::Snapshot::ReportState { map<Bucket*, Entry> buckets_; }; // Callback from ReportLeaks; updates ReportState. void HeapProfileTable::Snapshot::ReportCallback(const void* ptr, AllocValue* v, ReportState* state) { Entry* e = &state->buckets_[v->bucket()]; // Creates empty Entry first time e->bucket = v->bucket(); e->count++; e->bytes += v->bytes; } void HeapProfileTable::Snapshot::ReportLeaks(const char* checker_name, const char* filename, bool should_symbolize) { // This is only used by the heap leak checker, but is intimately // tied to the allocation map that belongs in this module and is // therefore placed here. RAW_LOG(ERROR, "Leak check %s detected leaks of %" PRIuS " bytes " "in %" PRIuS " objects", checker_name, size_t(total_.alloc_size), size_t(total_.allocs)); // Group objects by Bucket ReportState state; map_.Iterate(&ReportCallback, &state); // Sort buckets by decreasing leaked size const int n = state.buckets_.size(); Entry* entries = new Entry[n]; int dst = 0; for (map<Bucket*,Entry>::const_iterator iter = state.buckets_.begin(); iter != state.buckets_.end(); ++iter) { entries[dst++] = iter->second; } sort(entries, entries + n); // Report a bounded number of leaks to keep the leak report from // growing too long. const int to_report = (FLAGS_heap_check_max_leaks > 0 && n > FLAGS_heap_check_max_leaks) ? FLAGS_heap_check_max_leaks : n; RAW_LOG(ERROR, "The %d largest leaks:", to_report); // Print SymbolTable symbolization_table; for (int i = 0; i < to_report; i++) { const Entry& e = entries[i]; for (int j = 0; j < e.bucket->depth; j++) { symbolization_table.Add(e.bucket->stack[j]); } } static const int kBufSize = 2<<10; char buffer[kBufSize]; if (should_symbolize) symbolization_table.Symbolize(); for (int i = 0; i < to_report; i++) { const Entry& e = entries[i]; base::RawPrinter printer(buffer, kBufSize); printer.Printf("Leak of %d bytes in %d objects allocated from:\n", e.bytes, e.count); for (int j = 0; j < e.bucket->depth; j++) { const void* pc = e.bucket->stack[j]; printer.Printf("\t@ %" PRIxPTR " %s\n", reinterpret_cast<uintptr_t>(pc), symbolization_table.GetSymbol(pc)); } RAW_LOG(ERROR, "%s", buffer); } if (to_report < n) { RAW_LOG(ERROR, "Skipping leaks numbered %d..%d", to_report, n-1); } delete[] entries; // TODO: Dump the sorted Entry list instead of dumping raw data? // (should be much shorter) if (!HeapProfileTable::WriteProfile(filename, total_, &map_)) { RAW_LOG(ERROR, "Could not write pprof profile to %s", filename); } } void HeapProfileTable::Snapshot::ReportObject(const void* ptr, AllocValue* v, char* unused) { // Perhaps also log the allocation stack trace (unsymbolized) // on this line in case somebody finds it useful. RAW_LOG(ERROR, "leaked %" PRIuS " byte object %p", v->bytes, ptr); } void HeapProfileTable::Snapshot::ReportIndividualObjects() { char unused; map_.Iterate(ReportObject, &unused); }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/heap-profile-stats.h
.h
3,561
79
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2013, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This file defines structs to accumulate memory allocation and deallocation // counts. These structs are commonly used for malloc (in HeapProfileTable) // and mmap (in MemoryRegionMap). // A bucket is data structure for heap profiling to store a pair of a stack // trace and counts of (de)allocation. Buckets are stored in a hash table // which is declared as "HeapProfileBucket**". // // A hash value is computed from a stack trace. Collision in the hash table // is resolved by separate chaining with linked lists. The links in the list // are implemented with the member "HeapProfileBucket* next". // // A structure of a hash table HeapProfileBucket** bucket_table would be like: // bucket_table[0] => NULL // bucket_table[1] => HeapProfileBucket() => HeapProfileBucket() => NULL // ... // bucket_table[i] => HeapProfileBucket() => NULL // ... // bucket_table[n] => HeapProfileBucket() => NULL #ifndef HEAP_PROFILE_STATS_H_ #define HEAP_PROFILE_STATS_H_ struct HeapProfileStats { // Returns true if the two HeapProfileStats are semantically equal. bool Equivalent(const HeapProfileStats& other) const { return allocs - frees == other.allocs - other.frees && alloc_size - free_size == other.alloc_size - other.free_size; } int32 allocs; // Number of allocation calls. int32 frees; // Number of free calls. int64 alloc_size; // Total size of all allocated objects so far. int64 free_size; // Total size of all freed objects so far. }; // Allocation and deallocation statistics per each stack trace. struct HeapProfileBucket : public HeapProfileStats { // Longest stack trace we record. static const int kMaxStackDepth = 32; uintptr_t hash; // Hash value of the stack trace. int depth; // Depth of stack trace. const void** stack; // Stack trace. HeapProfileBucket* next; // Next entry in hash-table. }; #endif // HEAP_PROFILE_STATS_H_
Unknown
3D
mcellteam/mcell
libs/gperftools/src/stacktrace_libunwind-inl.h
.h
5,127
153
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Arun Sharma // // Produce stack trace using libunwind #ifndef BASE_STACKTRACE_LIBINWIND_INL_H_ #define BASE_STACKTRACE_LIBINWIND_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: // We only need local unwinder. #define UNW_LOCAL_ONLY extern "C" { #include <assert.h> #include <string.h> // for memset() #include <libunwind.h> } #include "gperftools/stacktrace.h" #include "base/basictypes.h" #include "base/logging.h" // Sometimes, we can try to get a stack trace from within a stack // trace, because libunwind can call mmap (maybe indirectly via an // internal mmap based memory allocator), and that mmap gets trapped // and causes a stack-trace request. If were to try to honor that // recursive request, we'd end up with infinite recursion or deadlock. // Luckily, it's safe to ignore those subsequent traces. In such // cases, we return 0 to indicate the situation. static __thread int recursive ATTR_INITIAL_EXEC; #if defined(TCMALLOC_ENABLE_UNWIND_FROM_UCONTEXT) && (defined(__i386__) || defined(__x86_64__)) && defined(__GNU_LIBRARY__) #define BASE_STACKTRACE_UNW_CONTEXT_IS_UCONTEXT 1 #endif #endif // BASE_STACKTRACE_LIBINWIND_INL_H_ // Note: this part of the file is included several times. // Do not put globals below. // The following 4 functions are generated from the code below: // GetStack{Trace,Frames}() // GetStack{Trace,Frames}WithContext() // // These functions take the following args: // void** result: the stack-trace, as an array // int* sizes: the size of each stack frame, as an array // (GetStackFrames* only) // int max_depth: the size of the result (and sizes) array(s) // int skip_count: how many stack pointers to skip before storing in result // void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) static int GET_STACK_TRACE_OR_FRAMES { void *ip; int n = 0; unw_cursor_t cursor; unw_context_t uc; #if IS_STACK_FRAMES unw_word_t sp = 0, next_sp = 0; #endif if (recursive) { return 0; } ++recursive; #if (IS_WITH_CONTEXT && defined(BASE_STACKTRACE_UNW_CONTEXT_IS_UCONTEXT)) if (ucp) { uc = *(static_cast<unw_context_t *>(const_cast<void *>(ucp))); /* this is a bit weird. profiler.cc calls us with signal's ucontext * yet passing us 2 as skip_count and essentially assuming we won't * use ucontext. */ /* In order to fix that I'm going to assume that if ucp is * non-null we're asked to ignore skip_count in case we're * able to use ucp */ skip_count = 0; } else { unw_getcontext(&uc); skip_count += 2; // Do not include current and parent frame } #else unw_getcontext(&uc); skip_count += 2; // Do not include current and parent frame #endif int ret = unw_init_local(&cursor, &uc); assert(ret >= 0); while (skip_count--) { if (unw_step(&cursor) <= 0) { goto out; } #if IS_STACK_FRAMES if (unw_get_reg(&cursor, UNW_REG_SP, &next_sp)) { goto out; } #endif } while (n < max_depth) { if (unw_get_reg(&cursor, UNW_REG_IP, (unw_word_t *) &ip) < 0) { break; } #if IS_STACK_FRAMES sizes[n] = 0; #endif result[n++] = ip; if (unw_step(&cursor) <= 0) { break; } #if IS_STACK_FRAMES sp = next_sp; if (unw_get_reg(&cursor, UNW_REG_SP, &next_sp) , 0) { break; } sizes[n - 1] = next_sp - sp; #endif } out: --recursive; return n; }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/third_party/valgrind.h
.h
232,322
3,925
/* -*- c -*- ---------------------------------------------------------------- Notice that the following BSD-style license applies to this one file (valgrind.h) only. The rest of Valgrind is licensed under the terms of the GNU General Public License, version 2, unless otherwise indicated. See the COPYING file in the source distribution for details. ---------------------------------------------------------------- This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2000-2008 Julian Seward. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------- Notice that the above BSD-style license applies to this one file (valgrind.h) only. The entire rest of Valgrind is licensed under the terms of the GNU General Public License, version 2. See the COPYING file in the source distribution for details. ---------------------------------------------------------------- */ /* This file is for inclusion into client (your!) code. You can use these macros to manipulate and query Valgrind's execution inside your own programs. The resulting executables will still run without Valgrind, just a little bit more slowly than they otherwise would, but otherwise unchanged. When not running on valgrind, each client request consumes very few (eg. 7) instructions, so the resulting performance loss is negligible unless you plan to execute client requests millions of times per second. Nevertheless, if that is still a problem, you can compile with the NVALGRIND symbol defined (gcc -DNVALGRIND) so that client requests are not even compiled in. */ #ifndef __VALGRIND_H #define __VALGRIND_H #include <stdarg.h> /* Nb: this file might be included in a file compiled with -ansi. So we can't use C++ style "//" comments nor the "asm" keyword (instead use "__asm__"). */ /* Derive some tags indicating what the target platform is. Note that in this file we're using the compiler's CPP symbols for identifying architectures, which are different to the ones we use within the rest of Valgrind. Note, __powerpc__ is active for both 32 and 64-bit PPC, whereas __powerpc64__ is only active for the latter (on Linux, that is). */ #undef PLAT_x86_linux #undef PLAT_amd64_linux #undef PLAT_ppc32_linux #undef PLAT_ppc64_linux #undef PLAT_ppc32_aix5 #undef PLAT_ppc64_aix5 #if !defined(_AIX) && defined(__i386__) # define PLAT_x86_linux 1 #elif !defined(_AIX) && defined(__x86_64__) # define PLAT_amd64_linux 1 #elif !defined(_AIX) && defined(__powerpc__) && !defined(__powerpc64__) # define PLAT_ppc32_linux 1 #elif !defined(_AIX) && defined(__powerpc__) && defined(__powerpc64__) # define PLAT_ppc64_linux 1 #elif defined(_AIX) && defined(__64BIT__) # define PLAT_ppc64_aix5 1 #elif defined(_AIX) && !defined(__64BIT__) # define PLAT_ppc32_aix5 1 #endif /* If we're not compiling for our target platform, don't generate any inline asms. */ #if !defined(PLAT_x86_linux) && !defined(PLAT_amd64_linux) \ && !defined(PLAT_ppc32_linux) && !defined(PLAT_ppc64_linux) \ && !defined(PLAT_ppc32_aix5) && !defined(PLAT_ppc64_aix5) # if !defined(NVALGRIND) # define NVALGRIND 1 # endif #endif /* ------------------------------------------------------------------ */ /* ARCHITECTURE SPECIFICS for SPECIAL INSTRUCTIONS. There is nothing */ /* in here of use to end-users -- skip to the next section. */ /* ------------------------------------------------------------------ */ #if defined(NVALGRIND) /* Define NVALGRIND to completely remove the Valgrind magic sequence from the compiled code (analogous to NDEBUG's effects on assert()) */ #define VALGRIND_DO_CLIENT_REQUEST( \ _zzq_rlval, _zzq_default, _zzq_request, \ _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ { \ (_zzq_rlval) = (_zzq_default); \ } #else /* ! NVALGRIND */ /* The following defines the magic code sequences which the JITter spots and handles magically. Don't look too closely at them as they will rot your brain. The assembly code sequences for all architectures is in this one file. This is because this file must be stand-alone, and we don't want to have multiple files. For VALGRIND_DO_CLIENT_REQUEST, we must ensure that the default value gets put in the return slot, so that everything works when this is executed not under Valgrind. Args are passed in a memory block, and so there's no intrinsic limit to the number that could be passed, but it's currently five. The macro args are: _zzq_rlval result lvalue _zzq_default default value (result returned when running on real CPU) _zzq_request request code _zzq_arg1..5 request params The other two macros are used to support function wrapping, and are a lot simpler. VALGRIND_GET_NR_CONTEXT returns the value of the guest's NRADDR pseudo-register and whatever other information is needed to safely run the call original from the wrapper: on ppc64-linux, the R2 value at the divert point is also needed. This information is abstracted into a user-visible type, OrigFn. VALGRIND_CALL_NOREDIR_* behaves the same as the following on the guest, but guarantees that the branch instruction will not be redirected: x86: call *%eax, amd64: call *%rax, ppc32/ppc64: branch-and-link-to-r11. VALGRIND_CALL_NOREDIR is just text, not a complete inline asm, since it needs to be combined with more magic inline asm stuff to be useful. */ /* ------------------------- x86-linux ------------------------- */ #if defined(PLAT_x86_linux) typedef struct { unsigned int nraddr; /* where's the code? */ } OrigFn; #define __SPECIAL_INSTRUCTION_PREAMBLE \ "roll $3, %%edi ; roll $13, %%edi\n\t" \ "roll $29, %%edi ; roll $19, %%edi\n\t" #define VALGRIND_DO_CLIENT_REQUEST( \ _zzq_rlval, _zzq_default, _zzq_request, \ _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ { volatile unsigned int _zzq_args[6]; \ volatile unsigned int _zzq_result; \ _zzq_args[0] = (unsigned int)(_zzq_request); \ _zzq_args[1] = (unsigned int)(_zzq_arg1); \ _zzq_args[2] = (unsigned int)(_zzq_arg2); \ _zzq_args[3] = (unsigned int)(_zzq_arg3); \ _zzq_args[4] = (unsigned int)(_zzq_arg4); \ _zzq_args[5] = (unsigned int)(_zzq_arg5); \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %EDX = client_request ( %EAX ) */ \ "xchgl %%ebx,%%ebx" \ : "=d" (_zzq_result) \ : "a" (&_zzq_args[0]), "0" (_zzq_default) \ : "cc", "memory" \ ); \ _zzq_rlval = _zzq_result; \ } #define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ volatile unsigned int __addr; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %EAX = guest_NRADDR */ \ "xchgl %%ecx,%%ecx" \ : "=a" (__addr) \ : \ : "cc", "memory" \ ); \ _zzq_orig->nraddr = __addr; \ } #define VALGRIND_CALL_NOREDIR_EAX \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* call-noredir *%EAX */ \ "xchgl %%edx,%%edx\n\t" #endif /* PLAT_x86_linux */ /* ------------------------ amd64-linux ------------------------ */ #if defined(PLAT_amd64_linux) typedef struct { unsigned long long int nraddr; /* where's the code? */ } OrigFn; #define __SPECIAL_INSTRUCTION_PREAMBLE \ "rolq $3, %%rdi ; rolq $13, %%rdi\n\t" \ "rolq $61, %%rdi ; rolq $51, %%rdi\n\t" #define VALGRIND_DO_CLIENT_REQUEST( \ _zzq_rlval, _zzq_default, _zzq_request, \ _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ { volatile unsigned long long int _zzq_args[6]; \ volatile unsigned long long int _zzq_result; \ _zzq_args[0] = (unsigned long long int)(_zzq_request); \ _zzq_args[1] = (unsigned long long int)(_zzq_arg1); \ _zzq_args[2] = (unsigned long long int)(_zzq_arg2); \ _zzq_args[3] = (unsigned long long int)(_zzq_arg3); \ _zzq_args[4] = (unsigned long long int)(_zzq_arg4); \ _zzq_args[5] = (unsigned long long int)(_zzq_arg5); \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %RDX = client_request ( %RAX ) */ \ "xchgq %%rbx,%%rbx" \ : "=d" (_zzq_result) \ : "a" (&_zzq_args[0]), "0" (_zzq_default) \ : "cc", "memory" \ ); \ _zzq_rlval = _zzq_result; \ } #define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ volatile unsigned long long int __addr; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %RAX = guest_NRADDR */ \ "xchgq %%rcx,%%rcx" \ : "=a" (__addr) \ : \ : "cc", "memory" \ ); \ _zzq_orig->nraddr = __addr; \ } #define VALGRIND_CALL_NOREDIR_RAX \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* call-noredir *%RAX */ \ "xchgq %%rdx,%%rdx\n\t" #endif /* PLAT_amd64_linux */ /* ------------------------ ppc32-linux ------------------------ */ #if defined(PLAT_ppc32_linux) typedef struct { unsigned int nraddr; /* where's the code? */ } OrigFn; #define __SPECIAL_INSTRUCTION_PREAMBLE \ "rlwinm 0,0,3,0,0 ; rlwinm 0,0,13,0,0\n\t" \ "rlwinm 0,0,29,0,0 ; rlwinm 0,0,19,0,0\n\t" #define VALGRIND_DO_CLIENT_REQUEST( \ _zzq_rlval, _zzq_default, _zzq_request, \ _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ \ { unsigned int _zzq_args[6]; \ unsigned int _zzq_result; \ unsigned int* _zzq_ptr; \ _zzq_args[0] = (unsigned int)(_zzq_request); \ _zzq_args[1] = (unsigned int)(_zzq_arg1); \ _zzq_args[2] = (unsigned int)(_zzq_arg2); \ _zzq_args[3] = (unsigned int)(_zzq_arg3); \ _zzq_args[4] = (unsigned int)(_zzq_arg4); \ _zzq_args[5] = (unsigned int)(_zzq_arg5); \ _zzq_ptr = _zzq_args; \ __asm__ volatile("mr 3,%1\n\t" /*default*/ \ "mr 4,%2\n\t" /*ptr*/ \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = client_request ( %R4 ) */ \ "or 1,1,1\n\t" \ "mr %0,3" /*result*/ \ : "=b" (_zzq_result) \ : "b" (_zzq_default), "b" (_zzq_ptr) \ : "cc", "memory", "r3", "r4"); \ _zzq_rlval = _zzq_result; \ } #define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ unsigned int __addr; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = guest_NRADDR */ \ "or 2,2,2\n\t" \ "mr %0,3" \ : "=b" (__addr) \ : \ : "cc", "memory", "r3" \ ); \ _zzq_orig->nraddr = __addr; \ } #define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* branch-and-link-to-noredir *%R11 */ \ "or 3,3,3\n\t" #endif /* PLAT_ppc32_linux */ /* ------------------------ ppc64-linux ------------------------ */ #if defined(PLAT_ppc64_linux) typedef struct { unsigned long long int nraddr; /* where's the code? */ unsigned long long int r2; /* what tocptr do we need? */ } OrigFn; #define __SPECIAL_INSTRUCTION_PREAMBLE \ "rotldi 0,0,3 ; rotldi 0,0,13\n\t" \ "rotldi 0,0,61 ; rotldi 0,0,51\n\t" #define VALGRIND_DO_CLIENT_REQUEST( \ _zzq_rlval, _zzq_default, _zzq_request, \ _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ \ { unsigned long long int _zzq_args[6]; \ register unsigned long long int _zzq_result __asm__("r3"); \ register unsigned long long int* _zzq_ptr __asm__("r4"); \ _zzq_args[0] = (unsigned long long int)(_zzq_request); \ _zzq_args[1] = (unsigned long long int)(_zzq_arg1); \ _zzq_args[2] = (unsigned long long int)(_zzq_arg2); \ _zzq_args[3] = (unsigned long long int)(_zzq_arg3); \ _zzq_args[4] = (unsigned long long int)(_zzq_arg4); \ _zzq_args[5] = (unsigned long long int)(_zzq_arg5); \ _zzq_ptr = _zzq_args; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = client_request ( %R4 ) */ \ "or 1,1,1" \ : "=r" (_zzq_result) \ : "0" (_zzq_default), "r" (_zzq_ptr) \ : "cc", "memory"); \ _zzq_rlval = _zzq_result; \ } #define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ register unsigned long long int __addr __asm__("r3"); \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = guest_NRADDR */ \ "or 2,2,2" \ : "=r" (__addr) \ : \ : "cc", "memory" \ ); \ _zzq_orig->nraddr = __addr; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = guest_NRADDR_GPR2 */ \ "or 4,4,4" \ : "=r" (__addr) \ : \ : "cc", "memory" \ ); \ _zzq_orig->r2 = __addr; \ } #define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* branch-and-link-to-noredir *%R11 */ \ "or 3,3,3\n\t" #endif /* PLAT_ppc64_linux */ /* ------------------------ ppc32-aix5 ------------------------- */ #if defined(PLAT_ppc32_aix5) typedef struct { unsigned int nraddr; /* where's the code? */ unsigned int r2; /* what tocptr do we need? */ } OrigFn; #define __SPECIAL_INSTRUCTION_PREAMBLE \ "rlwinm 0,0,3,0,0 ; rlwinm 0,0,13,0,0\n\t" \ "rlwinm 0,0,29,0,0 ; rlwinm 0,0,19,0,0\n\t" #define VALGRIND_DO_CLIENT_REQUEST( \ _zzq_rlval, _zzq_default, _zzq_request, \ _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ \ { unsigned int _zzq_args[7]; \ register unsigned int _zzq_result; \ register unsigned int* _zzq_ptr; \ _zzq_args[0] = (unsigned int)(_zzq_request); \ _zzq_args[1] = (unsigned int)(_zzq_arg1); \ _zzq_args[2] = (unsigned int)(_zzq_arg2); \ _zzq_args[3] = (unsigned int)(_zzq_arg3); \ _zzq_args[4] = (unsigned int)(_zzq_arg4); \ _zzq_args[5] = (unsigned int)(_zzq_arg5); \ _zzq_args[6] = (unsigned int)(_zzq_default); \ _zzq_ptr = _zzq_args; \ __asm__ volatile("mr 4,%1\n\t" \ "lwz 3, 24(4)\n\t" \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = client_request ( %R4 ) */ \ "or 1,1,1\n\t" \ "mr %0,3" \ : "=b" (_zzq_result) \ : "b" (_zzq_ptr) \ : "r3", "r4", "cc", "memory"); \ _zzq_rlval = _zzq_result; \ } #define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ register unsigned int __addr; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = guest_NRADDR */ \ "or 2,2,2\n\t" \ "mr %0,3" \ : "=b" (__addr) \ : \ : "r3", "cc", "memory" \ ); \ _zzq_orig->nraddr = __addr; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = guest_NRADDR_GPR2 */ \ "or 4,4,4\n\t" \ "mr %0,3" \ : "=b" (__addr) \ : \ : "r3", "cc", "memory" \ ); \ _zzq_orig->r2 = __addr; \ } #define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* branch-and-link-to-noredir *%R11 */ \ "or 3,3,3\n\t" #endif /* PLAT_ppc32_aix5 */ /* ------------------------ ppc64-aix5 ------------------------- */ #if defined(PLAT_ppc64_aix5) typedef struct { unsigned long long int nraddr; /* where's the code? */ unsigned long long int r2; /* what tocptr do we need? */ } OrigFn; #define __SPECIAL_INSTRUCTION_PREAMBLE \ "rotldi 0,0,3 ; rotldi 0,0,13\n\t" \ "rotldi 0,0,61 ; rotldi 0,0,51\n\t" #define VALGRIND_DO_CLIENT_REQUEST( \ _zzq_rlval, _zzq_default, _zzq_request, \ _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ \ { unsigned long long int _zzq_args[7]; \ register unsigned long long int _zzq_result; \ register unsigned long long int* _zzq_ptr; \ _zzq_args[0] = (unsigned int long long)(_zzq_request); \ _zzq_args[1] = (unsigned int long long)(_zzq_arg1); \ _zzq_args[2] = (unsigned int long long)(_zzq_arg2); \ _zzq_args[3] = (unsigned int long long)(_zzq_arg3); \ _zzq_args[4] = (unsigned int long long)(_zzq_arg4); \ _zzq_args[5] = (unsigned int long long)(_zzq_arg5); \ _zzq_args[6] = (unsigned int long long)(_zzq_default); \ _zzq_ptr = _zzq_args; \ __asm__ volatile("mr 4,%1\n\t" \ "ld 3, 48(4)\n\t" \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = client_request ( %R4 ) */ \ "or 1,1,1\n\t" \ "mr %0,3" \ : "=b" (_zzq_result) \ : "b" (_zzq_ptr) \ : "r3", "r4", "cc", "memory"); \ _zzq_rlval = _zzq_result; \ } #define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ register unsigned long long int __addr; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = guest_NRADDR */ \ "or 2,2,2\n\t" \ "mr %0,3" \ : "=b" (__addr) \ : \ : "r3", "cc", "memory" \ ); \ _zzq_orig->nraddr = __addr; \ __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ /* %R3 = guest_NRADDR_GPR2 */ \ "or 4,4,4\n\t" \ "mr %0,3" \ : "=b" (__addr) \ : \ : "r3", "cc", "memory" \ ); \ _zzq_orig->r2 = __addr; \ } #define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ __SPECIAL_INSTRUCTION_PREAMBLE \ /* branch-and-link-to-noredir *%R11 */ \ "or 3,3,3\n\t" #endif /* PLAT_ppc64_aix5 */ /* Insert assembly code for other platforms here... */ #endif /* NVALGRIND */ /* ------------------------------------------------------------------ */ /* PLATFORM SPECIFICS for FUNCTION WRAPPING. This is all very */ /* ugly. It's the least-worst tradeoff I can think of. */ /* ------------------------------------------------------------------ */ /* This section defines magic (a.k.a appalling-hack) macros for doing guaranteed-no-redirection macros, so as to get from function wrappers to the functions they are wrapping. The whole point is to construct standard call sequences, but to do the call itself with a special no-redirect call pseudo-instruction that the JIT understands and handles specially. This section is long and repetitious, and I can't see a way to make it shorter. The naming scheme is as follows: CALL_FN_{W,v}_{v,W,WW,WWW,WWWW,5W,6W,7W,etc} 'W' stands for "word" and 'v' for "void". Hence there are different macros for calling arity 0, 1, 2, 3, 4, etc, functions, and for each, the possibility of returning a word-typed result, or no result. */ /* Use these to write the name of your wrapper. NOTE: duplicates VG_WRAP_FUNCTION_Z{U,Z} in pub_tool_redir.h. */ #define I_WRAP_SONAME_FNNAME_ZU(soname,fnname) \ _vgwZU_##soname##_##fnname #define I_WRAP_SONAME_FNNAME_ZZ(soname,fnname) \ _vgwZZ_##soname##_##fnname /* Use this macro from within a wrapper function to collect the context (address and possibly other info) of the original function. Once you have that you can then use it in one of the CALL_FN_ macros. The type of the argument _lval is OrigFn. */ #define VALGRIND_GET_ORIG_FN(_lval) VALGRIND_GET_NR_CONTEXT(_lval) /* Derivatives of the main macros below, for calling functions returning void. */ #define CALL_FN_v_v(fnptr) \ do { volatile unsigned long _junk; \ CALL_FN_W_v(_junk,fnptr); } while (0) #define CALL_FN_v_W(fnptr, arg1) \ do { volatile unsigned long _junk; \ CALL_FN_W_W(_junk,fnptr,arg1); } while (0) #define CALL_FN_v_WW(fnptr, arg1,arg2) \ do { volatile unsigned long _junk; \ CALL_FN_W_WW(_junk,fnptr,arg1,arg2); } while (0) #define CALL_FN_v_WWW(fnptr, arg1,arg2,arg3) \ do { volatile unsigned long _junk; \ CALL_FN_W_WWW(_junk,fnptr,arg1,arg2,arg3); } while (0) /* ------------------------- x86-linux ------------------------- */ #if defined(PLAT_x86_linux) /* These regs are trashed by the hidden call. No need to mention eax as gcc can already see that, plus causes gcc to bomb. */ #define __CALLER_SAVED_REGS /*"eax"*/ "ecx", "edx" /* These CALL_FN_ macros assume that on x86-linux, sizeof(unsigned long) == 4. */ #define CALL_FN_W_v(lval, orig) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[1]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ __asm__ volatile( \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_W(lval, orig, arg1) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[2]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ __asm__ volatile( \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $4, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WW(lval, orig, arg1,arg2) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ __asm__ volatile( \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $8, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[4]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ __asm__ volatile( \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $12, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[5]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ __asm__ volatile( \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $16, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[6]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ __asm__ volatile( \ "pushl 20(%%eax)\n\t" \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $20, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[7]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ __asm__ volatile( \ "pushl 24(%%eax)\n\t" \ "pushl 20(%%eax)\n\t" \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $24, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[8]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ __asm__ volatile( \ "pushl 28(%%eax)\n\t" \ "pushl 24(%%eax)\n\t" \ "pushl 20(%%eax)\n\t" \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $28, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[9]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ __asm__ volatile( \ "pushl 32(%%eax)\n\t" \ "pushl 28(%%eax)\n\t" \ "pushl 24(%%eax)\n\t" \ "pushl 20(%%eax)\n\t" \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $32, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[10]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ _argvec[9] = (unsigned long)(arg9); \ __asm__ volatile( \ "pushl 36(%%eax)\n\t" \ "pushl 32(%%eax)\n\t" \ "pushl 28(%%eax)\n\t" \ "pushl 24(%%eax)\n\t" \ "pushl 20(%%eax)\n\t" \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $36, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[11]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ _argvec[9] = (unsigned long)(arg9); \ _argvec[10] = (unsigned long)(arg10); \ __asm__ volatile( \ "pushl 40(%%eax)\n\t" \ "pushl 36(%%eax)\n\t" \ "pushl 32(%%eax)\n\t" \ "pushl 28(%%eax)\n\t" \ "pushl 24(%%eax)\n\t" \ "pushl 20(%%eax)\n\t" \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $40, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ arg6,arg7,arg8,arg9,arg10, \ arg11) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[12]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ _argvec[9] = (unsigned long)(arg9); \ _argvec[10] = (unsigned long)(arg10); \ _argvec[11] = (unsigned long)(arg11); \ __asm__ volatile( \ "pushl 44(%%eax)\n\t" \ "pushl 40(%%eax)\n\t" \ "pushl 36(%%eax)\n\t" \ "pushl 32(%%eax)\n\t" \ "pushl 28(%%eax)\n\t" \ "pushl 24(%%eax)\n\t" \ "pushl 20(%%eax)\n\t" \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $44, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ arg6,arg7,arg8,arg9,arg10, \ arg11,arg12) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[13]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ _argvec[9] = (unsigned long)(arg9); \ _argvec[10] = (unsigned long)(arg10); \ _argvec[11] = (unsigned long)(arg11); \ _argvec[12] = (unsigned long)(arg12); \ __asm__ volatile( \ "pushl 48(%%eax)\n\t" \ "pushl 44(%%eax)\n\t" \ "pushl 40(%%eax)\n\t" \ "pushl 36(%%eax)\n\t" \ "pushl 32(%%eax)\n\t" \ "pushl 28(%%eax)\n\t" \ "pushl 24(%%eax)\n\t" \ "pushl 20(%%eax)\n\t" \ "pushl 16(%%eax)\n\t" \ "pushl 12(%%eax)\n\t" \ "pushl 8(%%eax)\n\t" \ "pushl 4(%%eax)\n\t" \ "movl (%%eax), %%eax\n\t" /* target->%eax */ \ VALGRIND_CALL_NOREDIR_EAX \ "addl $48, %%esp\n" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #endif /* PLAT_x86_linux */ /* ------------------------ amd64-linux ------------------------ */ #if defined(PLAT_amd64_linux) /* ARGREGS: rdi rsi rdx rcx r8 r9 (the rest on stack in R-to-L order) */ /* These regs are trashed by the hidden call. */ #define __CALLER_SAVED_REGS /*"rax",*/ "rcx", "rdx", "rsi", \ "rdi", "r8", "r9", "r10", "r11" /* These CALL_FN_ macros assume that on amd64-linux, sizeof(unsigned long) == 8. */ /* NB 9 Sept 07. There is a nasty kludge here in all these CALL_FN_ macros. In order not to trash the stack redzone, we need to drop %rsp by 128 before the hidden call, and restore afterwards. The nastyness is that it is only by luck that the stack still appears to be unwindable during the hidden call - since then the behaviour of any routine using this macro does not match what the CFI data says. Sigh. Why is this important? Imagine that a wrapper has a stack allocated local, and passes to the hidden call, a pointer to it. Because gcc does not know about the hidden call, it may allocate that local in the redzone. Unfortunately the hidden call may then trash it before it comes to use it. So we must step clear of the redzone, for the duration of the hidden call, to make it safe. Probably the same problem afflicts the other redzone-style ABIs too (ppc64-linux, ppc32-aix5, ppc64-aix5); but for those, the stack is self describing (none of this CFI nonsense) so at least messing with the stack pointer doesn't give a danger of non-unwindable stack. */ #define CALL_FN_W_v(lval, orig) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[1]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_W(lval, orig, arg1) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[2]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WW(lval, orig, arg1,arg2) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[4]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[5]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[6]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "movq 40(%%rax), %%r8\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[7]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "movq 48(%%rax), %%r9\n\t" \ "movq 40(%%rax), %%r8\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ "addq $128,%%rsp\n\t" \ VALGRIND_CALL_NOREDIR_RAX \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[8]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "pushq 56(%%rax)\n\t" \ "movq 48(%%rax), %%r9\n\t" \ "movq 40(%%rax), %%r8\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $8, %%rsp\n" \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[9]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "pushq 64(%%rax)\n\t" \ "pushq 56(%%rax)\n\t" \ "movq 48(%%rax), %%r9\n\t" \ "movq 40(%%rax), %%r8\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $16, %%rsp\n" \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[10]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ _argvec[9] = (unsigned long)(arg9); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "pushq 72(%%rax)\n\t" \ "pushq 64(%%rax)\n\t" \ "pushq 56(%%rax)\n\t" \ "movq 48(%%rax), %%r9\n\t" \ "movq 40(%%rax), %%r8\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $24, %%rsp\n" \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[11]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ _argvec[9] = (unsigned long)(arg9); \ _argvec[10] = (unsigned long)(arg10); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "pushq 80(%%rax)\n\t" \ "pushq 72(%%rax)\n\t" \ "pushq 64(%%rax)\n\t" \ "pushq 56(%%rax)\n\t" \ "movq 48(%%rax), %%r9\n\t" \ "movq 40(%%rax), %%r8\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $32, %%rsp\n" \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[12]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ _argvec[9] = (unsigned long)(arg9); \ _argvec[10] = (unsigned long)(arg10); \ _argvec[11] = (unsigned long)(arg11); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "pushq 88(%%rax)\n\t" \ "pushq 80(%%rax)\n\t" \ "pushq 72(%%rax)\n\t" \ "pushq 64(%%rax)\n\t" \ "pushq 56(%%rax)\n\t" \ "movq 48(%%rax), %%r9\n\t" \ "movq 40(%%rax), %%r8\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $40, %%rsp\n" \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11,arg12) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[13]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)(arg1); \ _argvec[2] = (unsigned long)(arg2); \ _argvec[3] = (unsigned long)(arg3); \ _argvec[4] = (unsigned long)(arg4); \ _argvec[5] = (unsigned long)(arg5); \ _argvec[6] = (unsigned long)(arg6); \ _argvec[7] = (unsigned long)(arg7); \ _argvec[8] = (unsigned long)(arg8); \ _argvec[9] = (unsigned long)(arg9); \ _argvec[10] = (unsigned long)(arg10); \ _argvec[11] = (unsigned long)(arg11); \ _argvec[12] = (unsigned long)(arg12); \ __asm__ volatile( \ "subq $128,%%rsp\n\t" \ "pushq 96(%%rax)\n\t" \ "pushq 88(%%rax)\n\t" \ "pushq 80(%%rax)\n\t" \ "pushq 72(%%rax)\n\t" \ "pushq 64(%%rax)\n\t" \ "pushq 56(%%rax)\n\t" \ "movq 48(%%rax), %%r9\n\t" \ "movq 40(%%rax), %%r8\n\t" \ "movq 32(%%rax), %%rcx\n\t" \ "movq 24(%%rax), %%rdx\n\t" \ "movq 16(%%rax), %%rsi\n\t" \ "movq 8(%%rax), %%rdi\n\t" \ "movq (%%rax), %%rax\n\t" /* target->%rax */ \ VALGRIND_CALL_NOREDIR_RAX \ "addq $48, %%rsp\n" \ "addq $128,%%rsp\n\t" \ : /*out*/ "=a" (_res) \ : /*in*/ "a" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #endif /* PLAT_amd64_linux */ /* ------------------------ ppc32-linux ------------------------ */ #if defined(PLAT_ppc32_linux) /* This is useful for finding out about the on-stack stuff: extern int f9 ( int,int,int,int,int,int,int,int,int ); extern int f10 ( int,int,int,int,int,int,int,int,int,int ); extern int f11 ( int,int,int,int,int,int,int,int,int,int,int ); extern int f12 ( int,int,int,int,int,int,int,int,int,int,int,int ); int g9 ( void ) { return f9(11,22,33,44,55,66,77,88,99); } int g10 ( void ) { return f10(11,22,33,44,55,66,77,88,99,110); } int g11 ( void ) { return f11(11,22,33,44,55,66,77,88,99,110,121); } int g12 ( void ) { return f12(11,22,33,44,55,66,77,88,99,110,121,132); } */ /* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ /* These regs are trashed by the hidden call. */ #define __CALLER_SAVED_REGS \ "lr", "ctr", "xer", \ "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ "r11", "r12", "r13" /* These CALL_FN_ macros assume that on ppc32-linux, sizeof(unsigned long) == 4. */ #define CALL_FN_W_v(lval, orig) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[1]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_W(lval, orig, arg1) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[2]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WW(lval, orig, arg1,arg2) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[4]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[5]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[6]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ _argvec[5] = (unsigned long)arg5; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 7,20(11)\n\t" \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[7]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ _argvec[5] = (unsigned long)arg5; \ _argvec[6] = (unsigned long)arg6; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 7,20(11)\n\t" \ "lwz 8,24(11)\n\t" \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[8]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ _argvec[5] = (unsigned long)arg5; \ _argvec[6] = (unsigned long)arg6; \ _argvec[7] = (unsigned long)arg7; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 7,20(11)\n\t" \ "lwz 8,24(11)\n\t" \ "lwz 9,28(11)\n\t" \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[9]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ _argvec[5] = (unsigned long)arg5; \ _argvec[6] = (unsigned long)arg6; \ _argvec[7] = (unsigned long)arg7; \ _argvec[8] = (unsigned long)arg8; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 7,20(11)\n\t" \ "lwz 8,24(11)\n\t" \ "lwz 9,28(11)\n\t" \ "lwz 10,32(11)\n\t" /* arg8->r10 */ \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[10]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ _argvec[5] = (unsigned long)arg5; \ _argvec[6] = (unsigned long)arg6; \ _argvec[7] = (unsigned long)arg7; \ _argvec[8] = (unsigned long)arg8; \ _argvec[9] = (unsigned long)arg9; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "addi 1,1,-16\n\t" \ /* arg9 */ \ "lwz 3,36(11)\n\t" \ "stw 3,8(1)\n\t" \ /* args1-8 */ \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 7,20(11)\n\t" \ "lwz 8,24(11)\n\t" \ "lwz 9,28(11)\n\t" \ "lwz 10,32(11)\n\t" /* arg8->r10 */ \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "addi 1,1,16\n\t" \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[11]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ _argvec[5] = (unsigned long)arg5; \ _argvec[6] = (unsigned long)arg6; \ _argvec[7] = (unsigned long)arg7; \ _argvec[8] = (unsigned long)arg8; \ _argvec[9] = (unsigned long)arg9; \ _argvec[10] = (unsigned long)arg10; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "addi 1,1,-16\n\t" \ /* arg10 */ \ "lwz 3,40(11)\n\t" \ "stw 3,12(1)\n\t" \ /* arg9 */ \ "lwz 3,36(11)\n\t" \ "stw 3,8(1)\n\t" \ /* args1-8 */ \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 7,20(11)\n\t" \ "lwz 8,24(11)\n\t" \ "lwz 9,28(11)\n\t" \ "lwz 10,32(11)\n\t" /* arg8->r10 */ \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "addi 1,1,16\n\t" \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[12]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ _argvec[5] = (unsigned long)arg5; \ _argvec[6] = (unsigned long)arg6; \ _argvec[7] = (unsigned long)arg7; \ _argvec[8] = (unsigned long)arg8; \ _argvec[9] = (unsigned long)arg9; \ _argvec[10] = (unsigned long)arg10; \ _argvec[11] = (unsigned long)arg11; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "addi 1,1,-32\n\t" \ /* arg11 */ \ "lwz 3,44(11)\n\t" \ "stw 3,16(1)\n\t" \ /* arg10 */ \ "lwz 3,40(11)\n\t" \ "stw 3,12(1)\n\t" \ /* arg9 */ \ "lwz 3,36(11)\n\t" \ "stw 3,8(1)\n\t" \ /* args1-8 */ \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 7,20(11)\n\t" \ "lwz 8,24(11)\n\t" \ "lwz 9,28(11)\n\t" \ "lwz 10,32(11)\n\t" /* arg8->r10 */ \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "addi 1,1,32\n\t" \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11,arg12) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[13]; \ volatile unsigned long _res; \ _argvec[0] = (unsigned long)_orig.nraddr; \ _argvec[1] = (unsigned long)arg1; \ _argvec[2] = (unsigned long)arg2; \ _argvec[3] = (unsigned long)arg3; \ _argvec[4] = (unsigned long)arg4; \ _argvec[5] = (unsigned long)arg5; \ _argvec[6] = (unsigned long)arg6; \ _argvec[7] = (unsigned long)arg7; \ _argvec[8] = (unsigned long)arg8; \ _argvec[9] = (unsigned long)arg9; \ _argvec[10] = (unsigned long)arg10; \ _argvec[11] = (unsigned long)arg11; \ _argvec[12] = (unsigned long)arg12; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "addi 1,1,-32\n\t" \ /* arg12 */ \ "lwz 3,48(11)\n\t" \ "stw 3,20(1)\n\t" \ /* arg11 */ \ "lwz 3,44(11)\n\t" \ "stw 3,16(1)\n\t" \ /* arg10 */ \ "lwz 3,40(11)\n\t" \ "stw 3,12(1)\n\t" \ /* arg9 */ \ "lwz 3,36(11)\n\t" \ "stw 3,8(1)\n\t" \ /* args1-8 */ \ "lwz 3,4(11)\n\t" /* arg1->r3 */ \ "lwz 4,8(11)\n\t" \ "lwz 5,12(11)\n\t" \ "lwz 6,16(11)\n\t" /* arg4->r6 */ \ "lwz 7,20(11)\n\t" \ "lwz 8,24(11)\n\t" \ "lwz 9,28(11)\n\t" \ "lwz 10,32(11)\n\t" /* arg8->r10 */ \ "lwz 11,0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "addi 1,1,32\n\t" \ "mr %0,3" \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[0]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #endif /* PLAT_ppc32_linux */ /* ------------------------ ppc64-linux ------------------------ */ #if defined(PLAT_ppc64_linux) /* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ /* These regs are trashed by the hidden call. */ #define __CALLER_SAVED_REGS \ "lr", "ctr", "xer", \ "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ "r11", "r12", "r13" /* These CALL_FN_ macros assume that on ppc64-linux, sizeof(unsigned long) == 8. */ #define CALL_FN_W_v(lval, orig) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+0]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_W(lval, orig, arg1) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+1]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WW(lval, orig, arg1,arg2) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+2]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+3]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+4]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+5]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+6]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+7]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+8]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)" /* restore tocptr */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+9]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "addi 1,1,-128\n\t" /* expand stack frame */ \ /* arg9 */ \ "ld 3,72(11)\n\t" \ "std 3,112(1)\n\t" \ /* args1-8 */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ "addi 1,1,128" /* restore frame */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+10]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "addi 1,1,-128\n\t" /* expand stack frame */ \ /* arg10 */ \ "ld 3,80(11)\n\t" \ "std 3,120(1)\n\t" \ /* arg9 */ \ "ld 3,72(11)\n\t" \ "std 3,112(1)\n\t" \ /* args1-8 */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ "addi 1,1,128" /* restore frame */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+11]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ _argvec[2+11] = (unsigned long)arg11; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "addi 1,1,-144\n\t" /* expand stack frame */ \ /* arg11 */ \ "ld 3,88(11)\n\t" \ "std 3,128(1)\n\t" \ /* arg10 */ \ "ld 3,80(11)\n\t" \ "std 3,120(1)\n\t" \ /* arg9 */ \ "ld 3,72(11)\n\t" \ "std 3,112(1)\n\t" \ /* args1-8 */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ "addi 1,1,144" /* restore frame */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11,arg12) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+12]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ _argvec[2+11] = (unsigned long)arg11; \ _argvec[2+12] = (unsigned long)arg12; \ __asm__ volatile( \ "mr 11,%1\n\t" \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "addi 1,1,-144\n\t" /* expand stack frame */ \ /* arg12 */ \ "ld 3,96(11)\n\t" \ "std 3,136(1)\n\t" \ /* arg11 */ \ "ld 3,88(11)\n\t" \ "std 3,128(1)\n\t" \ /* arg10 */ \ "ld 3,80(11)\n\t" \ "std 3,120(1)\n\t" \ /* arg9 */ \ "ld 3,72(11)\n\t" \ "std 3,112(1)\n\t" \ /* args1-8 */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ "addi 1,1,144" /* restore frame */ \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #endif /* PLAT_ppc64_linux */ /* ------------------------ ppc32-aix5 ------------------------- */ #if defined(PLAT_ppc32_aix5) /* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ /* These regs are trashed by the hidden call. */ #define __CALLER_SAVED_REGS \ "lr", "ctr", "xer", \ "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ "r11", "r12", "r13" /* Expand the stack frame, copying enough info that unwinding still works. Trashes r3. */ #define VG_EXPAND_FRAME_BY_trashes_r3(_n_fr) \ "addi 1,1,-" #_n_fr "\n\t" \ "lwz 3," #_n_fr "(1)\n\t" \ "stw 3,0(1)\n\t" #define VG_CONTRACT_FRAME_BY(_n_fr) \ "addi 1,1," #_n_fr "\n\t" /* These CALL_FN_ macros assume that on ppc32-aix5, sizeof(unsigned long) == 4. */ #define CALL_FN_W_v(lval, orig) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+0]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_W(lval, orig, arg1) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+1]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WW(lval, orig, arg1,arg2) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+2]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+3]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+4]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+5]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+6]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+7]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+8]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+9]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ VG_EXPAND_FRAME_BY_trashes_r3(64) \ /* arg9 */ \ "lwz 3,36(11)\n\t" \ "stw 3,56(1)\n\t" \ /* args1-8 */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(64) \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+10]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ VG_EXPAND_FRAME_BY_trashes_r3(64) \ /* arg10 */ \ "lwz 3,40(11)\n\t" \ "stw 3,60(1)\n\t" \ /* arg9 */ \ "lwz 3,36(11)\n\t" \ "stw 3,56(1)\n\t" \ /* args1-8 */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(64) \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+11]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ _argvec[2+11] = (unsigned long)arg11; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ VG_EXPAND_FRAME_BY_trashes_r3(72) \ /* arg11 */ \ "lwz 3,44(11)\n\t" \ "stw 3,64(1)\n\t" \ /* arg10 */ \ "lwz 3,40(11)\n\t" \ "stw 3,60(1)\n\t" \ /* arg9 */ \ "lwz 3,36(11)\n\t" \ "stw 3,56(1)\n\t" \ /* args1-8 */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(72) \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11,arg12) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+12]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ _argvec[2+11] = (unsigned long)arg11; \ _argvec[2+12] = (unsigned long)arg12; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "stw 2,-8(11)\n\t" /* save tocptr */ \ "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ VG_EXPAND_FRAME_BY_trashes_r3(72) \ /* arg12 */ \ "lwz 3,48(11)\n\t" \ "stw 3,68(1)\n\t" \ /* arg11 */ \ "lwz 3,44(11)\n\t" \ "stw 3,64(1)\n\t" \ /* arg10 */ \ "lwz 3,40(11)\n\t" \ "stw 3,60(1)\n\t" \ /* arg9 */ \ "lwz 3,36(11)\n\t" \ "stw 3,56(1)\n\t" \ /* args1-8 */ \ "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ "lwz 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "lwz 2,-8(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(72) \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #endif /* PLAT_ppc32_aix5 */ /* ------------------------ ppc64-aix5 ------------------------- */ #if defined(PLAT_ppc64_aix5) /* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ /* These regs are trashed by the hidden call. */ #define __CALLER_SAVED_REGS \ "lr", "ctr", "xer", \ "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ "r11", "r12", "r13" /* Expand the stack frame, copying enough info that unwinding still works. Trashes r3. */ #define VG_EXPAND_FRAME_BY_trashes_r3(_n_fr) \ "addi 1,1,-" #_n_fr "\n\t" \ "ld 3," #_n_fr "(1)\n\t" \ "std 3,0(1)\n\t" #define VG_CONTRACT_FRAME_BY(_n_fr) \ "addi 1,1," #_n_fr "\n\t" /* These CALL_FN_ macros assume that on ppc64-aix5, sizeof(unsigned long) == 8. */ #define CALL_FN_W_v(lval, orig) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+0]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_W(lval, orig, arg1) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+1]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WW(lval, orig, arg1,arg2) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+2]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+3]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+4]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+5]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+6]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+7]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+8]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+9]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ VG_EXPAND_FRAME_BY_trashes_r3(128) \ /* arg9 */ \ "ld 3,72(11)\n\t" \ "std 3,112(1)\n\t" \ /* args1-8 */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(128) \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+10]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ VG_EXPAND_FRAME_BY_trashes_r3(128) \ /* arg10 */ \ "ld 3,80(11)\n\t" \ "std 3,120(1)\n\t" \ /* arg9 */ \ "ld 3,72(11)\n\t" \ "std 3,112(1)\n\t" \ /* args1-8 */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(128) \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+11]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ _argvec[2+11] = (unsigned long)arg11; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ VG_EXPAND_FRAME_BY_trashes_r3(144) \ /* arg11 */ \ "ld 3,88(11)\n\t" \ "std 3,128(1)\n\t" \ /* arg10 */ \ "ld 3,80(11)\n\t" \ "std 3,120(1)\n\t" \ /* arg9 */ \ "ld 3,72(11)\n\t" \ "std 3,112(1)\n\t" \ /* args1-8 */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(144) \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ arg7,arg8,arg9,arg10,arg11,arg12) \ do { \ volatile OrigFn _orig = (orig); \ volatile unsigned long _argvec[3+12]; \ volatile unsigned long _res; \ /* _argvec[0] holds current r2 across the call */ \ _argvec[1] = (unsigned long)_orig.r2; \ _argvec[2] = (unsigned long)_orig.nraddr; \ _argvec[2+1] = (unsigned long)arg1; \ _argvec[2+2] = (unsigned long)arg2; \ _argvec[2+3] = (unsigned long)arg3; \ _argvec[2+4] = (unsigned long)arg4; \ _argvec[2+5] = (unsigned long)arg5; \ _argvec[2+6] = (unsigned long)arg6; \ _argvec[2+7] = (unsigned long)arg7; \ _argvec[2+8] = (unsigned long)arg8; \ _argvec[2+9] = (unsigned long)arg9; \ _argvec[2+10] = (unsigned long)arg10; \ _argvec[2+11] = (unsigned long)arg11; \ _argvec[2+12] = (unsigned long)arg12; \ __asm__ volatile( \ "mr 11,%1\n\t" \ VG_EXPAND_FRAME_BY_trashes_r3(512) \ "std 2,-16(11)\n\t" /* save tocptr */ \ "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ VG_EXPAND_FRAME_BY_trashes_r3(144) \ /* arg12 */ \ "ld 3,96(11)\n\t" \ "std 3,136(1)\n\t" \ /* arg11 */ \ "ld 3,88(11)\n\t" \ "std 3,128(1)\n\t" \ /* arg10 */ \ "ld 3,80(11)\n\t" \ "std 3,120(1)\n\t" \ /* arg9 */ \ "ld 3,72(11)\n\t" \ "std 3,112(1)\n\t" \ /* args1-8 */ \ "ld 3, 8(11)\n\t" /* arg1->r3 */ \ "ld 4, 16(11)\n\t" /* arg2->r4 */ \ "ld 5, 24(11)\n\t" /* arg3->r5 */ \ "ld 6, 32(11)\n\t" /* arg4->r6 */ \ "ld 7, 40(11)\n\t" /* arg5->r7 */ \ "ld 8, 48(11)\n\t" /* arg6->r8 */ \ "ld 9, 56(11)\n\t" /* arg7->r9 */ \ "ld 10, 64(11)\n\t" /* arg8->r10 */ \ "ld 11, 0(11)\n\t" /* target->r11 */ \ VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ "mr 11,%1\n\t" \ "mr %0,3\n\t" \ "ld 2,-16(11)\n\t" /* restore tocptr */ \ VG_CONTRACT_FRAME_BY(144) \ VG_CONTRACT_FRAME_BY(512) \ : /*out*/ "=r" (_res) \ : /*in*/ "r" (&_argvec[2]) \ : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ ); \ lval = (__typeof__(lval)) _res; \ } while (0) #endif /* PLAT_ppc64_aix5 */ /* ------------------------------------------------------------------ */ /* ARCHITECTURE INDEPENDENT MACROS for CLIENT REQUESTS. */ /* */ /* ------------------------------------------------------------------ */ /* Some request codes. There are many more of these, but most are not exposed to end-user view. These are the public ones, all of the form 0x1000 + small_number. Core ones are in the range 0x00000000--0x0000ffff. The non-public ones start at 0x2000. */ /* These macros are used by tools -- they must be public, but don't embed them into other programs. */ #define VG_USERREQ_TOOL_BASE(a,b) \ ((unsigned int)(((a)&0xff) << 24 | ((b)&0xff) << 16)) #define VG_IS_TOOL_USERREQ(a, b, v) \ (VG_USERREQ_TOOL_BASE(a,b) == ((v) & 0xffff0000)) /* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !! This enum comprises an ABI exported by Valgrind to programs which use client requests. DO NOT CHANGE THE ORDER OF THESE ENTRIES, NOR DELETE ANY -- add new ones at the end. */ typedef enum { VG_USERREQ__RUNNING_ON_VALGRIND = 0x1001, VG_USERREQ__DISCARD_TRANSLATIONS = 0x1002, /* These allow any function to be called from the simulated CPU but run on the real CPU. Nb: the first arg passed to the function is always the ThreadId of the running thread! So CLIENT_CALL0 actually requires a 1 arg function, etc. */ VG_USERREQ__CLIENT_CALL0 = 0x1101, VG_USERREQ__CLIENT_CALL1 = 0x1102, VG_USERREQ__CLIENT_CALL2 = 0x1103, VG_USERREQ__CLIENT_CALL3 = 0x1104, /* Can be useful in regression testing suites -- eg. can send Valgrind's output to /dev/null and still count errors. */ VG_USERREQ__COUNT_ERRORS = 0x1201, /* These are useful and can be interpreted by any tool that tracks malloc() et al, by using vg_replace_malloc.c. */ VG_USERREQ__MALLOCLIKE_BLOCK = 0x1301, VG_USERREQ__FREELIKE_BLOCK = 0x1302, /* Memory pool support. */ VG_USERREQ__CREATE_MEMPOOL = 0x1303, VG_USERREQ__DESTROY_MEMPOOL = 0x1304, VG_USERREQ__MEMPOOL_ALLOC = 0x1305, VG_USERREQ__MEMPOOL_FREE = 0x1306, VG_USERREQ__MEMPOOL_TRIM = 0x1307, VG_USERREQ__MOVE_MEMPOOL = 0x1308, VG_USERREQ__MEMPOOL_CHANGE = 0x1309, VG_USERREQ__MEMPOOL_EXISTS = 0x130a, /* Allow printfs to valgrind log. */ VG_USERREQ__PRINTF = 0x1401, VG_USERREQ__PRINTF_BACKTRACE = 0x1402, /* Stack support. */ VG_USERREQ__STACK_REGISTER = 0x1501, VG_USERREQ__STACK_DEREGISTER = 0x1502, VG_USERREQ__STACK_CHANGE = 0x1503 } Vg_ClientRequest; #if !defined(__GNUC__) # define __extension__ /* */ #endif /* Returns the number of Valgrinds this code is running under. That is, 0 if running natively, 1 if running under Valgrind, 2 if running under Valgrind which is running under another Valgrind, etc. */ #define RUNNING_ON_VALGRIND __extension__ \ ({unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0 /* if not */, \ VG_USERREQ__RUNNING_ON_VALGRIND, \ 0, 0, 0, 0, 0); \ _qzz_res; \ }) /* Discard translation of code in the range [_qzz_addr .. _qzz_addr + _qzz_len - 1]. Useful if you are debugging a JITter or some such, since it provides a way to make sure valgrind will retranslate the invalidated area. Returns no value. */ #define VALGRIND_DISCARD_TRANSLATIONS(_qzz_addr,_qzz_len) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__DISCARD_TRANSLATIONS, \ _qzz_addr, _qzz_len, 0, 0, 0); \ } /* These requests are for getting Valgrind itself to print something. Possibly with a backtrace. This is a really ugly hack. */ #if defined(NVALGRIND) # define VALGRIND_PRINTF(...) # define VALGRIND_PRINTF_BACKTRACE(...) #else /* NVALGRIND */ /* Modern GCC will optimize the static routine out if unused, and unused attribute will shut down warnings about it. */ static int VALGRIND_PRINTF(const char *format, ...) __attribute__((format(__printf__, 1, 2), __unused__)); static int VALGRIND_PRINTF(const char *format, ...) { unsigned long _qzz_res; va_list vargs; va_start(vargs, format); VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, VG_USERREQ__PRINTF, (unsigned long)format, (unsigned long)vargs, 0, 0, 0); va_end(vargs); return (int)_qzz_res; } static int VALGRIND_PRINTF_BACKTRACE(const char *format, ...) __attribute__((format(__printf__, 1, 2), __unused__)); static int VALGRIND_PRINTF_BACKTRACE(const char *format, ...) { unsigned long _qzz_res; va_list vargs; va_start(vargs, format); VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, VG_USERREQ__PRINTF_BACKTRACE, (unsigned long)format, (unsigned long)vargs, 0, 0, 0); va_end(vargs); return (int)_qzz_res; } #endif /* NVALGRIND */ /* These requests allow control to move from the simulated CPU to the real CPU, calling an arbitary function. Note that the current ThreadId is inserted as the first argument. So this call: VALGRIND_NON_SIMD_CALL2(f, arg1, arg2) requires f to have this signature: Word f(Word tid, Word arg1, Word arg2) where "Word" is a word-sized type. Note that these client requests are not entirely reliable. For example, if you call a function with them that subsequently calls printf(), there's a high chance Valgrind will crash. Generally, your prospects of these working are made higher if the called function does not refer to any global variables, and does not refer to any libc or other functions (printf et al). Any kind of entanglement with libc or dynamic linking is likely to have a bad outcome, for tricky reasons which we've grappled with a lot in the past. */ #define VALGRIND_NON_SIMD_CALL0(_qyy_fn) \ __extension__ \ ({unsigned long _qyy_res; \ VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ VG_USERREQ__CLIENT_CALL0, \ _qyy_fn, \ 0, 0, 0, 0); \ _qyy_res; \ }) #define VALGRIND_NON_SIMD_CALL1(_qyy_fn, _qyy_arg1) \ __extension__ \ ({unsigned long _qyy_res; \ VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ VG_USERREQ__CLIENT_CALL1, \ _qyy_fn, \ _qyy_arg1, 0, 0, 0); \ _qyy_res; \ }) #define VALGRIND_NON_SIMD_CALL2(_qyy_fn, _qyy_arg1, _qyy_arg2) \ __extension__ \ ({unsigned long _qyy_res; \ VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ VG_USERREQ__CLIENT_CALL2, \ _qyy_fn, \ _qyy_arg1, _qyy_arg2, 0, 0); \ _qyy_res; \ }) #define VALGRIND_NON_SIMD_CALL3(_qyy_fn, _qyy_arg1, _qyy_arg2, _qyy_arg3) \ __extension__ \ ({unsigned long _qyy_res; \ VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ VG_USERREQ__CLIENT_CALL3, \ _qyy_fn, \ _qyy_arg1, _qyy_arg2, \ _qyy_arg3, 0); \ _qyy_res; \ }) /* Counts the number of errors that have been recorded by a tool. Nb: the tool must record the errors with VG_(maybe_record_error)() or VG_(unique_error)() for them to be counted. */ #define VALGRIND_COUNT_ERRORS \ __extension__ \ ({unsigned int _qyy_res; \ VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ VG_USERREQ__COUNT_ERRORS, \ 0, 0, 0, 0, 0); \ _qyy_res; \ }) /* Mark a block of memory as having been allocated by a malloc()-like function. `addr' is the start of the usable block (ie. after any redzone) `rzB' is redzone size if the allocator can apply redzones; use '0' if not. Adding redzones makes it more likely Valgrind will spot block overruns. `is_zeroed' indicates if the memory is zeroed, as it is for calloc(). Put it immediately after the point where a block is allocated. If you're using Memcheck: If you're allocating memory via superblocks, and then handing out small chunks of each superblock, if you don't have redzones on your small blocks, it's worth marking the superblock with VALGRIND_MAKE_MEM_NOACCESS when it's created, so that block overruns are detected. But if you can put redzones on, it's probably better to not do this, so that messages for small overruns are described in terms of the small block rather than the superblock (but if you have a big overrun that skips over a redzone, you could miss an error this way). See memcheck/tests/custom_alloc.c for an example. WARNING: if your allocator uses malloc() or 'new' to allocate superblocks, rather than mmap() or brk(), this will not work properly -- you'll likely get assertion failures during leak detection. This is because Valgrind doesn't like seeing overlapping heap blocks. Sorry. Nb: block must be freed via a free()-like function specified with VALGRIND_FREELIKE_BLOCK or mismatch errors will occur. */ #define VALGRIND_MALLOCLIKE_BLOCK(addr, sizeB, rzB, is_zeroed) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__MALLOCLIKE_BLOCK, \ addr, sizeB, rzB, is_zeroed, 0); \ } /* Mark a block of memory as having been freed by a free()-like function. `rzB' is redzone size; it must match that given to VALGRIND_MALLOCLIKE_BLOCK. Memory not freed will be detected by the leak checker. Put it immediately after the point where the block is freed. */ #define VALGRIND_FREELIKE_BLOCK(addr, rzB) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__FREELIKE_BLOCK, \ addr, rzB, 0, 0, 0); \ } /* Create a memory pool. */ #define VALGRIND_CREATE_MEMPOOL(pool, rzB, is_zeroed) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__CREATE_MEMPOOL, \ pool, rzB, is_zeroed, 0, 0); \ } /* Destroy a memory pool. */ #define VALGRIND_DESTROY_MEMPOOL(pool) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__DESTROY_MEMPOOL, \ pool, 0, 0, 0, 0); \ } /* Associate a piece of memory with a memory pool. */ #define VALGRIND_MEMPOOL_ALLOC(pool, addr, size) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__MEMPOOL_ALLOC, \ pool, addr, size, 0, 0); \ } /* Disassociate a piece of memory from a memory pool. */ #define VALGRIND_MEMPOOL_FREE(pool, addr) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__MEMPOOL_FREE, \ pool, addr, 0, 0, 0); \ } /* Disassociate any pieces outside a particular range. */ #define VALGRIND_MEMPOOL_TRIM(pool, addr, size) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__MEMPOOL_TRIM, \ pool, addr, size, 0, 0); \ } /* Resize and/or move a piece associated with a memory pool. */ #define VALGRIND_MOVE_MEMPOOL(poolA, poolB) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__MOVE_MEMPOOL, \ poolA, poolB, 0, 0, 0); \ } /* Resize and/or move a piece associated with a memory pool. */ #define VALGRIND_MEMPOOL_CHANGE(pool, addrA, addrB, size) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__MEMPOOL_CHANGE, \ pool, addrA, addrB, size, 0); \ } /* Return 1 if a mempool exists, else 0. */ #define VALGRIND_MEMPOOL_EXISTS(pool) \ ({unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__MEMPOOL_EXISTS, \ pool, 0, 0, 0, 0); \ _qzz_res; \ }) /* Mark a piece of memory as being a stack. Returns a stack id. */ #define VALGRIND_STACK_REGISTER(start, end) \ ({unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__STACK_REGISTER, \ start, end, 0, 0, 0); \ _qzz_res; \ }) /* Unmark the piece of memory associated with a stack id as being a stack. */ #define VALGRIND_STACK_DEREGISTER(id) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__STACK_DEREGISTER, \ id, 0, 0, 0, 0); \ } /* Change the start and end address of the stack id. */ #define VALGRIND_STACK_CHANGE(id, start, end) \ {unsigned int _qzz_res; \ VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ VG_USERREQ__STACK_CHANGE, \ id, start, end, 0, 0); \ } #undef PLAT_x86_linux #undef PLAT_amd64_linux #undef PLAT_ppc32_linux #undef PLAT_ppc64_linux #undef PLAT_ppc32_aix5 #undef PLAT_ppc64_aix5 #endif /* __VALGRIND_H */
Unknown
3D
mcellteam/mcell
libs/gperftools/src/windows/patch_functions.cc
.cc
47,347
1,098
// Copyright (c) 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // --- // Author: Craig Silverstein // // The main purpose of this file is to patch the libc allocation // routines (malloc and friends, but also _msize and other // windows-specific libc-style routines). However, we also patch // windows routines to do accounting. We do better at the former than // the latter. Here are some comments from Paul Pluzhnikov about what // it might take to do a really good job patching windows routines to // keep track of memory usage: // // "You should intercept at least the following: // HeapCreate HeapDestroy HeapAlloc HeapReAlloc HeapFree // RtlCreateHeap RtlDestroyHeap RtlAllocateHeap RtlFreeHeap // malloc calloc realloc free // malloc_dbg calloc_dbg realloc_dbg free_dbg // Some of these call the other ones (but not always), sometimes // recursively (i.e. HeapCreate may call HeapAlloc on a different // heap, IIRC)." // // Since Paul didn't mention VirtualAllocEx, he may not have even been // considering all the mmap-like functions that windows has (or he may // just be ignoring it because he's seen we already patch it). Of the // above, we do not patch the *_dbg functions, and of the windows // functions, we only patch HeapAlloc and HeapFree. // // The *_dbg functions come into play with /MDd, /MTd, and /MLd, // probably. It may be ok to just turn off tcmalloc in those cases -- // if the user wants the windows debug malloc, they probably don't // want tcmalloc! We should also test with all of /MD, /MT, and /ML, // which we're not currently doing. // TODO(csilvers): try to do better here? Paul does conclude: // "Keeping track of all of this was a nightmare." #ifndef _WIN32 # error You should only be including windows/patch_functions.cc in a windows environment! #endif #include <config.h> #ifdef WIN32_OVERRIDE_ALLOCATORS #error This file is intended for patching allocators - use override_functions.cc instead. #endif // We use psapi. Non-MSVC systems will have to link this in themselves. #ifdef _MSC_VER #pragma comment(lib, "Psapi.lib") #endif // Make sure we always use the 'old' names of the psapi functions. #ifndef PSAPI_VERSION #define PSAPI_VERSION 1 #endif #include <windows.h> #include <stdio.h> #include <malloc.h> // for _msize and _expand #include <psapi.h> // for EnumProcessModules, GetModuleInformation, etc. #include <set> #include <map> #include <vector> #include <base/logging.h> #include "base/spinlock.h" #include "gperftools/malloc_hook.h" #include "malloc_hook-inl.h" #include "preamble_patcher.h" // The maximum number of modules we allow to be in one executable const int kMaxModules = 8182; // These are hard-coded, unfortunately. :-( They are also probably // compiler specific. See get_mangled_names.cc, in this directory, // for instructions on how to update these names for your compiler. #ifdef _WIN64 const char kMangledNew[] = "??2@YAPEAX_K@Z"; const char kMangledNewArray[] = "??_U@YAPEAX_K@Z"; const char kMangledDelete[] = "??3@YAXPEAX@Z"; const char kMangledDeleteArray[] = "??_V@YAXPEAX@Z"; const char kMangledNewNothrow[] = "??2@YAPEAX_KAEBUnothrow_t@std@@@Z"; const char kMangledNewArrayNothrow[] = "??_U@YAPEAX_KAEBUnothrow_t@std@@@Z"; const char kMangledDeleteNothrow[] = "??3@YAXPEAXAEBUnothrow_t@std@@@Z"; const char kMangledDeleteArrayNothrow[] = "??_V@YAXPEAXAEBUnothrow_t@std@@@Z"; #else const char kMangledNew[] = "??2@YAPAXI@Z"; const char kMangledNewArray[] = "??_U@YAPAXI@Z"; const char kMangledDelete[] = "??3@YAXPAX@Z"; const char kMangledDeleteArray[] = "??_V@YAXPAX@Z"; const char kMangledNewNothrow[] = "??2@YAPAXIABUnothrow_t@std@@@Z"; const char kMangledNewArrayNothrow[] = "??_U@YAPAXIABUnothrow_t@std@@@Z"; const char kMangledDeleteNothrow[] = "??3@YAXPAXABUnothrow_t@std@@@Z"; const char kMangledDeleteArrayNothrow[] = "??_V@YAXPAXABUnothrow_t@std@@@Z"; #endif // This is an unused but exported symbol that we can use to tell the // MSVC linker to bring in libtcmalloc, via the /INCLUDE linker flag. // Without this, the linker will likely decide that libtcmalloc.dll // doesn't add anything to the executable (since it does all its work // through patching, which the linker can't see), and ignore it // entirely. (The name 'tcmalloc' is already reserved for a // namespace. I'd rather export a variable named "_tcmalloc", but I // couldn't figure out how to get that to work. This function exports // the symbol "__tcmalloc".) extern "C" PERFTOOLS_DLL_DECL void _tcmalloc(); void _tcmalloc() { } // This is the version needed for windows x64, which has a different // decoration scheme which doesn't auto-add a leading underscore. extern "C" PERFTOOLS_DLL_DECL void __tcmalloc(); void __tcmalloc() { } namespace { // most everything here is in an unnamed namespace typedef void (*GenericFnPtr)(); using sidestep::PreamblePatcher; struct ModuleEntryCopy; // defined below // These functions are how we override the memory allocation // functions, just like tcmalloc.cc and malloc_hook.cc do. // This is information about the routines we're patching, for a given // module that implements libc memory routines. A single executable // can have several libc implementations running about (in different // .dll's), and we need to patch/unpatch them all. This defines // everything except the new functions we're patching in, which // are defined in LibcFunctions, below. class LibcInfo { public: LibcInfo() { memset(this, 0, sizeof(*this)); // easiest way to initialize the array } bool patched() const { return is_valid(); } void set_is_valid(bool b) { is_valid_ = b; } // According to http://msdn.microsoft.com/en-us/library/ms684229(VS.85).aspx: // "The load address of a module (lpBaseOfDll) is the same as the HMODULE // value." HMODULE hmodule() const { return reinterpret_cast<HMODULE>(const_cast<void*>(module_base_address_)); } // Populates all the windows_fn_[] vars based on our module info. // Returns false if windows_fn_ is all NULL's, because there's // nothing to patch. Also populates the rest of the module_entry // info, such as the module's name. bool PopulateWindowsFn(const ModuleEntryCopy& module_entry); protected: void CopyFrom(const LibcInfo& that) { if (this == &that) return; this->is_valid_ = that.is_valid_; memcpy(this->windows_fn_, that.windows_fn_, sizeof(windows_fn_)); this->module_base_address_ = that.module_base_address_; this->module_base_size_ = that.module_base_size_; } enum { kMalloc, kFree, kRealloc, kCalloc, kNew, kNewArray, kDelete, kDeleteArray, kNewNothrow, kNewArrayNothrow, kDeleteNothrow, kDeleteArrayNothrow, // These are windows-only functions from malloc.h k_Msize, k_Expand, // A MS CRT "internal" function, implemented using _calloc_impl k_CallocCrt, // Underlying deallocation functions called by CRT internal functions or operator delete kFreeBase, kFreeDbg, kNumFunctions }; // I'd like to put these together in a struct (perhaps in the // subclass, so we can put in perftools_fn_ as well), but vc8 seems // to have a bug where it doesn't initialize the struct properly if // we try to take the address of a function that's not yet loaded // from a dll, as is the common case for static_fn_. So we need // each to be in its own array. :-( static const char* const function_name_[kNumFunctions]; // This function is only used when statically linking the binary. // In that case, loading malloc/etc from the dll (via // PatchOneModule) won't work, since there are no dlls. Instead, // you just want to be taking the address of malloc/etc directly. // In the common, non-static-link case, these pointers will all be // NULL, since this initializer runs before msvcrt.dll is loaded. static const GenericFnPtr static_fn_[kNumFunctions]; // This is the address of the function we are going to patch // (malloc, etc). Other info about the function is in the // patch-specific subclasses, below. GenericFnPtr windows_fn_[kNumFunctions]; // This is set to true when this structure is initialized (because // we're patching a new library) and set to false when it's // uninitialized (because we've freed that library). bool is_valid_; const void *module_base_address_; size_t module_base_size_; public: // These shouldn't have to be public, since only subclasses of // LibcInfo need it, but they do. Maybe something to do with // templates. Shrug. I hide them down here so users won't see // them. :-) (OK, I also need to define ctrgProcAddress late.) bool is_valid() const { return is_valid_; } GenericFnPtr windows_fn(int ifunction) const { return windows_fn_[ifunction]; } // These three are needed by ModuleEntryCopy. static const int ctrgProcAddress = kNumFunctions; static GenericFnPtr static_fn(int ifunction) { return static_fn_[ifunction]; } static const char* const function_name(int ifunction) { return function_name_[ifunction]; } }; // Template trickiness: logically, a LibcInfo would include // Windows_malloc_, origstub_malloc_, and Perftools_malloc_: for a // given module, these three go together. And in fact, // Perftools_malloc_ may need to call origstub_malloc_, which means we // either need to change Perftools_malloc_ to take origstub_malloc_ as // an argument -- unfortunately impossible since it needs to keep the // same API as normal malloc -- or we need to write a different // version of Perftools_malloc_ for each LibcInfo instance we create. // We choose the second route, and use templates to implement it (we // could have also used macros). So to get multiple versions // of the struct, we say "struct<1> var1; struct<2> var2;". The price // we pay is some code duplication, and more annoying, each instance // of this var is a separate type. template<int> class LibcInfoWithPatchFunctions : public LibcInfo { public: // me_info should have had PopulateWindowsFn() called on it, so the // module_* vars and windows_fn_ are set up. bool Patch(const LibcInfo& me_info); void Unpatch(); private: // This holds the original function contents after we patch the function. // This has to be defined static in the subclass, because the perftools_fns // reference origstub_fn_. static GenericFnPtr origstub_fn_[kNumFunctions]; // This is the function we want to patch in static const GenericFnPtr perftools_fn_[kNumFunctions]; static void* Perftools_malloc(size_t size) __THROW; static void Perftools_free(void* ptr) __THROW; static void Perftools_free_base(void* ptr) __THROW; static void Perftools_free_dbg(void* ptr, int block_use) __THROW; static void* Perftools_realloc(void* ptr, size_t size) __THROW; static void* Perftools_calloc(size_t nmemb, size_t size) __THROW; static void* Perftools_new(size_t size); static void* Perftools_newarray(size_t size); static void Perftools_delete(void *ptr); static void Perftools_deletearray(void *ptr); static void* Perftools_new_nothrow(size_t size, const std::nothrow_t&) __THROW; static void* Perftools_newarray_nothrow(size_t size, const std::nothrow_t&) __THROW; static void Perftools_delete_nothrow(void *ptr, const std::nothrow_t&) __THROW; static void Perftools_deletearray_nothrow(void *ptr, const std::nothrow_t&) __THROW; static size_t Perftools__msize(void *ptr) __THROW; static void* Perftools__expand(void *ptr, size_t size) __THROW; // malloc.h also defines these functions: // _aligned_malloc, _aligned_free, // _recalloc, _aligned_offset_malloc, _aligned_realloc, _aligned_recalloc // _aligned_offset_realloc, _aligned_offset_recalloc, _malloca, _freea // But they seem pretty obscure, and I'm fine not overriding them for now. // It may be they all call into malloc/free anyway. }; // This is a subset of MODDULEENTRY32, that we need for patching. struct ModuleEntryCopy { LPVOID modBaseAddr; // the same as hmodule DWORD modBaseSize; // This is not part of MODDULEENTRY32, but is needed to avoid making // windows syscalls while we're holding patch_all_modules_lock (see // lock-inversion comments at patch_all_modules_lock definition, below). GenericFnPtr rgProcAddresses[LibcInfo::ctrgProcAddress]; ModuleEntryCopy() { modBaseAddr = NULL; modBaseSize = 0; for (int i = 0; i < sizeof(rgProcAddresses)/sizeof(*rgProcAddresses); i++) rgProcAddresses[i] = LibcInfo::static_fn(i); } ModuleEntryCopy(const MODULEINFO& mi) { this->modBaseAddr = mi.lpBaseOfDll; this->modBaseSize = mi.SizeOfImage; LPVOID modEndAddr = (char*)mi.lpBaseOfDll + mi.SizeOfImage; for (int i = 0; i < sizeof(rgProcAddresses)/sizeof(*rgProcAddresses); i++) { FARPROC target = ::GetProcAddress( reinterpret_cast<const HMODULE>(mi.lpBaseOfDll), LibcInfo::function_name(i)); // Sometimes a DLL forwards a function to a function in another // DLL. We don't want to patch those forwarded functions -- // they'll get patched when the other DLL is processed. if (target >= modBaseAddr && target < modEndAddr) rgProcAddresses[i] = (GenericFnPtr)target; else rgProcAddresses[i] = (GenericFnPtr)NULL; } } }; // This class is easier because there's only one of them. class WindowsInfo { public: void Patch(); void Unpatch(); private: // TODO(csilvers): should we be patching GlobalAlloc/LocalAlloc instead, // for pre-XP systems? enum { kHeapAlloc, kHeapFree, kVirtualAllocEx, kVirtualFreeEx, kMapViewOfFileEx, kUnmapViewOfFile, kLoadLibraryExW, kFreeLibrary, kNumFunctions }; struct FunctionInfo { const char* const name; // name of fn in a module (eg "malloc") GenericFnPtr windows_fn; // the fn whose name we call (&malloc) GenericFnPtr origstub_fn; // original fn contents after we patch const GenericFnPtr perftools_fn; // fn we want to patch in }; static FunctionInfo function_info_[kNumFunctions]; // A Windows-API equivalent of malloc and free static LPVOID WINAPI Perftools_HeapAlloc(HANDLE hHeap, DWORD dwFlags, DWORD_PTR dwBytes); static BOOL WINAPI Perftools_HeapFree(HANDLE hHeap, DWORD dwFlags, LPVOID lpMem); // A Windows-API equivalent of mmap and munmap, for "anonymous regions" static LPVOID WINAPI Perftools_VirtualAllocEx(HANDLE process, LPVOID address, SIZE_T size, DWORD type, DWORD protect); static BOOL WINAPI Perftools_VirtualFreeEx(HANDLE process, LPVOID address, SIZE_T size, DWORD type); // A Windows-API equivalent of mmap and munmap, for actual files static LPVOID WINAPI Perftools_MapViewOfFileEx(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap, LPVOID lpBaseAddress); static BOOL WINAPI Perftools_UnmapViewOfFile(LPCVOID lpBaseAddress); // We don't need the other 3 variants because they all call this one. */ static HMODULE WINAPI Perftools_LoadLibraryExW(LPCWSTR lpFileName, HANDLE hFile, DWORD dwFlags); static BOOL WINAPI Perftools_FreeLibrary(HMODULE hLibModule); }; // If you run out, just add a few more to the array. You'll also need // to update the switch statement in PatchOneModule(), and the list in // UnpatchWindowsFunctions(). // main_executable and main_executable_windows are two windows into // the same executable. One is responsible for patching the libc // routines that live in the main executable (if any) to use tcmalloc; // the other is responsible for patching the windows routines like // HeapAlloc/etc to use tcmalloc. static LibcInfoWithPatchFunctions<0> main_executable; static LibcInfoWithPatchFunctions<1> libc1; static LibcInfoWithPatchFunctions<2> libc2; static LibcInfoWithPatchFunctions<3> libc3; static LibcInfoWithPatchFunctions<4> libc4; static LibcInfoWithPatchFunctions<5> libc5; static LibcInfoWithPatchFunctions<6> libc6; static LibcInfoWithPatchFunctions<7> libc7; static LibcInfoWithPatchFunctions<8> libc8; static LibcInfo* g_module_libcs[] = { &libc1, &libc2, &libc3, &libc4, &libc5, &libc6, &libc7, &libc8 }; static WindowsInfo main_executable_windows; const char* const LibcInfo::function_name_[] = { "malloc", "free", "realloc", "calloc", kMangledNew, kMangledNewArray, kMangledDelete, kMangledDeleteArray, // Ideally we should patch the nothrow versions of new/delete, but // at least in msvcrt, nothrow-new machine-code is of a type we // can't patch. Since these are relatively rare, I'm hoping it's ok // not to patch them. (NULL name turns off patching.) NULL, // kMangledNewNothrow, NULL, // kMangledNewArrayNothrow, NULL, // kMangledDeleteNothrow, NULL, // kMangledDeleteArrayNothrow, "_msize", "_expand", "_calloc_crt", "_free_base", "_free_dbg" }; // For mingw, I can't patch the new/delete here, because the // instructions are too small to patch. Luckily, they're so small // because all they do is call into malloc/free, so they still end up // calling tcmalloc routines, and we don't actually lose anything // (except maybe some stacktrace goodness) by not patching. const GenericFnPtr LibcInfo::static_fn_[] = { (GenericFnPtr)&::malloc, (GenericFnPtr)&::free, (GenericFnPtr)&::realloc, (GenericFnPtr)&::calloc, #ifdef __MINGW32__ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, #else (GenericFnPtr)(void*(*)(size_t))&::operator new, (GenericFnPtr)(void*(*)(size_t))&::operator new[], (GenericFnPtr)(void(*)(void*))&::operator delete, (GenericFnPtr)(void(*)(void*))&::operator delete[], (GenericFnPtr) (void*(*)(size_t, struct std::nothrow_t const &))&::operator new, (GenericFnPtr) (void*(*)(size_t, struct std::nothrow_t const &))&::operator new[], (GenericFnPtr) (void(*)(void*, struct std::nothrow_t const &))&::operator delete, (GenericFnPtr) (void(*)(void*, struct std::nothrow_t const &))&::operator delete[], #endif (GenericFnPtr)&::_msize, (GenericFnPtr)&::_expand, (GenericFnPtr)&::calloc, (GenericFnPtr)&::free, (GenericFnPtr)&::free }; template<int T> GenericFnPtr LibcInfoWithPatchFunctions<T>::origstub_fn_[] = { // This will get filled in at run-time, as patching is done. }; template<int T> const GenericFnPtr LibcInfoWithPatchFunctions<T>::perftools_fn_[] = { (GenericFnPtr)&Perftools_malloc, (GenericFnPtr)&Perftools_free, (GenericFnPtr)&Perftools_realloc, (GenericFnPtr)&Perftools_calloc, (GenericFnPtr)&Perftools_new, (GenericFnPtr)&Perftools_newarray, (GenericFnPtr)&Perftools_delete, (GenericFnPtr)&Perftools_deletearray, (GenericFnPtr)&Perftools_new_nothrow, (GenericFnPtr)&Perftools_newarray_nothrow, (GenericFnPtr)&Perftools_delete_nothrow, (GenericFnPtr)&Perftools_deletearray_nothrow, (GenericFnPtr)&Perftools__msize, (GenericFnPtr)&Perftools__expand, (GenericFnPtr)&Perftools_calloc, (GenericFnPtr)&Perftools_free_base, (GenericFnPtr)&Perftools_free_dbg }; /*static*/ WindowsInfo::FunctionInfo WindowsInfo::function_info_[] = { { "HeapAlloc", NULL, NULL, (GenericFnPtr)&Perftools_HeapAlloc }, { "HeapFree", NULL, NULL, (GenericFnPtr)&Perftools_HeapFree }, { "VirtualAllocEx", NULL, NULL, (GenericFnPtr)&Perftools_VirtualAllocEx }, { "VirtualFreeEx", NULL, NULL, (GenericFnPtr)&Perftools_VirtualFreeEx }, { "MapViewOfFileEx", NULL, NULL, (GenericFnPtr)&Perftools_MapViewOfFileEx }, { "UnmapViewOfFile", NULL, NULL, (GenericFnPtr)&Perftools_UnmapViewOfFile }, { "LoadLibraryExW", NULL, NULL, (GenericFnPtr)&Perftools_LoadLibraryExW }, { "FreeLibrary", NULL, NULL, (GenericFnPtr)&Perftools_FreeLibrary }, }; bool LibcInfo::PopulateWindowsFn(const ModuleEntryCopy& module_entry) { // First, store the location of the function to patch before // patching it. If none of these functions are found in the module, // then this module has no libc in it, and we just return false. for (int i = 0; i < kNumFunctions; i++) { if (!function_name_[i]) // we can turn off patching by unsetting name continue; // The ::GetProcAddress calls were done in the ModuleEntryCopy // constructor, so we don't have to make any windows calls here. const GenericFnPtr fn = module_entry.rgProcAddresses[i]; if (fn) { windows_fn_[i] = PreamblePatcher::ResolveTarget(fn); } } // Some modules use the same function pointer for new and new[]. If // we find that, set one of the pointers to NULL so we don't double- // patch. Same may happen with new and nothrow-new, or even new[] // and nothrow-new. It's easiest just to check each fn-ptr against // every other. for (int i = 0; i < kNumFunctions; i++) { for (int j = i+1; j < kNumFunctions; j++) { if (windows_fn_[i] == windows_fn_[j]) { // We NULL the later one (j), so as to minimize the chances we // NULL kFree and kRealloc. See comments below. This is fragile! windows_fn_[j] = NULL; } } } // There's always a chance that our module uses the same function // as another module that we've already loaded. In that case, we // need to set our windows_fn to NULL, to avoid double-patching. for (int ifn = 0; ifn < kNumFunctions; ifn++) { for (int imod = 0; imod < sizeof(g_module_libcs)/sizeof(*g_module_libcs); imod++) { if (g_module_libcs[imod]->is_valid() && this->windows_fn(ifn) == g_module_libcs[imod]->windows_fn(ifn)) { windows_fn_[ifn] = NULL; } } } bool found_non_null = false; for (int i = 0; i < kNumFunctions; i++) { if (windows_fn_[i]) found_non_null = true; } if (!found_non_null) return false; // It's important we didn't NULL out windows_fn_[kFree] or [kRealloc]. // The reason is, if those are NULL-ed out, we'll never patch them // and thus never get an origstub_fn_ value for them, and when we // try to call origstub_fn_[kFree/kRealloc] in Perftools_free and // Perftools_realloc, below, it will fail. We could work around // that by adding a pointer from one patch-unit to the other, but we // haven't needed to yet. CHECK(windows_fn_[kFree]); CHECK(windows_fn_[kRealloc]); // OK, we successfully populated. Let's store our member information. module_base_address_ = module_entry.modBaseAddr; module_base_size_ = module_entry.modBaseSize; return true; } template<int T> bool LibcInfoWithPatchFunctions<T>::Patch(const LibcInfo& me_info) { CopyFrom(me_info); // copies the module_entry and the windows_fn_ array for (int i = 0; i < kNumFunctions; i++) { if (windows_fn_[i] && windows_fn_[i] != perftools_fn_[i]) { // if origstub_fn_ is not NULL, it's left around from a previous // patch. We need to set it to NULL for the new Patch call. // // Note that origstub_fn_ was logically freed by // PreamblePatcher::Unpatch, so we don't have to do anything // about it. origstub_fn_[i] = NULL; // Patch() will fill this in CHECK_EQ(sidestep::SIDESTEP_SUCCESS, PreamblePatcher::Patch(windows_fn_[i], perftools_fn_[i], &origstub_fn_[i])); } } set_is_valid(true); return true; } template<int T> void LibcInfoWithPatchFunctions<T>::Unpatch() { // We have to cast our GenericFnPtrs to void* for unpatch. This is // contra the C++ spec; we use C-style casts to empahsize that. for (int i = 0; i < kNumFunctions; i++) { if (windows_fn_[i]) CHECK_EQ(sidestep::SIDESTEP_SUCCESS, PreamblePatcher::Unpatch((void*)windows_fn_[i], (void*)perftools_fn_[i], (void*)origstub_fn_[i])); } set_is_valid(false); } void WindowsInfo::Patch() { HMODULE hkernel32 = ::GetModuleHandleA("kernel32"); CHECK_NE(hkernel32, NULL); // Unlike for libc, we know these exist in our module, so we can get // and patch at the same time. for (int i = 0; i < kNumFunctions; i++) { function_info_[i].windows_fn = (GenericFnPtr) ::GetProcAddress(hkernel32, function_info_[i].name); // If origstub_fn is not NULL, it's left around from a previous // patch. We need to set it to NULL for the new Patch call. // Since we've patched Unpatch() not to delete origstub_fn_ (it // causes problems in some contexts, though obviously not this // one), we should delete it now, before setting it to NULL. // NOTE: casting from a function to a pointer is contra the C++ // spec. It's not safe on IA64, but is on i386. We use // a C-style cast here to emphasize this is not legal C++. delete[] (char*)(function_info_[i].origstub_fn); function_info_[i].origstub_fn = NULL; // Patch() will fill this in CHECK_EQ(sidestep::SIDESTEP_SUCCESS, PreamblePatcher::Patch(function_info_[i].windows_fn, function_info_[i].perftools_fn, &function_info_[i].origstub_fn)); } } void WindowsInfo::Unpatch() { // We have to cast our GenericFnPtrs to void* for unpatch. This is // contra the C++ spec; we use C-style casts to empahsize that. for (int i = 0; i < kNumFunctions; i++) { CHECK_EQ(sidestep::SIDESTEP_SUCCESS, PreamblePatcher::Unpatch((void*)function_info_[i].windows_fn, (void*)function_info_[i].perftools_fn, (void*)function_info_[i].origstub_fn)); } } // You should hold the patch_all_modules_lock when calling this. void PatchOneModuleLocked(const LibcInfo& me_info) { // If we don't already have info on this module, let's add it. This // is where we're sad that each libcX has a different type, so we // can't use an array; instead, we have to use a switch statement. // Patch() returns false if there were no libc functions in the module. for (int i = 0; i < sizeof(g_module_libcs)/sizeof(*g_module_libcs); i++) { if (!g_module_libcs[i]->is_valid()) { // found an empty spot to add! switch (i) { case 0: libc1.Patch(me_info); return; case 1: libc2.Patch(me_info); return; case 2: libc3.Patch(me_info); return; case 3: libc4.Patch(me_info); return; case 4: libc5.Patch(me_info); return; case 5: libc6.Patch(me_info); return; case 6: libc7.Patch(me_info); return; case 7: libc8.Patch(me_info); return; } } } printf("PERFTOOLS ERROR: Too many modules containing libc in this executable\n"); } void PatchMainExecutableLocked() { if (main_executable.patched()) return; // main executable has already been patched ModuleEntryCopy fake_module_entry; // make a fake one to pass into Patch() // No need to call PopulateModuleEntryProcAddresses on the main executable. main_executable.PopulateWindowsFn(fake_module_entry); main_executable.Patch(main_executable); } // This lock is subject to a subtle and annoying lock inversion // problem: it may interact badly with unknown internal windows locks. // In particular, windows may be holding a lock when it calls // LoadLibraryExW and FreeLibrary, which we've patched. We have those // routines call PatchAllModules, which acquires this lock. If we // make windows system calls while holding this lock, those system // calls may need the internal windows locks that are being held in // the call to LoadLibraryExW, resulting in deadlock. The solution is // to be very careful not to call *any* windows routines while holding // patch_all_modules_lock, inside PatchAllModules(). static SpinLock patch_all_modules_lock(SpinLock::LINKER_INITIALIZED); // last_loaded: The set of modules that were loaded the last time // PatchAllModules was called. This is an optimization for only // looking at modules that were added or removed from the last call. static std::set<HMODULE> *g_last_loaded; // Iterates over all the modules currently loaded by the executable, // according to windows, and makes sure they're all patched. Most // modules will already be in loaded_modules, meaning we have already // loaded and either patched them or determined they did not need to // be patched. Others will not, which means we need to patch them // (if necessary). Finally, we have to go through the existing // g_module_libcs and see if any of those are *not* in the modules // currently loaded by the executable. If so, we need to invalidate // them. Returns true if we did any work (patching or invalidating), // false if we were a noop. May update loaded_modules as well. // NOTE: you must hold the patch_all_modules_lock to access loaded_modules. bool PatchAllModules() { std::vector<ModuleEntryCopy> modules; bool made_changes = false; const HANDLE hCurrentProcess = GetCurrentProcess(); DWORD num_modules = 0; HMODULE hModules[kMaxModules]; // max # of modules we support in one process if (!::EnumProcessModules(hCurrentProcess, hModules, sizeof(hModules), &num_modules)) { num_modules = 0; } // EnumProcessModules actually set the bytes written into hModules, // so we need to divide to make num_modules actually be a module-count. num_modules /= sizeof(*hModules); if (num_modules >= kMaxModules) { printf("PERFTOOLS ERROR: Too many modules in this executable to try" " to patch them all (if you need to, raise kMaxModules in" " patch_functions.cc).\n"); num_modules = kMaxModules; } // Now we handle the unpatching of modules we have in g_module_libcs // but that were not found in EnumProcessModules. We need to // invalidate them. To speed that up, we store the EnumProcessModules // output in a set. // At the same time, we prepare for the adding of new modules, by // removing from hModules all the modules we know we've already // patched (or decided don't need to be patched). At the end, // hModules will hold only the modules that we need to consider patching. std::set<HMODULE> currently_loaded_modules; { SpinLockHolder h(&patch_all_modules_lock); if (!g_last_loaded) g_last_loaded = new std::set<HMODULE>; // At the end of this loop, currently_loaded_modules contains the // full list of EnumProcessModules, and hModules just the ones we // haven't handled yet. for (int i = 0; i < num_modules; ) { currently_loaded_modules.insert(hModules[i]); if (g_last_loaded->count(hModules[i]) > 0) { hModules[i] = hModules[--num_modules]; // replace element i with tail } else { i++; // keep element i } } // Now we do the unpatching/invalidation. for (int i = 0; i < sizeof(g_module_libcs)/sizeof(*g_module_libcs); i++) { if (g_module_libcs[i]->patched() && currently_loaded_modules.count(g_module_libcs[i]->hmodule()) == 0) { // Means g_module_libcs[i] is no longer loaded (no me32 matched). // We could call Unpatch() here, but why bother? The module // has gone away, so nobody is going to call into it anyway. g_module_libcs[i]->set_is_valid(false); made_changes = true; } } // Update the loaded module cache. g_last_loaded->swap(currently_loaded_modules); } // Now that we know what modules are new, let's get the info we'll // need to patch them. Note this *cannot* be done while holding the // lock, since it needs to make windows calls (see the lock-inversion // comments before the definition of patch_all_modules_lock). MODULEINFO mi; for (int i = 0; i < num_modules; i++) { if (::GetModuleInformation(hCurrentProcess, hModules[i], &mi, sizeof(mi))) modules.push_back(ModuleEntryCopy(mi)); } // Now we can do the patching of new modules. { SpinLockHolder h(&patch_all_modules_lock); for (std::vector<ModuleEntryCopy>::iterator it = modules.begin(); it != modules.end(); ++it) { LibcInfo libc_info; if (libc_info.PopulateWindowsFn(*it)) { // true==module has libc routines PatchOneModuleLocked(libc_info); made_changes = true; } } // Now that we've dealt with the modules (dlls), update the main // executable. We do this last because PatchMainExecutableLocked // wants to look at how other modules were patched. if (!main_executable.patched()) { PatchMainExecutableLocked(); made_changes = true; } } // TODO(csilvers): for this to be reliable, we need to also take // into account if we *would* have patched any modules had they not // already been loaded. (That is, made_changes should ignore // g_last_loaded.) return made_changes; } } // end unnamed namespace // --------------------------------------------------------------------- // Now that we've done all the patching machinery, let's actually // define the functions we're patching in. Mostly these are // simple wrappers around the do_* routines in tcmalloc.cc. // // In fact, we #include tcmalloc.cc to get at the tcmalloc internal // do_* functions, the better to write our own hook functions. // U-G-L-Y, I know. But the alternatives are, perhaps, worse. This // also lets us define _msize(), _expand(), and other windows-specific // functions here, using tcmalloc internals, without polluting // tcmalloc.cc. // ------------------------------------------------------------------- // TODO(csilvers): refactor tcmalloc.cc into two files, so I can link // against the file with do_malloc, and ignore the one with malloc. #include "tcmalloc.cc" template<int T> void* LibcInfoWithPatchFunctions<T>::Perftools_malloc(size_t size) __THROW { return malloc_fast_path<tcmalloc::malloc_oom>(size); } template<int T> void LibcInfoWithPatchFunctions<T>::Perftools_free(void* ptr) __THROW { MallocHook::InvokeDeleteHook(ptr); // This calls the windows free if do_free decides ptr was not // allocated by tcmalloc. Note it calls the origstub_free from // *this* templatized instance of LibcInfo. See "template // trickiness" above. do_free_with_callback(ptr, (void (*)(void*))origstub_fn_[kFree], false, 0); } template<int T> void LibcInfoWithPatchFunctions<T>::Perftools_free_base(void* ptr) __THROW{ MallocHook::InvokeDeleteHook(ptr); // This calls the windows free if do_free decides ptr was not // allocated by tcmalloc. Note it calls the origstub_free from // *this* templatized instance of LibcInfo. See "template // trickiness" above. do_free_with_callback(ptr, (void(*)(void*))origstub_fn_[kFreeBase], false, 0); } template<int T> void LibcInfoWithPatchFunctions<T>::Perftools_free_dbg(void* ptr, int block_use) __THROW { MallocHook::InvokeDeleteHook(ptr); // The windows _free_dbg is called if ptr isn't owned by tcmalloc. if (MallocExtension::instance()->GetOwnership(ptr) == MallocExtension::kOwned) { do_free(ptr); } else { reinterpret_cast<void (*)(void*, int)>(origstub_fn_[kFreeDbg])(ptr, block_use); } } template<int T> void* LibcInfoWithPatchFunctions<T>::Perftools_realloc( void* old_ptr, size_t new_size) __THROW { if (old_ptr == NULL) { void* result = do_malloc_or_cpp_alloc(new_size); MallocHook::InvokeNewHook(result, new_size); return result; } if (new_size == 0) { MallocHook::InvokeDeleteHook(old_ptr); do_free_with_callback(old_ptr, (void (*)(void*))origstub_fn_[kFree], false, 0); return NULL; } return do_realloc_with_callback( old_ptr, new_size, (void (*)(void*))origstub_fn_[kFree], (size_t (*)(const void*))origstub_fn_[k_Msize]); } template<int T> void* LibcInfoWithPatchFunctions<T>::Perftools_calloc( size_t n, size_t elem_size) __THROW { void* result = do_calloc(n, elem_size); MallocHook::InvokeNewHook(result, n * elem_size); return result; } template<int T> void* LibcInfoWithPatchFunctions<T>::Perftools_new(size_t size) { return malloc_fast_path<tcmalloc::cpp_throw_oom>(size); } template<int T> void* LibcInfoWithPatchFunctions<T>::Perftools_newarray(size_t size) { return malloc_fast_path<tcmalloc::cpp_throw_oom>(size); } template<int T> void LibcInfoWithPatchFunctions<T>::Perftools_delete(void *p) { MallocHook::InvokeDeleteHook(p); do_free_with_callback(p, (void (*)(void*))origstub_fn_[kFree], false, 0); } template<int T> void LibcInfoWithPatchFunctions<T>::Perftools_deletearray(void *p) { MallocHook::InvokeDeleteHook(p); do_free_with_callback(p, (void (*)(void*))origstub_fn_[kFree], false, 0); } template<int T> void* LibcInfoWithPatchFunctions<T>::Perftools_new_nothrow( size_t size, const std::nothrow_t&) __THROW { return malloc_fast_path<tcmalloc::cpp_nothrow_oom>(size); } template<int T> void* LibcInfoWithPatchFunctions<T>::Perftools_newarray_nothrow( size_t size, const std::nothrow_t&) __THROW { return malloc_fast_path<tcmalloc::cpp_nothrow_oom>(size); } template<int T> void LibcInfoWithPatchFunctions<T>::Perftools_delete_nothrow( void *p, const std::nothrow_t&) __THROW { MallocHook::InvokeDeleteHook(p); do_free_with_callback(p, (void (*)(void*))origstub_fn_[kFree], false, 0); } template<int T> void LibcInfoWithPatchFunctions<T>::Perftools_deletearray_nothrow( void *p, const std::nothrow_t&) __THROW { MallocHook::InvokeDeleteHook(p); do_free_with_callback(p, (void (*)(void*))origstub_fn_[kFree], false, 0); } // _msize() lets you figure out how much space is reserved for a // pointer, in Windows. Even if applications don't call it, any DLL // with global constructors will call (transitively) something called // __dllonexit_lk in order to make sure the destructors get called // when the dll unloads. And that will call msize -- horrible things // can ensue if this is not hooked. Other parts of libc may also call // this internally. template<int T> size_t LibcInfoWithPatchFunctions<T>::Perftools__msize(void* ptr) __THROW { return GetSizeWithCallback(ptr, (size_t (*)(const void*))origstub_fn_[k_Msize]); } // We need to define this because internal windows functions like to // call into it(?). _expand() is like realloc but doesn't move the // pointer. We punt, which will cause callers to fall back on realloc. template<int T> void* LibcInfoWithPatchFunctions<T>::Perftools__expand(void *ptr, size_t size) __THROW { return NULL; } LPVOID WINAPI WindowsInfo::Perftools_HeapAlloc(HANDLE hHeap, DWORD dwFlags, DWORD_PTR dwBytes) { LPVOID result = ((LPVOID (WINAPI *)(HANDLE, DWORD, DWORD_PTR)) function_info_[kHeapAlloc].origstub_fn)( hHeap, dwFlags, dwBytes); MallocHook::InvokeNewHook(result, dwBytes); return result; } BOOL WINAPI WindowsInfo::Perftools_HeapFree(HANDLE hHeap, DWORD dwFlags, LPVOID lpMem) { MallocHook::InvokeDeleteHook(lpMem); return ((BOOL (WINAPI *)(HANDLE, DWORD, LPVOID)) function_info_[kHeapFree].origstub_fn)( hHeap, dwFlags, lpMem); } LPVOID WINAPI WindowsInfo::Perftools_VirtualAllocEx(HANDLE process, LPVOID address, SIZE_T size, DWORD type, DWORD protect) { LPVOID result = ((LPVOID (WINAPI *)(HANDLE, LPVOID, SIZE_T, DWORD, DWORD)) function_info_[kVirtualAllocEx].origstub_fn)( process, address, size, type, protect); // VirtualAllocEx() seems to be the Windows equivalent of mmap() MallocHook::InvokeMmapHook(result, address, size, protect, type, -1, 0); return result; } BOOL WINAPI WindowsInfo::Perftools_VirtualFreeEx(HANDLE process, LPVOID address, SIZE_T size, DWORD type) { MallocHook::InvokeMunmapHook(address, size); return ((BOOL (WINAPI *)(HANDLE, LPVOID, SIZE_T, DWORD)) function_info_[kVirtualFreeEx].origstub_fn)( process, address, size, type); } LPVOID WINAPI WindowsInfo::Perftools_MapViewOfFileEx( HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap, LPVOID lpBaseAddress) { // For this function pair, you always deallocate the full block of // data that you allocate, so NewHook/DeleteHook is the right API. LPVOID result = ((LPVOID (WINAPI *)(HANDLE, DWORD, DWORD, DWORD, SIZE_T, LPVOID)) function_info_[kMapViewOfFileEx].origstub_fn)( hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap, lpBaseAddress); MallocHook::InvokeNewHook(result, dwNumberOfBytesToMap); return result; } BOOL WINAPI WindowsInfo::Perftools_UnmapViewOfFile(LPCVOID lpBaseAddress) { MallocHook::InvokeDeleteHook(lpBaseAddress); return ((BOOL (WINAPI *)(LPCVOID)) function_info_[kUnmapViewOfFile].origstub_fn)( lpBaseAddress); } HMODULE WINAPI WindowsInfo::Perftools_LoadLibraryExW(LPCWSTR lpFileName, HANDLE hFile, DWORD dwFlags) { HMODULE rv; // Check to see if the modules is already loaded, flag 0 gets a // reference if it was loaded. If it was loaded no need to call // PatchAllModules, just increase the reference count to match // what GetModuleHandleExW does internally inside windows. if (::GetModuleHandleExW(0, lpFileName, &rv)) { return rv; } else { // Not already loaded, so load it. rv = ((HMODULE (WINAPI *)(LPCWSTR, HANDLE, DWORD)) function_info_[kLoadLibraryExW].origstub_fn)( lpFileName, hFile, dwFlags); // This will patch any newly loaded libraries, if patching needs // to be done. PatchAllModules(); return rv; } } BOOL WINAPI WindowsInfo::Perftools_FreeLibrary(HMODULE hLibModule) { BOOL rv = ((BOOL (WINAPI *)(HMODULE)) function_info_[kFreeLibrary].origstub_fn)(hLibModule); // Check to see if the module is still loaded by passing the base // address and seeing if it comes back with the same address. If it // is the same address it's still loaded, so the FreeLibrary() call // was a noop, and there's no need to redo the patching. HMODULE owner = NULL; BOOL result = ::GetModuleHandleExW( (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT), (LPCWSTR)hLibModule, &owner); if (result && owner == hLibModule) return rv; PatchAllModules(); // this will fix up the list of patched libraries return rv; } // --------------------------------------------------------------------- // PatchWindowsFunctions() // This is the function that is exposed to the outside world. // It should be called before the program becomes multi-threaded, // since main_executable_windows.Patch() is not thread-safe. // --------------------------------------------------------------------- void PatchWindowsFunctions() { // This does the libc patching in every module, and the main executable. PatchAllModules(); main_executable_windows.Patch(); } #if 0 // It's possible to unpatch all the functions when we are exiting. // The idea is to handle properly windows-internal data that is // allocated before PatchWindowsFunctions is called. If all // destruction happened in reverse order from construction, then we // could call UnpatchWindowsFunctions at just the right time, so that // that early-allocated data would be freed using the windows // allocation functions rather than tcmalloc. The problem is that // windows allocates some structures lazily, so it would allocate them // late (using tcmalloc) and then try to deallocate them late as well. // So instead of unpatching, we just modify all the tcmalloc routines // so they call through to the libc rountines if the memory in // question doesn't seem to have been allocated with tcmalloc. I keep // this unpatch code around for reference. void UnpatchWindowsFunctions() { // We need to go back to the system malloc/etc at global destruct time, // so objects that were constructed before tcmalloc, using the system // malloc, can destroy themselves using the system free. This depends // on DLLs unloading in the reverse order in which they load! // // We also go back to the default HeapAlloc/etc, just for consistency. // Who knows, it may help avoid weird bugs in some situations. main_executable_windows.Unpatch(); main_executable.Unpatch(); if (libc1.is_valid()) libc1.Unpatch(); if (libc2.is_valid()) libc2.Unpatch(); if (libc3.is_valid()) libc3.Unpatch(); if (libc4.is_valid()) libc4.Unpatch(); if (libc5.is_valid()) libc5.Unpatch(); if (libc6.is_valid()) libc6.Unpatch(); if (libc7.is_valid()) libc7.Unpatch(); if (libc8.is_valid()) libc8.Unpatch(); } #endif
Unknown
3D
mcellteam/mcell
libs/gperftools/src/windows/port.cc
.cc
9,840
250
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- /* Copyright (c) 2007, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Craig Silverstein */ #ifndef _WIN32 # error You should only be including windows/port.cc in a windows environment! #endif #define NOMINMAX // so std::max, below, compiles correctly #include <config.h> #include <string.h> // for strlen(), memset(), memcmp() #include <assert.h> #include <stdarg.h> // for va_list, va_start, va_end #include <algorithm> // for std:{min,max} #include <windows.h> #include "port.h" #include "base/logging.h" #include "base/spinlock.h" #include "internal_logging.h" // ----------------------------------------------------------------------- // Basic libraries PERFTOOLS_DLL_DECL int getpagesize() { static int pagesize = 0; if (pagesize == 0) { SYSTEM_INFO system_info; GetSystemInfo(&system_info); pagesize = std::max(system_info.dwPageSize, system_info.dwAllocationGranularity); } return pagesize; } extern "C" PERFTOOLS_DLL_DECL void* __sbrk(ptrdiff_t increment) { LOG(FATAL, "Windows doesn't implement sbrk!\n"); return NULL; } // We need to write to 'stderr' without having windows allocate memory. // The safest way is via a low-level call like WriteConsoleA(). But // even then we need to be sure to print in small bursts so as to not // require memory allocation. extern "C" PERFTOOLS_DLL_DECL void WriteToStderr(const char* buf, int len) { // Looks like windows allocates for writes of >80 bytes for (int i = 0; i < len; i += 80) { write(STDERR_FILENO, buf + i, std::min(80, len - i)); } } // ----------------------------------------------------------------------- // Threads code // Windows doesn't support pthread_key_create's destr_function, and in // fact it's a bit tricky to get code to run when a thread exits. This // is cargo-cult magic from https://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way // and http://lallouslab.net/2017/05/30/using-cc-tls-callbacks-in-visual-studio-with-your-32-or-64bits-programs/. // This code is for VC++ 7.1 and later; VC++ 6.0 support is possible // but more busy-work -- see the webpage for how to do it. If all // this fails, we could use DllMain instead. The big problem with // DllMain is it doesn't run if this code is statically linked into a // binary (it also doesn't run if the thread is terminated via // TerminateThread, which if we're lucky this routine does). // Force a reference to _tls_used to make the linker create the TLS directory // if it's not already there (that is, even if __declspec(thread) is not used). // Force a reference to p_thread_callback_tcmalloc and p_process_term_tcmalloc // to prevent whole program optimization from discarding the variables. #ifdef _MSC_VER #if defined(_M_IX86) #pragma comment(linker, "/INCLUDE:__tls_used") #pragma comment(linker, "/INCLUDE:_p_thread_callback_tcmalloc") #pragma comment(linker, "/INCLUDE:_p_process_term_tcmalloc") #elif defined(_M_X64) #pragma comment(linker, "/INCLUDE:_tls_used") #pragma comment(linker, "/INCLUDE:p_thread_callback_tcmalloc") #pragma comment(linker, "/INCLUDE:p_process_term_tcmalloc") #endif #endif // When destr_fn eventually runs, it's supposed to take as its // argument the tls-value associated with key that pthread_key_create // creates. (Yeah, it sounds confusing but it's really not.) We // store the destr_fn/key pair in this data structure. Because we // store this in a single var, this implies we can only have one // destr_fn in a program! That's enough in practice. If asserts // trigger because we end up needing more, we'll have to turn this // into an array. struct DestrFnClosure { void (*destr_fn)(void*); pthread_key_t key_for_destr_fn_arg; }; static DestrFnClosure destr_fn_info; // initted to all NULL/0. static int on_process_term(void) { if (destr_fn_info.destr_fn) { void *ptr = TlsGetValue(destr_fn_info.key_for_destr_fn_arg); // This shouldn't be necessary, but in Release mode, Windows // sometimes trashes the pointer in the TLS slot, so we need to // remove the pointer from the TLS slot before the thread dies. TlsSetValue(destr_fn_info.key_for_destr_fn_arg, NULL); if (ptr) // pthread semantics say not to call if ptr is NULL (*destr_fn_info.destr_fn)(ptr); } return 0; } static void NTAPI on_tls_callback(HINSTANCE h, DWORD dwReason, PVOID pv) { if (dwReason == DLL_THREAD_DETACH) { // thread is being destroyed! on_process_term(); } } #ifdef _MSC_VER // extern "C" suppresses C++ name mangling so we know the symbol names // for the linker /INCLUDE:symbol pragmas above. // Note that for some unknown reason, the extern "C" {} construct is ignored // by the MSVC VS2017 compiler (at least) when a const modifier is used #if defined(_M_IX86) extern "C" { // In x86, the PE loader looks for callbacks in a data segment #pragma data_seg(push, old_seg) #pragma data_seg(".CRT$XLB") void (NTAPI *p_thread_callback_tcmalloc)( HINSTANCE h, DWORD dwReason, PVOID pv) = on_tls_callback; #pragma data_seg(".CRT$XTU") int (*p_process_term_tcmalloc)(void) = on_process_term; #pragma data_seg(pop, old_seg) } // extern "C" #elif defined(_M_X64) // In x64, the PE loader looks for callbacks in a constant segment #pragma const_seg(push, oldseg) #pragma const_seg(".CRT$XLB") extern "C" void (NTAPI * const p_thread_callback_tcmalloc)( HINSTANCE h, DWORD dwReason, PVOID pv) = on_tls_callback; #pragma const_seg(".CRT$XTU") extern "C" int (NTAPI * const p_process_term_tcmalloc)(void) = on_process_term; #pragma const_seg(pop, oldseg) #endif #else // #ifdef _MSC_VER [probably msys/mingw] // We have to try the DllMain solution here, because we can't use the // msvc-specific pragmas. BOOL WINAPI DllMain(HINSTANCE h, DWORD dwReason, PVOID pv) { if (dwReason == DLL_THREAD_DETACH) on_tls_callback(h, dwReason, pv); else if (dwReason == DLL_PROCESS_DETACH) on_process_term(); return TRUE; } #endif // #ifdef _MSC_VER extern "C" pthread_key_t PthreadKeyCreate(void (*destr_fn)(void*)) { // Semantics are: we create a new key, and then promise to call // destr_fn with TlsGetValue(key) when the thread is destroyed // (as long as TlsGetValue(key) is not NULL). pthread_key_t key = TlsAlloc(); if (destr_fn) { // register it // If this assert fails, we'll need to support an array of destr_fn_infos assert(destr_fn_info.destr_fn == NULL); destr_fn_info.destr_fn = destr_fn; destr_fn_info.key_for_destr_fn_arg = key; } return key; } // NOTE: this is Win2K and later. For Win98 we could use a CRITICAL_SECTION... extern "C" int perftools_pthread_once(pthread_once_t *once_control, void (*init_routine)(void)) { // Try for a fast path first. Note: this should be an acquire semantics read. // It is on x86 and x64, where Windows runs. if (*once_control != 1) { while (true) { switch (InterlockedCompareExchange(once_control, 2, 0)) { case 0: init_routine(); InterlockedExchange(once_control, 1); return 0; case 1: // The initializer has already been executed return 0; default: // The initializer is being processed by another thread SwitchToThread(); } } } return 0; } // ----------------------------------------------------------------------- // These functions rework existing functions of the same name in the // Google codebase. // A replacement for HeapProfiler::CleanupOldProfiles. void DeleteMatchingFiles(const char* prefix, const char* full_glob) { WIN32_FIND_DATAA found; // that final A is for Ansi (as opposed to Unicode) HANDLE hFind = FindFirstFileA(full_glob, &found); // A is for Ansi if (hFind != INVALID_HANDLE_VALUE) { const int prefix_length = strlen(prefix); do { const char *fname = found.cFileName; if ((strlen(fname) >= prefix_length) && (memcmp(fname, prefix, prefix_length) == 0)) { RAW_VLOG(0, "Removing old heap profile %s\n", fname); // TODO(csilvers): we really need to unlink dirname + fname _unlink(fname); } } while (FindNextFileA(hFind, &found) != FALSE); // A is for Ansi FindClose(hFind); } }
Unknown
3D
mcellteam/mcell
libs/gperftools/src/windows/ia32_opcode_map.cc
.cc
113,909
1,220
/* Copyright (c) 2007, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Joi Sigurdsson * * Opcode decoding maps. Based on the IA-32 Intel® Architecture * Software Developer's Manual Volume 2: Instruction Set Reference. Idea * for how to lay out the tables in memory taken from the implementation * in the Bastard disassembly environment. */ #include "mini_disassembler.h" namespace sidestep { /* * This is the first table to be searched; the first field of each * Opcode in the table is either 0 to indicate you're in the * right table, or an index to the correct table, in the global * map g_pentiumOpcodeMap */ const Opcode s_first_opcode_byte[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF */ { 1, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x10 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x11 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x12 */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x13 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x14 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x15 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x16 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x17 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x18 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x19 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1A */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1C */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1E */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1F */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x20 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x21 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x22 */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x23 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x24 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x25 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x26 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x27 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "daa", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x28 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x29 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2A */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2C */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2E */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2F */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "das", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x30 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x31 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x32 */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x33 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x34 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x35 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x36 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x37 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "aaa", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x38 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x39 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3A */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3C */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3E */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3F */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "aas", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, #ifdef _M_X64 /* REX Prefixes in 64-bit mode. */ /* 0x40 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x41 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x42 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x43 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x44 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x45 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x46 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x47 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x48 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x49 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4A */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4B */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4C */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4D */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4E */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4F */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, #else /* 0x40 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x41 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x42 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x43 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x44 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x45 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x46 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x47 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x48 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x49 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4A */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4B */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4C */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4E */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4F */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, #endif /* 0x50 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x51 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x52 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x53 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x54 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x55 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x56 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x57 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x58 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x59 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5A */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5B */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5C */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5E */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5F */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x60 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "pushad", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x61 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "popad", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x62 */ { 0, IT_GENERIC, AM_G | OT_V, AM_M | OT_A, AM_NOT_USED, "bound", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x63 */ { 0, IT_GENERIC, AM_E | OT_W, AM_G | OT_W, AM_NOT_USED, "arpl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x64 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x65 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x66 */ { 0, IT_PREFIX_OPERAND, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x67 */ { 0, IT_PREFIX_ADDRESS, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x68 */ { 0, IT_GENERIC, AM_I | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x69 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_I | OT_V, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6A */ { 0, IT_GENERIC, AM_I | OT_B, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_I | OT_B, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6C */ { 0, IT_GENERIC, AM_Y | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "insb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6D */ { 0, IT_GENERIC, AM_Y | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "insd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6E */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_X | OT_B, AM_NOT_USED, "outsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6F */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_X | OT_V, AM_NOT_USED, "outsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x70 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x71 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jno", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x72 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x73 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jnc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x74 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x75 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x76 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jbe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x77 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "ja", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x78 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "js", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x79 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jns", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7A */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jpe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7B */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jpo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7C */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7D */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jge", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7E */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jle", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7F */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x80 */ { 2, IT_REFERENCE, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x81 */ { 3, IT_REFERENCE, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x82 */ { 4, IT_REFERENCE, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x83 */ { 5, IT_REFERENCE, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x84 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x85 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x86 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x87 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x88 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x89 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8A */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8C */ { 0, IT_GENERIC, AM_E | OT_W, AM_S | OT_W, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8D */ { 0, IT_GENERIC, AM_G | OT_V, AM_M | OT_ADDRESS_MODE_M, AM_NOT_USED, "lea", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8E */ { 0, IT_GENERIC, AM_S | OT_W, AM_E | OT_W, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8F */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x90 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "nop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x91 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x92 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x93 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x94 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x95 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x96 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x97 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x98 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cwde", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x99 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cdq", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9A */ { 0, IT_JUMP, AM_A | OT_P, AM_NOT_USED, AM_NOT_USED, "callf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9B */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "wait", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9C */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "pushfd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9D */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "popfd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9E */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "sahf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9F */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "lahf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA0 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_O | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA1 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_O | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA2 */ { 0, IT_GENERIC, AM_O | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA3 */ { 0, IT_GENERIC, AM_O | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA4 */ { 0, IT_GENERIC, AM_X | OT_B, AM_Y | OT_B, AM_NOT_USED, "movsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA5 */ { 0, IT_GENERIC, AM_X | OT_V, AM_Y | OT_V, AM_NOT_USED, "movsd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA6 */ { 0, IT_GENERIC, AM_X | OT_B, AM_Y | OT_B, AM_NOT_USED, "cmpsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA7 */ { 0, IT_GENERIC, AM_X | OT_V, AM_Y | OT_V, AM_NOT_USED, "cmpsd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA8 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA9 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAA */ { 0, IT_GENERIC, AM_Y | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "stosb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAB */ { 0, IT_GENERIC, AM_Y | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "stosd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAC */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_X| OT_B, AM_NOT_USED, "lodsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAD */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_X| OT_V, AM_NOT_USED, "lodsd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAE */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_Y | OT_B, AM_NOT_USED, "scasb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAF */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_Y | OT_V, AM_NOT_USED, "scasd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB0 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB1 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB2 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB3 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB4 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB5 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB6 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB7 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, #ifdef _M_X64 /* 0xB8 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V | IOS_64, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB9 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V | IOS_64, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBA */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V | IOS_64, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBB */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V | IOS_64, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBC */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V | IOS_64, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBD */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V | IOS_64, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBE */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V | IOS_64, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBF */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V | IOS_64, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, #else /* 0xB8 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB9 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBA */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBB */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBC */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBD */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBE */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBF */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, #endif /* 0xC0 */ { 6, IT_REFERENCE, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC1 */ { 7, IT_REFERENCE, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC2 */ { 0, IT_RETURN, AM_I | OT_W, AM_NOT_USED, AM_NOT_USED, "ret", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC3 */ { 0, IT_RETURN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "ret", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC4 */ { 0, IT_GENERIC, AM_G | OT_V, AM_M | OT_P, AM_NOT_USED, "les", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC5 */ { 0, IT_GENERIC, AM_G | OT_V, AM_M | OT_P, AM_NOT_USED, "lds", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC8 */ { 0, IT_GENERIC, AM_I | OT_W, AM_I | OT_B, AM_NOT_USED, "enter", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC9 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "leave", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCA */ { 0, IT_RETURN, AM_I | OT_W, AM_NOT_USED, AM_NOT_USED, "retf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCB */ { 0, IT_RETURN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "retf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCC */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "int3", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCD */ { 0, IT_GENERIC, AM_I | OT_B, AM_NOT_USED, AM_NOT_USED, "int", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCE */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "into", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCF */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "iret", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD0 */ { 8, IT_REFERENCE, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD1 */ { 9, IT_REFERENCE, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD2 */ { 10, IT_REFERENCE, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD3 */ { 11, IT_REFERENCE, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD4 */ { 0, IT_GENERIC, AM_I | OT_B, AM_NOT_USED, AM_NOT_USED, "aam", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD5 */ { 0, IT_GENERIC, AM_I | OT_B, AM_NOT_USED, AM_NOT_USED, "aad", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD6 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD7 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "xlat", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, // The following 8 lines would be references to the FPU tables, but we currently // do not support the FPU instructions in this disassembler. /* 0xD8 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD9 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xDA */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xDB */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xDC */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xDD */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xDE */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xDF */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE0 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "loopnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE1 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "loopz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE2 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "loop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE3 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jcxz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE4 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "in", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE5 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "in", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE6 */ { 0, IT_GENERIC, AM_I | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "out", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE7 */ { 0, IT_GENERIC, AM_I | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "out", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE8 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "call", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE9 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xEA */ { 0, IT_JUMP, AM_A | OT_P, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xEB */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xEC */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_REGISTER | OT_W, AM_NOT_USED, "in", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xED */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_W, AM_NOT_USED, "in", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xEE */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_REGISTER | OT_B, AM_NOT_USED, "out", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xEF */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_REGISTER | OT_V, AM_NOT_USED, "out", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF0 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "lock:", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF2 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "repne:", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF3 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rep:", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF4 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "hlt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF5 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cmc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF6 */ { 12, IT_REFERENCE, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF7 */ { 13, IT_REFERENCE, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF8 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "clc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF9 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "stc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xFA */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cli", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xFB */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "sti", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xFC */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cld", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xFD */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "std", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xFE */ { 14, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xFF */ { 15, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_0f[] = { /* 0x0 */ { 16, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 17, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_W, AM_NOT_USED, "lar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_W, AM_NOT_USED, "lsl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "clts", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "invd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "wbinvd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "ud2", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xE */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x10 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "movups", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "movsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "movss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "movupd" } }, /* 0x11 */ { 0, IT_GENERIC, AM_W | OT_PS, AM_V | OT_PS, AM_NOT_USED, "movups", true, /* F2h */ { 0, IT_GENERIC, AM_W | OT_SD, AM_V | OT_SD, AM_NOT_USED, "movsd" }, /* F3h */ { 0, IT_GENERIC, AM_W | OT_SS, AM_V | OT_SS, AM_NOT_USED, "movss" }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_PD, AM_V | OT_PD, AM_NOT_USED, "movupd" } }, /* 0x12 */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movlps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movhlps" }, // only one of ... /* F3h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movhlps" }, // ...these two is correct, Intel doesn't specify which /* 66h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_S, AM_NOT_USED, "movlpd" } }, /* 0x13 */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movlps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movlpd" } }, /* 0x14 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_Q, AM_NOT_USED, "unpcklps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_Q, AM_NOT_USED, "unpcklpd" } }, /* 0x15 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_Q, AM_NOT_USED, "unpckhps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_Q, AM_NOT_USED, "unpckhpd" } }, /* 0x16 */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movhps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movlhps" }, // only one of... /* F3h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movlhps" }, // ...these two is correct, Intel doesn't specify which /* 66h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movhpd" } }, /* 0x17 */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movhps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movhpd" } }, /* 0x18 */ { 18, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x19 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1A */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1B */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1C */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1D */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1E */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1F */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x20 */ { 0, IT_GENERIC, AM_R | OT_D, AM_C | OT_D, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x21 */ { 0, IT_GENERIC, AM_R | OT_D, AM_D | OT_D, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x22 */ { 0, IT_GENERIC, AM_C | OT_D, AM_R | OT_D, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x23 */ { 0, IT_GENERIC, AM_D | OT_D, AM_R | OT_D, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x24 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x25 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x26 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x27 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x28 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "movaps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "movapd" } }, /* 0x29 */ { 0, IT_GENERIC, AM_W | OT_PS, AM_V | OT_PS, AM_NOT_USED, "movaps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_PD, AM_V | OT_PD, AM_NOT_USED, "movapd" } }, /* 0x2A */ { 0, IT_GENERIC, AM_V | OT_PS, AM_Q | OT_Q, AM_NOT_USED, "cvtpi2ps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_E | OT_D, AM_NOT_USED, "cvtsi2sd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_E | OT_D, AM_NOT_USED, "cvtsi2ss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_Q | OT_DQ, AM_NOT_USED, "cvtpi2pd" } }, /* 0x2B */ { 0, IT_GENERIC, AM_W | OT_PS, AM_V | OT_PS, AM_NOT_USED, "movntps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_PD, AM_V | OT_PD, AM_NOT_USED, "movntpd" } }, /* 0x2C */ { 0, IT_GENERIC, AM_Q | OT_Q, AM_W | OT_PS, AM_NOT_USED, "cvttps2pi", true, /* F2h */ { 0, IT_GENERIC, AM_G | OT_D, AM_W | OT_SD, AM_NOT_USED, "cvttsd2si" }, /* F3h */ { 0, IT_GENERIC, AM_G | OT_D, AM_W | OT_SS, AM_NOT_USED, "cvttss2si" }, /* 66h */ { 0, IT_GENERIC, AM_Q | OT_DQ, AM_W | OT_PD, AM_NOT_USED, "cvttpd2pi" } }, /* 0x2D */ { 0, IT_GENERIC, AM_Q | OT_Q, AM_W | OT_PS, AM_NOT_USED, "cvtps2pi", true, /* F2h */ { 0, IT_GENERIC, AM_G | OT_D, AM_W | OT_SD, AM_NOT_USED, "cvtsd2si" }, /* F3h */ { 0, IT_GENERIC, AM_G | OT_D, AM_W | OT_SS, AM_NOT_USED, "cvtss2si" }, /* 66h */ { 0, IT_GENERIC, AM_Q | OT_DQ, AM_W | OT_PD, AM_NOT_USED, "cvtpd2pi" } }, /* 0x2E */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "ucomiss", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "ucomisd" } }, /* 0x2F */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_SS, AM_NOT_USED, "comiss", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "comisd" } }, /* 0x30 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "wrmsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x31 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rdtsc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x32 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rdmsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x33 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rdpmc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x34 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "sysenter", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x35 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "sysexit", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x36 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x37 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x38 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x39 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3A */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3B */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3C */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "movnti", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3D */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3E */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3F */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x40 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x41 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovno", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x42 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x43 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovnc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x44 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x45 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x46 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovbe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x47 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmova", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x48 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovs", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x49 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovns", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4A */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovpe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovpo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4C */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4D */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovge", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4E */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovle", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4F */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x50 */ { 0, IT_GENERIC, AM_E | OT_D, AM_V | OT_PS, AM_NOT_USED, "movmskps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_E | OT_D, AM_V | OT_PD, AM_NOT_USED, "movmskpd" } }, /* 0x51 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "sqrtps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "sqrtsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "sqrtss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "sqrtpd" } }, /* 0x52 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "rsqrtps", true, /* F2h */ { 0 }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "rsqrtss" }, /* 66h */ { 0 } }, /* 0x53 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "rcpps", true, /* F2h */ { 0 }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "rcpss" }, /* 66h */ { 0 } }, /* 0x54 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "andps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "andpd" } }, /* 0x55 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "andnps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "andnpd" } }, /* 0x56 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "orps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "orpd" } }, /* 0x57 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "xorps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "xorpd" } }, /* 0x58 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "addps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "addsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "addss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "addpd" } }, /* 0x59 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "mulps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "mulsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "mulss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "mulpd" } }, /* 0x5A */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PS, AM_NOT_USED, "cvtps2pd", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "cvtsd2ss" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "cvtss2sd" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PD, AM_NOT_USED, "cvtpd2ps" } }, /* 0x5B */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_DQ, AM_NOT_USED, "cvtdq2ps", true, /* F2h */ { 0 }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_PS, AM_NOT_USED, "cvttps2dq" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_PS, AM_NOT_USED, "cvtps2dq" } }, /* 0x5C */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "subps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "subsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "subss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "subpd" } }, /* 0x5D */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "minps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "minsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "minss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "minpd" } }, /* 0x5E */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "divps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "divsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "divss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "divpd" } }, /* 0x5F */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "maxps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "maxsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "maxss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "maxpd" } }, /* 0x60 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpcklbw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpcklbw" } }, /* 0x61 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpcklwd", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpcklwd" } }, /* 0x62 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpckldq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpckldq" } }, /* 0x63 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "packsswb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "packsswb" } }, /* 0x64 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "pcmpgtb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpgtb" } }, /* 0x65 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "pcmpgtw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpgtw" } }, /* 0x66 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "pcmpgtd", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpgtd" } }, /* 0x67 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "packuswb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "packuswb" } }, /* 0x68 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpckhbw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_Q | OT_DQ, AM_NOT_USED, "punpckhbw" } }, /* 0x69 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpckhwd", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_Q | OT_DQ, AM_NOT_USED, "punpckhwd" } }, /* 0x6A */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpckhdq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_Q | OT_DQ, AM_NOT_USED, "punpckhdq" } }, /* 0x6B */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "packssdw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_Q | OT_DQ, AM_NOT_USED, "packssdw" } }, /* 0x6C */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "not used without prefix", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpcklqdq" } }, /* 0x6D */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "not used without prefix", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpcklqdq" } }, /* 0x6E */ { 0, IT_GENERIC, AM_P | OT_D, AM_E | OT_D, AM_NOT_USED, "movd", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_E | OT_D, AM_NOT_USED, "movd" } }, /* 0x6F */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "movq", true, /* F2h */ { 0 }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "movdqu" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "movdqa" } }, /* 0x70 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_I | OT_B, "pshuf", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_I | OT_B, "pshuflw" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_I | OT_B, "pshufhw" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_I | OT_B, "pshufd" } }, /* 0x71 */ { 19, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x72 */ { 20, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x73 */ { 21, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x74 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pcmpeqb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpeqb" } }, /* 0x75 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pcmpeqw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpeqw" } }, /* 0x76 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pcmpeqd", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpeqd" } }, /* 0x77 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "emms", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, // The following six opcodes are escapes into the MMX stuff, which this disassembler does not support. /* 0x78 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x79 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7A */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7B */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7C */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7D */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7E */ { 0, IT_GENERIC, AM_E | OT_D, AM_P | OT_D, AM_NOT_USED, "movd", true, /* F2h */ { 0 }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movq" }, /* 66h */ { 0, IT_GENERIC, AM_E | OT_D, AM_V | OT_DQ, AM_NOT_USED, "movd" } }, /* 0x7F */ { 0, IT_GENERIC, AM_Q | OT_Q, AM_P | OT_Q, AM_NOT_USED, "movq", true, /* F2h */ { 0 }, /* F3h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_V | OT_DQ, AM_NOT_USED, "movdqu" }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_V | OT_DQ, AM_NOT_USED, "movdqa" } }, /* 0x80 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x81 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jno", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x82 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x83 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jnc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x84 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x85 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x86 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jbe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x87 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "ja", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x88 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "js", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x89 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jns", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8A */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jpe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8B */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jpo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8C */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8D */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jge", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8E */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jle", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x8F */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x90 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "seto", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x91 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setno", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x92 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x93 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setnc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x94 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x95 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x96 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setbe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x97 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "seta", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x98 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "sets", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x99 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setns", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9A */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setpe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9B */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setpo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9C */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9D */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setge", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9E */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setle", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x9F */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA0 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA1 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA2 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cpuid", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "bt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_I | OT_B, "shld", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_I | OT_B | AM_REGISTER, "shld", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA6 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA7 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA8 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xA9 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAA */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rsm", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAB */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "bts", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAC */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_I | OT_B, "shrd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAD */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_I | OT_B | AM_REGISTER, "shrd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAE */ { 22, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xAF */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "cmpxchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "cmpxchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB2 */ { 0, IT_GENERIC, AM_M | OT_P, AM_NOT_USED, AM_NOT_USED, "lss", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "btr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB4 */ { 0, IT_GENERIC, AM_M | OT_P, AM_NOT_USED, AM_NOT_USED, "lfs", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB5 */ { 0, IT_GENERIC, AM_M | OT_P, AM_NOT_USED, AM_NOT_USED, "lgs", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB6 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_B, AM_NOT_USED, "movzx", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB7 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_W, AM_NOT_USED, "movzx", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB8 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xB9 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "ud1", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBA */ { 23, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBB */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "btc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBC */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "bsf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBD */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "bsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBE */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_B, AM_NOT_USED, "movsx", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xBF */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_W, AM_NOT_USED, "movsx", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "xadd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "xadd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC2 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_I | OT_B, "cmpps", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_I | OT_B, "cmpsd" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_I | OT_B, "cmpss" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_I | OT_B, "cmppd" } }, /* 0xC3 */ { 0, IT_GENERIC, AM_E | OT_D, AM_G | OT_D, AM_NOT_USED, "movnti", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_E | OT_D, AM_I | OT_B, "pinsrw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_E | OT_D, AM_I | OT_B, "pinsrw" } }, /* 0xC5 */ { 0, IT_GENERIC, AM_G | OT_D, AM_P | OT_Q, AM_I | OT_B, "pextrw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_G | OT_D, AM_V | OT_DQ, AM_I | OT_B, "pextrw" } }, /* 0xC6 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_I | OT_B, "shufps", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_I | OT_B, "shufpd" } }, /* 0xC7 */ { 24, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC8 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xC9 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCA */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCB */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCC */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCD */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCE */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xCF */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xD1 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psrlw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrlw" } }, /* 0xD2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psrld", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrld" } }, /* 0xD3 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psrlq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrlq" } }, /* 0xD4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddq" } }, /* 0xD5 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmullw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmullw" } }, /* 0xD6 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "unused without prefix", true, /* F2h */ { 0, IT_GENERIC, AM_P | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movdq2q" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_Q | OT_Q, AM_NOT_USED, "movq2dq" }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movq" } }, /* 0xD7 */ { 0, IT_GENERIC, AM_G | OT_D, AM_P | OT_Q, AM_NOT_USED, "pmovmskb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_G | OT_D, AM_V | OT_DQ, AM_NOT_USED, "pmovmskb" } }, /* 0xD8 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubusb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubusb" } }, /* 0xD9 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubusw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubusw" } }, /* 0xDA */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pminub", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pminub" } }, /* 0xDB */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pand", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pand" } }, /* 0xDC */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddusb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddusb" } }, /* 0xDD */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddusw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddusw" } }, /* 0xDE */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmaxub", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmaxub" } }, /* 0xDF */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pandn", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pandn" } }, /* 0xE0 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pavgb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pavgb" } }, /* 0xE1 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psraw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrqw" } }, /* 0xE2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psrad", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrad" } }, /* 0xE3 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pavgw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pavgw" } }, /* 0xE4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmulhuw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmulhuw" } }, /* 0xE5 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmulhuw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmulhw" } }, /* 0xE6 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "not used without prefix", true, /* F2h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_PD, AM_NOT_USED, "cvtpd2dq" }, /* F3h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_DQ, AM_NOT_USED, "cvtdq2pd" }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_PD, AM_NOT_USED, "cvttpd2dq" } }, /* 0xE7 */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movntq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_V | OT_DQ, AM_NOT_USED, "movntdq" } }, /* 0xE8 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubsb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubsb" } }, /* 0xE9 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubsw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubsw" } }, /* 0xEA */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pminsw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pminsw" } }, /* 0xEB */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "por", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "por" } }, /* 0xEC */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddsb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddsb" } }, /* 0xED */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddsw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddsw" } }, /* 0xEE */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmaxsw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmaxsw" } }, /* 0xEF */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pxor", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pxor" } }, /* 0xF0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0xF1 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psllw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psllw" } }, /* 0xF2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pslld", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pslld" } }, /* 0xF3 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psllq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psllq" } }, /* 0xF4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmuludq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmuludq" } }, /* 0xF5 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmaddwd", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmaddwd" } }, /* 0xF6 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psadbw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psadbw" } }, /* 0xF7 */ { 0, IT_GENERIC, AM_P | OT_PI, AM_Q | OT_PI, AM_NOT_USED, "maskmovq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "maskmovdqu" } }, /* 0xF8 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubb" } }, /* 0xF9 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubw" } }, /* 0xFA */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubd", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubd" } }, /* 0xFB */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubq" } }, /* 0xFC */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddb", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddb" } }, /* 0xFD */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddw" } }, /* 0xFE */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddd", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddd" } }, /* 0xFF */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_0f00[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "sldt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "str", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "lldt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "ltr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "verr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "verw", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_0f01[] = { /* 0x0 */ { 0, IT_GENERIC, AM_M | OT_S, AM_NOT_USED, AM_NOT_USED, "sgdt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_M | OT_S, AM_NOT_USED, AM_NOT_USED, "sidt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_M | OT_S, AM_NOT_USED, AM_NOT_USED, "lgdt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_M | OT_S, AM_NOT_USED, AM_NOT_USED, "lidt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "smsw", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "lmsw", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_M | OT_B, AM_NOT_USED, AM_NOT_USED, "invlpg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_0f18[] = { /* 0x0 */ { 0, IT_GENERIC, AM_M | OT_ADDRESS_MODE_M, AM_NOT_USED, AM_NOT_USED, "prefetch", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "prefetch", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "prefetch", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "prefetch", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_0f71[] = { /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psrlw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psrlw" } }, /* 0x3 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psraw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psraw" } }, /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psllw", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psllw" } }, /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_0f72[] = { /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psrld", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psrld" } }, /* 0x3 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psrad", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psrad" } }, /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "pslld", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "pslld" } }, /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_0f73[] = { /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psrlq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psrlq" } }, /* 0x3 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psllq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psllq" } }, /* 0x7 */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "pslldq", true, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "pslldq" } }, }; const Opcode s_opcode_byte_after_0fae[] = { /* 0x0 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "fxsave", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "fxrstor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "ldmxcsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "stmxcsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "lfence", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "mfence", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "clflush/sfence", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, }; const Opcode s_opcode_byte_after_0fba[] = { /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "bt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "bts", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "btr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "btc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_0fc7[] = { /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_M | OT_Q, AM_NOT_USED, AM_NOT_USED, "cmpxch8b", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_80[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_81[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_82[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_83[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_c0[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_c1[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_d0[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_d1[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_d2[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_d3[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_f6[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "not", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "neg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, OT_B | AM_REGISTER, AM_E | OT_B, AM_NOT_USED, "mul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, OT_B | AM_REGISTER, AM_E | OT_B, AM_NOT_USED, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_E | OT_B, AM_NOT_USED, "div", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_E | OT_B, AM_NOT_USED, "idiv", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_f7[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "not", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "neg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_E | OT_V, AM_NOT_USED, "mul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_E | OT_V, AM_NOT_USED, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_E | OT_V, AM_NOT_USED, "div", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_E | OT_V, AM_NOT_USED, "idiv", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_fe[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; const Opcode s_opcode_byte_after_ff[] = { /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x2 */ { 0, IT_JUMP, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "call", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x3 */ { 0, IT_JUMP, AM_E | OT_P, AM_NOT_USED, AM_NOT_USED, "call", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x4 */ { 0, IT_JUMP, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x5 */ { 0, IT_JUMP, AM_E | OT_P, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }, /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } } }; /* * A table of all the other tables, containing some extra information, e.g. * how to mask out the byte we're looking at. */ const OpcodeTable MiniDisassembler::s_ia32_opcode_map_[]={ // One-byte opcodes and jumps to larger /* 0 */ {s_first_opcode_byte, 0, 0xff, 0, 0xff}, // Two-byte opcodes (second byte) /* 1 */ {s_opcode_byte_after_0f, 0, 0xff, 0, 0xff}, // Start of tables for opcodes using ModR/M bits as extension /* 2 */ {s_opcode_byte_after_80, 3, 0x07, 0, 0x07}, /* 3 */ {s_opcode_byte_after_81, 3, 0x07, 0, 0x07}, /* 4 */ {s_opcode_byte_after_82, 3, 0x07, 0, 0x07}, /* 5 */ {s_opcode_byte_after_83, 3, 0x07, 0, 0x07}, /* 6 */ {s_opcode_byte_after_c0, 3, 0x07, 0, 0x07}, /* 7 */ {s_opcode_byte_after_c1, 3, 0x07, 0, 0x07}, /* 8 */ {s_opcode_byte_after_d0, 3, 0x07, 0, 0x07}, /* 9 */ {s_opcode_byte_after_d1, 3, 0x07, 0, 0x07}, /* 10 */ {s_opcode_byte_after_d2, 3, 0x07, 0, 0x07}, /* 11 */ {s_opcode_byte_after_d3, 3, 0x07, 0, 0x07}, /* 12 */ {s_opcode_byte_after_f6, 3, 0x07, 0, 0x07}, /* 13 */ {s_opcode_byte_after_f7, 3, 0x07, 0, 0x07}, /* 14 */ {s_opcode_byte_after_fe, 3, 0x07, 0, 0x01}, /* 15 */ {s_opcode_byte_after_ff, 3, 0x07, 0, 0x07}, /* 16 */ {s_opcode_byte_after_0f00, 3, 0x07, 0, 0x07}, /* 17 */ {s_opcode_byte_after_0f01, 3, 0x07, 0, 0x07}, /* 18 */ {s_opcode_byte_after_0f18, 3, 0x07, 0, 0x07}, /* 19 */ {s_opcode_byte_after_0f71, 3, 0x07, 0, 0x07}, /* 20 */ {s_opcode_byte_after_0f72, 3, 0x07, 0, 0x07}, /* 21 */ {s_opcode_byte_after_0f73, 3, 0x07, 0, 0x07}, /* 22 */ {s_opcode_byte_after_0fae, 3, 0x07, 0, 0x07}, /* 23 */ {s_opcode_byte_after_0fba, 3, 0x07, 0, 0x07}, /* 24 */ {s_opcode_byte_after_0fc7, 3, 0x07, 0, 0x01} }; }; // namespace sidestep
Unknown
3D
mcellteam/mcell
libs/gperftools/src/windows/addr2line-pdb.c
.c
6,445
183
/* Copyright (c) 2008, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: David Vitek * * Dump function addresses using Microsoft debug symbols. This works * on PDB files. Note that this program will download symbols to * c:\websymbols without asking. */ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE #endif #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <dbghelp.h> #define SEARCH_CAP (1024*1024) #define WEBSYM "SRV*c:\\websymbols*http://msdl.microsoft.com/download/symbols" void usage() { fprintf(stderr, "usage: addr2line-pdb " "[-f|--functions] [-C|--demangle] [-e|--exe filename]\n"); fprintf(stderr, "(Then list the hex addresses on stdin, one per line)\n"); } int main(int argc, char *argv[]) { DWORD error; HANDLE process; ULONG64 module_base; int i; char* search; char buf[256]; /* Enough to hold one hex address, I trust! */ int rv = 0; /* We may add SYMOPT_UNDNAME if --demangle is specified: */ DWORD symopts = SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES; char* filename = "a.out"; /* The default if -e isn't specified */ int print_function_name = 0; /* Set to 1 if -f is specified */ for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--functions") == 0 || strcmp(argv[i], "-f") == 0) { print_function_name = 1; } else if (strcmp(argv[i], "--demangle") == 0 || strcmp(argv[i], "-C") == 0) { symopts |= SYMOPT_UNDNAME; } else if (strcmp(argv[i], "--exe") == 0 || strcmp(argv[i], "-e") == 0) { if (i + 1 >= argc) { fprintf(stderr, "FATAL ERROR: -e must be followed by a filename\n"); return 1; } filename = argv[i+1]; i++; /* to skip over filename too */ } else if (strcmp(argv[i], "--help") == 0) { usage(); exit(0); } else { usage(); exit(1); } } process = GetCurrentProcess(); if (!SymInitialize(process, NULL, FALSE)) { error = GetLastError(); fprintf(stderr, "SymInitialize returned error : %lu\n", error); return 1; } search = malloc(SEARCH_CAP); if (SymGetSearchPath(process, search, SEARCH_CAP)) { if (strlen(search) + sizeof(";" WEBSYM) > SEARCH_CAP) { fprintf(stderr, "Search path too long\n"); SymCleanup(process); return 1; } strcat(search, ";" WEBSYM); } else { error = GetLastError(); fprintf(stderr, "SymGetSearchPath returned error : %lu\n", error); rv = 1; /* An error, but not a fatal one */ strcpy(search, WEBSYM); /* Use a default value */ } if (!SymSetSearchPath(process, search)) { error = GetLastError(); fprintf(stderr, "SymSetSearchPath returned error : %lu\n", error); rv = 1; /* An error, but not a fatal one */ } SymSetOptions(symopts); module_base = SymLoadModuleEx(process, NULL, filename, NULL, 0, 0, NULL, 0); if (!module_base) { /* SymLoadModuleEx failed */ error = GetLastError(); fprintf(stderr, "SymLoadModuleEx returned error : %lu for %s\n", error, filename); SymCleanup(process); return 1; } buf[sizeof(buf)-1] = '\0'; /* Just to be safe */ while (fgets(buf, sizeof(buf)-1, stdin)) { /* GNU addr2line seems to just do a strtol and ignore any * weird characters it gets, so we will too. */ unsigned __int64 reladdr = _strtoui64(buf, NULL, 16); ULONG64 buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME*sizeof(TCHAR) + sizeof(ULONG64) - 1) / sizeof(ULONG64)]; memset(buffer, 0, sizeof(buffer)); PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer; IMAGEHLP_LINE64 line; DWORD dummy; // Just ignore overflow. In an overflow scenario, the resulting address // will be lower than module_base which hasn't been mapped by any prior // SymLoadModuleEx() command. This will cause SymFromAddr() and // SymGetLineFromAddr64() both to return failures and print the correct // ?? and ??:0 message variant. ULONG64 absaddr = reladdr + module_base; pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); // The length of the name is not including the null-terminating character. pSymbol->MaxNameLen = MAX_SYM_NAME - 1; if (print_function_name) { if (SymFromAddr(process, (DWORD64)absaddr, NULL, pSymbol)) { printf("%s\n", pSymbol->Name); } else { printf("??\n"); } } line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); if (SymGetLineFromAddr64(process, (DWORD64)absaddr, &dummy, &line)) { printf("%s:%d\n", line.FileName, (int)line.LineNumber); } else { printf("??:0\n"); } } SymUnloadModule64(process, module_base); SymCleanup(process); return rv; }
C
3D
mcellteam/mcell
libs/gperftools/src/windows/ia32_modrm_map.cc
.cc
5,125
122
/* Copyright (c) 2007, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Joi Sigurdsson * * Table of relevant information about how to decode the ModR/M byte. * Based on information in the IA-32 Intel® Architecture * Software Developer's Manual Volume 2: Instruction Set Reference. */ #include "mini_disassembler.h" #include "mini_disassembler_types.h" namespace sidestep { const ModrmEntry MiniDisassembler::s_ia16_modrm_map_[] = { // mod == 00 /* r/m == 000 */ { false, false, OS_ZERO }, /* r/m == 001 */ { false, false, OS_ZERO }, /* r/m == 010 */ { false, false, OS_ZERO }, /* r/m == 011 */ { false, false, OS_ZERO }, /* r/m == 100 */ { false, false, OS_ZERO }, /* r/m == 101 */ { false, false, OS_ZERO }, /* r/m == 110 */ { true, false, OS_WORD }, /* r/m == 111 */ { false, false, OS_ZERO }, // mod == 01 /* r/m == 000 */ { true, false, OS_BYTE }, /* r/m == 001 */ { true, false, OS_BYTE }, /* r/m == 010 */ { true, false, OS_BYTE }, /* r/m == 011 */ { true, false, OS_BYTE }, /* r/m == 100 */ { true, false, OS_BYTE }, /* r/m == 101 */ { true, false, OS_BYTE }, /* r/m == 110 */ { true, false, OS_BYTE }, /* r/m == 111 */ { true, false, OS_BYTE }, // mod == 10 /* r/m == 000 */ { true, false, OS_WORD }, /* r/m == 001 */ { true, false, OS_WORD }, /* r/m == 010 */ { true, false, OS_WORD }, /* r/m == 011 */ { true, false, OS_WORD }, /* r/m == 100 */ { true, false, OS_WORD }, /* r/m == 101 */ { true, false, OS_WORD }, /* r/m == 110 */ { true, false, OS_WORD }, /* r/m == 111 */ { true, false, OS_WORD }, // mod == 11 /* r/m == 000 */ { false, false, OS_ZERO }, /* r/m == 001 */ { false, false, OS_ZERO }, /* r/m == 010 */ { false, false, OS_ZERO }, /* r/m == 011 */ { false, false, OS_ZERO }, /* r/m == 100 */ { false, false, OS_ZERO }, /* r/m == 101 */ { false, false, OS_ZERO }, /* r/m == 110 */ { false, false, OS_ZERO }, /* r/m == 111 */ { false, false, OS_ZERO } }; const ModrmEntry MiniDisassembler::s_ia32_modrm_map_[] = { // mod == 00 /* r/m == 000 */ { false, false, OS_ZERO }, /* r/m == 001 */ { false, false, OS_ZERO }, /* r/m == 010 */ { false, false, OS_ZERO }, /* r/m == 011 */ { false, false, OS_ZERO }, /* r/m == 100 */ { false, true, OS_ZERO }, /* r/m == 101 */ { true, false, OS_DOUBLE_WORD }, /* r/m == 110 */ { false, false, OS_ZERO }, /* r/m == 111 */ { false, false, OS_ZERO }, // mod == 01 /* r/m == 000 */ { true, false, OS_BYTE }, /* r/m == 001 */ { true, false, OS_BYTE }, /* r/m == 010 */ { true, false, OS_BYTE }, /* r/m == 011 */ { true, false, OS_BYTE }, /* r/m == 100 */ { true, true, OS_BYTE }, /* r/m == 101 */ { true, false, OS_BYTE }, /* r/m == 110 */ { true, false, OS_BYTE }, /* r/m == 111 */ { true, false, OS_BYTE }, // mod == 10 /* r/m == 000 */ { true, false, OS_DOUBLE_WORD }, /* r/m == 001 */ { true, false, OS_DOUBLE_WORD }, /* r/m == 010 */ { true, false, OS_DOUBLE_WORD }, /* r/m == 011 */ { true, false, OS_DOUBLE_WORD }, /* r/m == 100 */ { true, true, OS_DOUBLE_WORD }, /* r/m == 101 */ { true, false, OS_DOUBLE_WORD }, /* r/m == 110 */ { true, false, OS_DOUBLE_WORD }, /* r/m == 111 */ { true, false, OS_DOUBLE_WORD }, // mod == 11 /* r/m == 000 */ { false, false, OS_ZERO }, /* r/m == 001 */ { false, false, OS_ZERO }, /* r/m == 010 */ { false, false, OS_ZERO }, /* r/m == 011 */ { false, false, OS_ZERO }, /* r/m == 100 */ { false, false, OS_ZERO }, /* r/m == 101 */ { false, false, OS_ZERO }, /* r/m == 110 */ { false, false, OS_ZERO }, /* r/m == 111 */ { false, false, OS_ZERO }, }; }; // namespace sidestep
Unknown
3D
mcellteam/mcell
libs/gperftools/src/windows/preamble_patcher.cc
.cc
29,199
737
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- /* Copyright (c) 2007, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Joi Sigurdsson * Author: Scott Francis * * Implementation of PreamblePatcher */ #include "preamble_patcher.h" #include "mini_disassembler.h" // compatibility shims #include "base/logging.h" // Definitions of assembly statements we need #define ASM_JMP32REL 0xE9 #define ASM_INT3 0xCC #define ASM_JMP32ABS_0 0xFF #define ASM_JMP32ABS_1 0x25 #define ASM_JMP8REL 0xEB #define ASM_JCC32REL_0 0x0F #define ASM_JCC32REL_1_MASK 0x80 #define ASM_NOP 0x90 // X64 opcodes #define ASM_REXW 0x48 #define ASM_MOVRAX_IMM 0xB8 #define ASM_JMP 0xFF #define ASM_JMP_RAX 0xE0 namespace sidestep { PreamblePatcher::PreamblePage* PreamblePatcher::preamble_pages_ = NULL; long PreamblePatcher::granularity_ = 0; long PreamblePatcher::pagesize_ = 0; bool PreamblePatcher::initialized_ = false; static const unsigned int kPreamblePageMagic = 0x4347414D; // "MAGC" // Handle a special case that we see with functions that point into an // IAT table (including functions linked statically into the // application): these function already starts with ASM_JMP32*. For // instance, malloc() might be implemented as a JMP to __malloc(). // This function follows the initial JMPs for us, until we get to the // place where the actual code is defined. If we get to STOP_BEFORE, // we return the address before stop_before. The stop_before_trampoline // flag is used in 64-bit mode. If true, we will return the address // before a trampoline is detected. Trampolines are defined as: // // nop // mov rax, <replacement_function> // jmp rax // // See PreamblePatcher::RawPatchWithStub for more information. void* PreamblePatcher::ResolveTargetImpl(unsigned char* target, unsigned char* stop_before, bool stop_before_trampoline) { if (target == NULL) return NULL; while (1) { unsigned char* new_target; if (target[0] == ASM_JMP32REL) { // target[1-4] holds the place the jmp goes to, but it's // relative to the next instruction. int relative_offset; // Windows guarantees int is 4 bytes SIDESTEP_ASSERT(sizeof(relative_offset) == 4); memcpy(reinterpret_cast<void*>(&relative_offset), reinterpret_cast<void*>(target + 1), 4); new_target = target + 5 + relative_offset; } else if (target[0] == ASM_JMP8REL) { // Visual Studio 7.1 implements new[] as an 8 bit jump to new signed char relative_offset; memcpy(reinterpret_cast<void*>(&relative_offset), reinterpret_cast<void*>(target + 1), 1); new_target = target + 2 + relative_offset; } else if (target[0] == ASM_JMP32ABS_0 && target[1] == ASM_JMP32ABS_1) { jmp32rel: // Visual studio seems to sometimes do it this way instead of the // previous way. Not sure what the rules are, but it was happening // with operator new in some binaries. void** new_target_v; if (kIs64BitBinary) { // In 64-bit mode JMPs are RIP-relative, not absolute int target_offset; memcpy(reinterpret_cast<void*>(&target_offset), reinterpret_cast<void*>(target + 2), 4); new_target_v = reinterpret_cast<void**>(target + target_offset + 6); } else { SIDESTEP_ASSERT(sizeof(new_target) == 4); memcpy(&new_target_v, reinterpret_cast<void*>(target + 2), 4); } new_target = reinterpret_cast<unsigned char*>(*new_target_v); } else if (kIs64BitBinary && target[0] == ASM_REXW && target[1] == ASM_JMP32ABS_0 && target[2] == ASM_JMP32ABS_1) { // in Visual Studio 2012 we're seeing jump like that: // rex.W jmpq *0x11d019(%rip) // // according to docs I have, rex prefix is actually unneeded and // can be ignored. I.e. docs say for jumps like that operand // already defaults to 64-bit. But clearly it breaks abs. jump // detection above and we just skip rex target++; goto jmp32rel; } else { break; } if (new_target == stop_before) break; if (stop_before_trampoline && *new_target == ASM_NOP && new_target[1] == ASM_REXW && new_target[2] == ASM_MOVRAX_IMM) break; target = new_target; } return target; } // Special case scoped_ptr to avoid dependency on scoped_ptr below. class DeleteUnsignedCharArray { public: DeleteUnsignedCharArray(unsigned char* array) : array_(array) { } ~DeleteUnsignedCharArray() { if (array_) { PreamblePatcher::FreePreambleBlock(array_); } } unsigned char* Release() { unsigned char* temp = array_; array_ = NULL; return temp; } private: unsigned char* array_; }; SideStepError PreamblePatcher::RawPatchWithStubAndProtections( void* target_function, void *replacement_function, unsigned char* preamble_stub, unsigned long stub_size, unsigned long* bytes_needed) { // We need to be able to write to a process-local copy of the first // MAX_PREAMBLE_STUB_SIZE bytes of target_function DWORD old_target_function_protect = 0; BOOL succeeded = ::VirtualProtect(reinterpret_cast<void*>(target_function), MAX_PREAMBLE_STUB_SIZE, PAGE_EXECUTE_READWRITE, &old_target_function_protect); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to make page containing target function " "copy-on-write."); return SIDESTEP_ACCESS_DENIED; } SideStepError error_code = RawPatchWithStub(target_function, replacement_function, preamble_stub, stub_size, bytes_needed); // Restore the protection of the first MAX_PREAMBLE_STUB_SIZE bytes of // pTargetFunction to what they were before we started goofing around. // We do this regardless of whether the patch succeeded or not. succeeded = ::VirtualProtect(reinterpret_cast<void*>(target_function), MAX_PREAMBLE_STUB_SIZE, old_target_function_protect, &old_target_function_protect); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to restore protection to target function."); // We must not return an error here because the function has // likely actually been patched, and returning an error might // cause our client code not to unpatch it. So we just keep // going. } if (SIDESTEP_SUCCESS != error_code) { // Testing RawPatchWithStub, above SIDESTEP_ASSERT(false); return error_code; } // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // // FlushInstructionCache is actually a no-op at least on // single-processor XP machines. I'm not sure why this is so, but // it is, yet I want to keep the call to the API here for // correctness in case there is a difference in some variants of // Windows/hardware. succeeded = ::FlushInstructionCache(::GetCurrentProcess(), target_function, MAX_PREAMBLE_STUB_SIZE); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); // We must not return an error here because the function has actually // been patched, and returning an error would likely cause our client // code not to unpatch it. So we just keep going. } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::RawPatch(void* target_function, void* replacement_function, void** original_function_stub) { if (!target_function || !replacement_function || !original_function_stub || (*original_function_stub) || target_function == replacement_function) { SIDESTEP_ASSERT(false && "Preconditions not met"); return SIDESTEP_INVALID_PARAMETER; } BOOL succeeded = FALSE; // First, deal with a special case that we see with functions that // point into an IAT table (including functions linked statically // into the application): these function already starts with // ASM_JMP32REL. For instance, malloc() might be implemented as a // JMP to __malloc(). In that case, we replace the destination of // the JMP (__malloc), rather than the JMP itself (malloc). This // way we get the correct behavior no matter how malloc gets called. void* new_target = ResolveTarget(target_function); if (new_target != target_function) { target_function = new_target; } // In 64-bit mode, preamble_stub must be within 2GB of target function // so that if target contains a jump, we can translate it. unsigned char* preamble_stub = AllocPreambleBlockNear(target_function); if (!preamble_stub) { SIDESTEP_ASSERT(false && "Unable to allocate preamble-stub."); return SIDESTEP_INSUFFICIENT_BUFFER; } // Frees the array at end of scope. DeleteUnsignedCharArray guard_preamble_stub(preamble_stub); SideStepError error_code = RawPatchWithStubAndProtections( target_function, replacement_function, preamble_stub, MAX_PREAMBLE_STUB_SIZE, NULL); if (SIDESTEP_SUCCESS != error_code) { SIDESTEP_ASSERT(false); return error_code; } // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // // FlushInstructionCache is actually a no-op at least on // single-processor XP machines. I'm not sure why this is so, but // it is, yet I want to keep the call to the API here for // correctness in case there is a difference in some variants of // Windows/hardware. succeeded = ::FlushInstructionCache(::GetCurrentProcess(), target_function, MAX_PREAMBLE_STUB_SIZE); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); // We must not return an error here because the function has actually // been patched, and returning an error would likely cause our client // code not to unpatch it. So we just keep going. } SIDESTEP_LOG("PreamblePatcher::RawPatch successfully patched."); // detach the scoped pointer so the memory is not freed *original_function_stub = reinterpret_cast<void*>(guard_preamble_stub.Release()); return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::Unpatch(void* target_function, void* replacement_function, void* original_function_stub) { SIDESTEP_ASSERT(target_function && replacement_function && original_function_stub); if (!target_function || !replacement_function || !original_function_stub) { return SIDESTEP_INVALID_PARAMETER; } // Before unpatching, target_function should be a JMP to // replacement_function. If it's not, then either it's an error, or // we're falling into the case where the original instruction was a // JMP, and we patched the jumped_to address rather than the JMP // itself. (For instance, if malloc() is just a JMP to __malloc(), // we patched __malloc() and not malloc().) unsigned char* target = reinterpret_cast<unsigned char*>(target_function); target = reinterpret_cast<unsigned char*>( ResolveTargetImpl( target, reinterpret_cast<unsigned char*>(replacement_function), true)); // We should end at the function we patched. When we patch, we insert // a ASM_JMP32REL instruction, so look for that as a sanity check. if (target[0] != ASM_JMP32REL) { SIDESTEP_ASSERT(false && "target_function does not look like it was patched."); return SIDESTEP_INVALID_PARAMETER; } const unsigned int kRequiredTargetPatchBytes = 5; // We need to be able to write to a process-local copy of the first // kRequiredTargetPatchBytes bytes of target_function DWORD old_target_function_protect = 0; BOOL succeeded = ::VirtualProtect(reinterpret_cast<void*>(target), kRequiredTargetPatchBytes, PAGE_EXECUTE_READWRITE, &old_target_function_protect); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to make page containing target function " "copy-on-write."); return SIDESTEP_ACCESS_DENIED; } unsigned char* preamble_stub = reinterpret_cast<unsigned char*>( original_function_stub); // Disassemble the preamble of stub and copy the bytes back to target. // If we've done any conditional jumps in the preamble we need to convert // them back to the original REL8 jumps in the target. MiniDisassembler disassembler; unsigned int preamble_bytes = 0; unsigned int target_bytes = 0; while (target_bytes < kRequiredTargetPatchBytes) { unsigned int cur_bytes = 0; InstructionType instruction_type = disassembler.Disassemble(preamble_stub + preamble_bytes, cur_bytes); if (IT_JUMP == instruction_type) { unsigned int jump_bytes = 0; SideStepError jump_ret = SIDESTEP_JUMP_INSTRUCTION; if (IsNearConditionalJump(preamble_stub + preamble_bytes, cur_bytes) || IsNearRelativeJump(preamble_stub + preamble_bytes, cur_bytes) || IsNearAbsoluteCall(preamble_stub + preamble_bytes, cur_bytes) || IsNearRelativeCall(preamble_stub + preamble_bytes, cur_bytes)) { jump_ret = PatchNearJumpOrCall(preamble_stub + preamble_bytes, cur_bytes, target + target_bytes, &jump_bytes, MAX_PREAMBLE_STUB_SIZE); } if (jump_ret == SIDESTEP_JUMP_INSTRUCTION) { SIDESTEP_ASSERT(false && "Found unsupported jump instruction in stub!!"); return SIDESTEP_UNSUPPORTED_INSTRUCTION; } target_bytes += jump_bytes; } else if (IT_GENERIC == instruction_type) { if (IsMovWithDisplacement(preamble_stub + preamble_bytes, cur_bytes)) { unsigned int mov_bytes = 0; if (PatchMovWithDisplacement(preamble_stub + preamble_bytes, cur_bytes, target + target_bytes, &mov_bytes, MAX_PREAMBLE_STUB_SIZE) != SIDESTEP_SUCCESS) { SIDESTEP_ASSERT(false && "Found unsupported generic instruction in stub!!"); return SIDESTEP_UNSUPPORTED_INSTRUCTION; } } else { memcpy(reinterpret_cast<void*>(target + target_bytes), reinterpret_cast<void*>(reinterpret_cast<unsigned char*>( original_function_stub) + preamble_bytes), cur_bytes); target_bytes += cur_bytes; } } else { SIDESTEP_ASSERT(false && "Found unsupported instruction in stub!!"); return SIDESTEP_UNSUPPORTED_INSTRUCTION; } preamble_bytes += cur_bytes; } FreePreambleBlock(reinterpret_cast<unsigned char*>(original_function_stub)); // Restore the protection of the first kRequiredTargetPatchBytes bytes of // target to what they were before we started goofing around. succeeded = ::VirtualProtect(reinterpret_cast<void*>(target), kRequiredTargetPatchBytes, old_target_function_protect, &old_target_function_protect); // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // // See comment on FlushInstructionCache elsewhere in this file. succeeded = ::FlushInstructionCache(::GetCurrentProcess(), target, MAX_PREAMBLE_STUB_SIZE); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); return SIDESTEP_UNEXPECTED; } SIDESTEP_LOG("PreamblePatcher::Unpatch successfully unpatched."); return SIDESTEP_SUCCESS; } void PreamblePatcher::Initialize() { if (!initialized_) { SYSTEM_INFO si = { 0 }; ::GetSystemInfo(&si); granularity_ = si.dwAllocationGranularity; pagesize_ = si.dwPageSize; initialized_ = true; } } unsigned char* PreamblePatcher::AllocPreambleBlockNear(void* target) { PreamblePage* preamble_page = preamble_pages_; while (preamble_page != NULL) { if (preamble_page->free_ != NULL) { __int64 val = reinterpret_cast<__int64>(preamble_page) - reinterpret_cast<__int64>(target); if ((val > 0 && val + pagesize_ <= INT_MAX) || (val < 0 && val >= INT_MIN)) { break; } } preamble_page = preamble_page->next_; } // The free_ member of the page is used to store the next available block // of memory to use or NULL if there are no chunks available, in which case // we'll allocate a new page. if (preamble_page == NULL || preamble_page->free_ == NULL) { // Create a new preamble page and initialize the free list preamble_page = reinterpret_cast<PreamblePage*>(AllocPageNear(target)); SIDESTEP_ASSERT(preamble_page != NULL && "Could not allocate page!"); void** pp = &preamble_page->free_; unsigned char* ptr = reinterpret_cast<unsigned char*>(preamble_page) + MAX_PREAMBLE_STUB_SIZE; unsigned char* limit = reinterpret_cast<unsigned char*>(preamble_page) + pagesize_; while (ptr < limit) { *pp = ptr; pp = reinterpret_cast<void**>(ptr); ptr += MAX_PREAMBLE_STUB_SIZE; } *pp = NULL; // Insert the new page into the list preamble_page->magic_ = kPreamblePageMagic; preamble_page->next_ = preamble_pages_; preamble_pages_ = preamble_page; } unsigned char* ret = reinterpret_cast<unsigned char*>(preamble_page->free_); preamble_page->free_ = *(reinterpret_cast<void**>(preamble_page->free_)); return ret; } void PreamblePatcher::FreePreambleBlock(unsigned char* block) { SIDESTEP_ASSERT(block != NULL); SIDESTEP_ASSERT(granularity_ != 0); uintptr_t ptr = reinterpret_cast<uintptr_t>(block); ptr -= ptr & (granularity_ - 1); PreamblePage* preamble_page = reinterpret_cast<PreamblePage*>(ptr); SIDESTEP_ASSERT(preamble_page->magic_ == kPreamblePageMagic); *(reinterpret_cast<void**>(block)) = preamble_page->free_; preamble_page->free_ = block; } void* PreamblePatcher::AllocPageNear(void* target) { MEMORY_BASIC_INFORMATION mbi = { 0 }; if (!::VirtualQuery(target, &mbi, sizeof(mbi))) { SIDESTEP_ASSERT(false && "VirtualQuery failed on target address"); return 0; } if (initialized_ == false) { PreamblePatcher::Initialize(); SIDESTEP_ASSERT(initialized_); } void* pv = NULL; unsigned char* allocation_base = reinterpret_cast<unsigned char*>( mbi.AllocationBase); __int64 i = 1; bool high_target = reinterpret_cast<__int64>(target) > UINT_MAX; while (pv == NULL) { __int64 val = reinterpret_cast<__int64>(allocation_base) - (i * granularity_); if (high_target && reinterpret_cast<__int64>(target) - val > INT_MAX) { // We're further than 2GB from the target break; } else if (val <= 0) { // Less than 0 break; } pv = ::VirtualAlloc(reinterpret_cast<void*>(allocation_base - (i++ * granularity_)), pagesize_, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); } // We couldn't allocate low, try to allocate high if (pv == NULL) { i = 1; // Round up to the next multiple of page granularity allocation_base = reinterpret_cast<unsigned char*>( (reinterpret_cast<__int64>(target) & (~(granularity_ - 1))) + granularity_); while (pv == NULL) { __int64 val = reinterpret_cast<__int64>(allocation_base) + (i * granularity_) - reinterpret_cast<__int64>(target); if (val > INT_MAX || val < 0) { // We're too far or we overflowed break; } pv = ::VirtualAlloc(reinterpret_cast<void*>(allocation_base + (i++ * granularity_)), pagesize_, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); } } return pv; } bool PreamblePatcher::IsShortConditionalJump( unsigned char* target, unsigned int instruction_size) { return (*(target) & 0x70) == 0x70 && instruction_size == 2; } bool PreamblePatcher::IsShortJump( unsigned char* target, unsigned int instruction_size) { return target[0] == 0xeb && instruction_size == 2; } bool PreamblePatcher::IsNearConditionalJump( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xf && (*(target + 1) & 0x80) == 0x80 && instruction_size == 6; } bool PreamblePatcher::IsNearRelativeJump( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xe9 && instruction_size == 5; } bool PreamblePatcher::IsNearAbsoluteCall( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xff && (*(target + 1) & 0x10) == 0x10 && instruction_size == 6; } bool PreamblePatcher::IsNearRelativeCall( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xe8 && instruction_size == 5; } bool PreamblePatcher::IsMovWithDisplacement( unsigned char* target, unsigned int instruction_size) { // In this case, the ModRM byte's mod field will be 0 and r/m will be 101b (5) return instruction_size == 7 && *target == 0x48 && *(target + 1) == 0x8b && (*(target + 2) >> 6) == 0 && (*(target + 2) & 0x7) == 5; } SideStepError PreamblePatcher::PatchShortConditionalJump( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { // note: rel8 offset is signed. Thus we need to ask for signed char // to negative offsets right unsigned char* original_jump_dest = (source + 2) + static_cast<signed char>(source[1]); unsigned char* stub_jump_from = target + 6; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up short jump because target" " is too far away."); return SIDESTEP_JUMP_INSTRUCTION; } *target_bytes = 6; if (target_size > *target_bytes) { // Convert the short jump to a near jump. // // 0f 8x xx xx xx xx = Jcc rel32off unsigned short jmpcode = ((0x80 | (source[0] & 0xf)) << 8) | 0x0f; memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(&jmpcode), 2); memcpy(reinterpret_cast<void*>(target + 2), reinterpret_cast<void*>(&fixup_jump_offset), 4); } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::PatchShortJump( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { // note: rel8 offset is _signed_. Thus we need signed char here. unsigned char* original_jump_dest = (source + 2) + static_cast<signed char>(source[1]); unsigned char* stub_jump_from = target + 5; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up short jump because target" " is too far away."); return SIDESTEP_JUMP_INSTRUCTION; } *target_bytes = 5; if (target_size > *target_bytes) { // Convert the short jump to a near jump. // // e9 xx xx xx xx = jmp rel32off target[0] = 0xe9; memcpy(reinterpret_cast<void*>(target + 1), reinterpret_cast<void*>(&fixup_jump_offset), 4); } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::PatchNearJumpOrCall( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { SIDESTEP_ASSERT(instruction_size == 5 || instruction_size == 6); unsigned int jmp_offset_in_instruction = instruction_size == 5 ? 1 : 2; unsigned char* original_jump_dest = reinterpret_cast<unsigned char *>( reinterpret_cast<__int64>(source + instruction_size) + *(reinterpret_cast<int*>(source + jmp_offset_in_instruction))); unsigned char* stub_jump_from = target + instruction_size; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up near jump because target" " is too far away."); return SIDESTEP_JUMP_INSTRUCTION; } if ((fixup_jump_offset < SCHAR_MAX && fixup_jump_offset > SCHAR_MIN)) { *target_bytes = 2; if (target_size > *target_bytes) { // If the new offset is in range, use a short jump instead of a near jump. if (source[0] == ASM_JCC32REL_0 && (source[1] & ASM_JCC32REL_1_MASK) == ASM_JCC32REL_1_MASK) { unsigned short jmpcode = (static_cast<unsigned char>( fixup_jump_offset) << 8) | (0x70 | (source[1] & 0xf)); memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(&jmpcode), 2); } else { target[0] = ASM_JMP8REL; target[1] = static_cast<unsigned char>(fixup_jump_offset); } } } else { *target_bytes = instruction_size; if (target_size > *target_bytes) { memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(source), jmp_offset_in_instruction); memcpy(reinterpret_cast<void*>(target + jmp_offset_in_instruction), reinterpret_cast<void*>(&fixup_jump_offset), 4); } } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::PatchMovWithDisplacement( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { SIDESTEP_ASSERT(instruction_size == 7); const int mov_offset_in_instruction = 3; // 0x48 0x8b 0x0d <offset> unsigned char* original_mov_dest = reinterpret_cast<unsigned char*>( reinterpret_cast<__int64>(source + instruction_size) + *(reinterpret_cast<int*>(source + mov_offset_in_instruction))); unsigned char* stub_mov_from = target + instruction_size; __int64 fixup_mov_offset = original_mov_dest - stub_mov_from; if (fixup_mov_offset > INT_MAX || fixup_mov_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up near MOV because target is too far away."); return SIDESTEP_UNEXPECTED; } *target_bytes = instruction_size; if (target_size > *target_bytes) { memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(source), mov_offset_in_instruction); memcpy(reinterpret_cast<void*>(target + mov_offset_in_instruction), reinterpret_cast<void*>(&fixup_mov_offset), 4); } return SIDESTEP_SUCCESS; } }; // namespace sidestep
Unknown
3D
mcellteam/mcell
libs/gperftools/src/windows/mini_disassembler_types.h
.h
8,505
238
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- /* Copyright (c) 2007, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Joi Sigurdsson * * Several simple types used by the disassembler and some of the patching * mechanisms. */ #ifndef GOOGLE_PERFTOOLS_MINI_DISASSEMBLER_TYPES_H_ #define GOOGLE_PERFTOOLS_MINI_DISASSEMBLER_TYPES_H_ namespace sidestep { // Categories of instructions that we care about enum InstructionType { // This opcode is not used IT_UNUSED, // This disassembler does not recognize this opcode (error) IT_UNKNOWN, // This is not an instruction but a reference to another table IT_REFERENCE, // This byte is a prefix byte that we can ignore IT_PREFIX, // This is a prefix byte that switches to the nondefault address size IT_PREFIX_ADDRESS, // This is a prefix byte that switches to the nondefault operand size IT_PREFIX_OPERAND, // A jump or call instruction IT_JUMP, // A return instruction IT_RETURN, // Any other type of instruction (in this case we don't care what it is) IT_GENERIC, }; // Lists IA-32 operand sizes in multiples of 8 bits enum OperandSize { OS_ZERO = 0, OS_BYTE = 1, OS_WORD = 2, OS_DOUBLE_WORD = 4, OS_QUAD_WORD = 8, OS_DOUBLE_QUAD_WORD = 16, OS_32_BIT_POINTER = 32/8, OS_48_BIT_POINTER = 48/8, OS_SINGLE_PRECISION_FLOATING = 32/8, OS_DOUBLE_PRECISION_FLOATING = 64/8, OS_DOUBLE_EXTENDED_PRECISION_FLOATING = 80/8, OS_128_BIT_PACKED_SINGLE_PRECISION_FLOATING = 128/8, OS_PSEUDO_DESCRIPTOR = 6 }; // Operand addressing methods from the IA-32 manual. The enAmMask value // is a mask for the rest. The other enumeration values are named for the // names given to the addressing methods in the manual, e.g. enAm_D is for // the D addressing method. // // The reason we use a full 4 bytes and a mask, is that we need to combine // these flags with the enOperandType to store the details // on the operand in a single integer. enum AddressingMethod { AM_NOT_USED = 0, // This operand is not used for this instruction AM_MASK = 0x00FF0000, // Mask for the rest of the values in this enumeration AM_A = 0x00010000, // A addressing type AM_C = 0x00020000, // C addressing type AM_D = 0x00030000, // D addressing type AM_E = 0x00040000, // E addressing type AM_F = 0x00050000, // F addressing type AM_G = 0x00060000, // G addressing type AM_I = 0x00070000, // I addressing type AM_J = 0x00080000, // J addressing type AM_M = 0x00090000, // M addressing type AM_O = 0x000A0000, // O addressing type AM_P = 0x000B0000, // P addressing type AM_Q = 0x000C0000, // Q addressing type AM_R = 0x000D0000, // R addressing type AM_S = 0x000E0000, // S addressing type AM_T = 0x000F0000, // T addressing type AM_V = 0x00100000, // V addressing type AM_W = 0x00110000, // W addressing type AM_X = 0x00120000, // X addressing type AM_Y = 0x00130000, // Y addressing type AM_REGISTER = 0x00140000, // Specific register is always used as this op AM_IMPLICIT = 0x00150000, // An implicit, fixed value is used }; // Operand types from the IA-32 manual. The enOtMask value is // a mask for the rest. The rest of the values are named for the // names given to these operand types in the manual, e.g. enOt_ps // is for the ps operand type in the manual. // // The reason we use a full 4 bytes and a mask, is that we need // to combine these flags with the enAddressingMethod to store the details // on the operand in a single integer. enum OperandType { OT_MASK = 0xFF000000, OT_A = 0x01000000, OT_B = 0x02000000, OT_C = 0x03000000, OT_D = 0x04000000, OT_DQ = 0x05000000, OT_P = 0x06000000, OT_PI = 0x07000000, OT_PS = 0x08000000, // actually unsupported for (we don't know its size) OT_Q = 0x09000000, OT_S = 0x0A000000, OT_SS = 0x0B000000, OT_SI = 0x0C000000, OT_V = 0x0D000000, OT_W = 0x0E000000, OT_SD = 0x0F000000, // scalar double-precision floating-point value OT_PD = 0x10000000, // double-precision floating point // dummy "operand type" for address mode M - which doesn't specify // operand type OT_ADDRESS_MODE_M = 0x80000000 }; // Flag that indicates if an immediate operand is 64-bits. // // The Intel 64 and IA-32 Architecture Software Developer's Manual currently // defines MOV as the only instruction supporting a 64-bit immediate operand. enum ImmediateOperandSize { IOS_MASK = 0x0000F000, IOS_DEFAULT = 0x0, IOS_64 = 0x00001000 }; // Everything that's in an Opcode (see below) except the three // alternative opcode structs for different prefixes. struct SpecificOpcode { // Index to continuation table, or 0 if this is the last // byte in the opcode. int table_index_; // The opcode type InstructionType type_; // Description of the type of the dest, src and aux operands, // put together from enOperandType, enAddressingMethod and // enImmediateOperandSize flags. int flag_dest_; int flag_source_; int flag_aux_; // We indicate the mnemonic for debugging purposes const char* mnemonic_; }; // The information we keep in our tables about each of the different // valid instructions recognized by the IA-32 architecture. struct Opcode { // Index to continuation table, or 0 if this is the last // byte in the opcode. int table_index_; // The opcode type InstructionType type_; // Description of the type of the dest, src and aux operands, // put together from an enOperandType flag and an enAddressingMethod // flag. unsigned flag_dest_; unsigned flag_source_; unsigned flag_aux_; // We indicate the mnemonic for debugging purposes const char* mnemonic_; // Alternative opcode info if certain prefixes are specified. // In most cases, all of these are zeroed-out. Only used if // bPrefixDependent is true. bool is_prefix_dependent_; SpecificOpcode opcode_if_f2_prefix_; SpecificOpcode opcode_if_f3_prefix_; SpecificOpcode opcode_if_66_prefix_; }; // Information about each table entry. struct OpcodeTable { // Table of instruction entries const Opcode* table_; // How many bytes left to shift ModR/M byte <b>before</b> applying mask unsigned char shift_; // Mask to apply to byte being looked at before comparing to table unsigned char mask_; // Minimum/maximum indexes in table. unsigned char min_lim_; unsigned char max_lim_; }; // Information about each entry in table used to decode ModR/M byte. struct ModrmEntry { // Is the operand encoded as bytes in the instruction (rather than // if it's e.g. a register in which case it's just encoded in the // ModR/M byte) bool is_encoded_in_instruction_; // Is there a SIB byte? In this case we always need to decode it. bool use_sib_byte_; // What is the size of the operand (only important if it's encoded // in the instruction)? OperandSize operand_size_; }; }; // namespace sidestep #endif // GOOGLE_PERFTOOLS_MINI_DISASSEMBLER_TYPES_H_
Unknown