summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSung-jae Park <nicesj.park@samsung.com>2012-12-20 17:10:58 +0900
committerSung-jae Park <nicesj.park@samsung.com>2012-12-20 17:10:58 +0900
commit22f84d43dab1118a4bf64b2bc187f64f23358318 (patch)
tree575352fa6ab79abb8a56d1368b02b84d70139960
parent0494e95f3463fac59f88b4114834bb175fa150b0 (diff)
downloadheap-monitor-22f84d43dab1118a4bf64b2bc187f64f23358318.tar.gz
heap-monitor-22f84d43dab1118a4bf64b2bc187f64f23358318.tar.bz2
heap-monitor-22f84d43dab1118a4bf64b2bc187f64f23358318.zip
Initialize the project.
Change-Id: I714e97a2fe9f99d5902c34e463737227bbfb5948
-rw-r--r--CMakeLists.txt51
-rw-r--r--LICENSE83
-rw-r--r--detector/Makefile7
-rw-r--r--detector/detector.c73
-rw-r--r--detector/test.c51
-rw-r--r--heap-monitor.pc.in11
-rw-r--r--include/dlist.h43
-rw-r--r--include/heap-monitor.h26
-rw-r--r--libheap-monitor.manifest5
-rw-r--r--packaging/libheap-monitor.spec45
-rw-r--r--sample/Makefile2
-rw-r--r--sample/sample.c111
-rw-r--r--src/dlist.c180
-rw-r--r--src/heap-monitor.c732
14 files changed, 1420 insertions, 0 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..2718d8b
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,51 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(heap-monitor C)
+
+SET(PREFIX ${CMAKE_INSTALL_PREFIX})
+SET(EXEC_PREFIX "\${prefix}")
+SET(PROJECT_NAME "${PROJECT_NAME}")
+SET(LIBDIR "\${exec_prefix}/lib")
+SET(INCLUDEDIR "\${prefix}/include/${PROJECT_NAME}")
+SET(VERSION_MAJOR 0)
+SET(VERSION "${VERSION_MAJOR}.0.1")
+
+set(CMAKE_SKIP_BUILD_RPATH true)
+
+INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(pkgs REQUIRED
+ dlog
+)
+
+FOREACH(flag ${pkgs_CFLAGS})
+ SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fvisibility=hidden -Wall -Werror -Winline -fno-builtin-malloc -O3 -g")
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+ADD_DEFINITIONS("-DPREFIX=\"${PREFIX}\"")
+ADD_DEFINITIONS("-DNDEBUG")
+ADD_DEFINITIONS("-DLOG_TAG=\"${PROJECT_NAME}\"")
+ADD_DEFINITIONS("-D_THREAD_SAFETY")
+
+ADD_LIBRARY(${PROJECT_NAME} SHARED
+ src/heap-monitor.c
+ src/dlist.c
+)
+
+SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${VERSION})
+TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${pkgs_LDFLAGS} "-lpthread")
+
+CONFIGURE_FILE(${PROJECT_NAME}.pc.in ${PROJECT_NAME}.pc @ONLY)
+SET_DIRECTORY_PROPERTIES(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${PROJECT_NAME}.pc")
+
+INSTALL(TARGETS ${PROJECT_NAME} DESTINATION lib)
+INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc DESTINATION lib/pkgconfig)
+INSTALL(FILES ${CMAKE_SOURCE_DIR}/include/heap-monitor.h DESTINATION include/${PROJECT_NAME})
+INSTALL(FILES ${CMAKE_SOURCE_DIR}/LICENSE DESTINATION /usr/share/license RENAME "lib${PROJECT_NAME}")
+
+#ADD_SUBDIRECTORY(data)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..27daa90
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,83 @@
+Flora License
+
+Version 1.0, May, 2012
+
+http://www.tizenopensource.org/license
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+"Tizen Certified Platform" shall mean a software platform that complies with the standards set forth in the Compatibility Definition Document and passes the Compatibility Test Suite as defined from time to time by the Tizen Technical Steering Group and certified by the Tizen Association or its designated agent.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work solely as incorporated into a Tizen Certified Platform, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work solely as incorporated into a Tizen Certified Platform to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof pursuant to the copyright license above, in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+You must give any other recipients of the Work or Derivative Works a copy of this License; and
+You must cause any modified files to carry prominent notices stating that You changed the files; and
+You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Flora License to your work
+
+To apply the Flora License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+
+
+ Licensed under the Flora License, Version 1.0 (the "License");
+
+ you may not use this file except in compliance with the License.
+
+ You may obtain a copy of the License at
+
+
+
+ http://www.tizenopensource.org/license
+
+
+
+ Unless required by applicable law or agreed to in writing, software
+
+ distributed under the License is distributed on an "AS IS" BASIS,
+
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+
+ See the License for the specific language governing permissions and
+
+ limitations under the License.
diff --git a/detector/Makefile b/detector/Makefile
new file mode 100644
index 0000000..5b4a905
--- /dev/null
+++ b/detector/Makefile
@@ -0,0 +1,7 @@
+all:
+ @gcc detector.c -o libdetector.so `pkg-config heap-monitor --libs --cflags` -shared -fPIC -Wall -Werror
+ @gcc test.c -o test -pthread -Wall -Werror
+
+clean:
+ @rm -rf libdetector.so
+ @rm -rf test
diff --git a/detector/detector.c b/detector/detector.c
new file mode 100644
index 0000000..c779319
--- /dev/null
+++ b/detector/detector.c
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2012 Samsung Electronics Co., Ltd
+ *
+ * Licensed under the Flora License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.tizenopensource.org/license
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#include <heap-monitor.h>
+
+int errno;
+static char execpath[4096];
+
+int destructor(void) __attribute__((destructor));
+int constructor(void) __attribute__((constructor));
+
+void (*__malloc_initialize_hook)(void) = heap_monitor_init;
+
+int constructor(void)
+{
+ int fd;
+
+ snprintf(execpath, sizeof(execpath), "/proc/%d/cmdline", getpid());
+
+ fd = open(execpath, O_RDONLY);
+ if (fd >= 0) {
+ int len;
+ len = read(fd, execpath, sizeof(execpath));
+ close(fd);
+
+ printf("execpath: [%s]\n", execpath);
+
+ heap_monitor_add_target("");
+ heap_monitor_start();
+ } else {
+ printf("open: %s\n", strerror(errno));
+ }
+
+ return 0;
+}
+
+int destructor(void)
+{
+ if (strlen(execpath)) {
+ int usage;
+
+ heap_monitor_stop();
+ usage = heap_monitor_target_usage("");
+ heap_monitor_del_target("");
+
+ printf("execpath: [%s]\n", execpath);
+ printf("Leak: %d\n", usage);
+ }
+ return 0;
+}
+
+/* End of a file */
diff --git a/detector/test.c b/detector/test.c
new file mode 100644
index 0000000..d649f8c
--- /dev/null
+++ b/detector/test.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2012 Samsung Electronics Co., Ltd
+ *
+ * Licensed under the Flora License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.tizenopensource.org/license
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <malloc.h>
+#include <string.h>
+#include <errno.h>
+#include <pthread.h>
+
+int errno;
+
+int main(int argc, char *argv[])
+{
+ void *ptr;
+ int err;
+ size_t size;
+ pthread_attr_t attr;
+ ptr = malloc(1000);
+ ptr = malloc(1000);
+ ptr = malloc(1000);
+ ptr = malloc(1000);
+ ptr = malloc(1000);
+ memset(ptr, 0, 1000);
+ printf("ptr: %p\n", ptr);
+ err = pthread_getattr_np(pthread_self(), &attr);
+ if (!err) {
+ void *addr;
+ pthread_attr_getstack(&attr, &addr, &size);
+ printf("stack: %p [%d]\n", addr, size);
+ pthread_attr_destroy(&attr);
+ } else {
+ printf("error: %s\n", strerror(err));
+ }
+ return 0;
+}
+
+/* End of a file */
diff --git a/heap-monitor.pc.in b/heap-monitor.pc.in
new file mode 100644
index 0000000..6730d7c
--- /dev/null
+++ b/heap-monitor.pc.in
@@ -0,0 +1,11 @@
+prefix=@PREFIX@
+exec_prefix=@EXEC_PREFIX@
+libdir=@LIBDIR@
+includedir=@INCLUDEDIR@
+
+Name: libheap-monitor
+Description: Monitoring the heap usage with caller information
+Version: @VERSION@
+Libs: -L${libdir} -lheap-monitor
+cppflags: -I${includedir}
+Cflags: -I${includedir}
diff --git a/include/dlist.h b/include/dlist.h
new file mode 100644
index 0000000..b4a5719
--- /dev/null
+++ b/include/dlist.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2012 Samsung Electronics Co., Ltd
+ *
+ * Licensed under the Flora License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.tizenopensource.org/license
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define dlist_remove_data(list, data) do { \
+ struct dlist *l; \
+ l = dlist_find_data(list, data); \
+ list = dlist_remove(list, l); \
+} while (0)
+
+#define dlist_foreach(list, l, data) \
+ for ((l) = (list); (l) && ((data) = dlist_data(l)); (l) = dlist_next(l))
+
+#define dlist_foreach_safe(list, l, n, data) \
+ for ((l) = (list), (n) = dlist_next(l); \
+ (l) && ((data) = dlist_data(l)); \
+ (l) = (n), (n) = dlist_next(l))
+
+struct dlist;
+
+extern struct dlist *dlist_append(struct dlist *list, void *data);
+extern struct dlist *dlist_prepend(struct dlist *list, void *data);
+extern struct dlist *dlist_remove(struct dlist *list, struct dlist *l);
+extern struct dlist *dlist_find_data(struct dlist *list, void *data);
+extern void *dlist_data(struct dlist *l);
+extern struct dlist *dlist_next(struct dlist *l);
+extern struct dlist *dlist_prev(struct dlist *l);
+extern int dlist_count(struct dlist *l);
+extern struct dlist *dlist_nth(struct dlist *l, int nth);
+
+/* End of a file */
diff --git a/include/heap-monitor.h b/include/heap-monitor.h
new file mode 100644
index 0000000..fc787d9
--- /dev/null
+++ b/include/heap-monitor.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2012 Samsung Electronics Co., Ltd
+ *
+ * Licensed under the Flora License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.tizenopensource.org/license
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+extern int heap_monitor_initialized(void);
+extern void heap_monitor_init(void);
+extern void heap_monitor_start(void);
+extern void heap_monitor_stop(void);
+extern size_t heap_monitor_target_usage(const char *name);
+extern int heap_monitor_add_target(const char *name);
+extern int heap_monitor_del_target(const char *name);
+extern void heap_monitor_set_stack_boundary(unsigned long stack_boundary);
+
+/* End of a file */
diff --git a/libheap-monitor.manifest b/libheap-monitor.manifest
new file mode 100644
index 0000000..a76fdba
--- /dev/null
+++ b/libheap-monitor.manifest
@@ -0,0 +1,5 @@
+<manifest>
+ <request>
+ <domain name="_" />
+ </request>
+</manifest>
diff --git a/packaging/libheap-monitor.spec b/packaging/libheap-monitor.spec
new file mode 100644
index 0000000..e9578ad
--- /dev/null
+++ b/packaging/libheap-monitor.spec
@@ -0,0 +1,45 @@
+Name: libheap-monitor
+Summary: Library for monitoring the heap usage
+Version: 0.0.9
+Release: 1
+Group: main/app
+License: Flora License
+Source0: %{name}-%{version}.tar.gz
+BuildRequires: cmake, gettext-tools
+BuildRequires: pkgconfig(dlog)
+
+%description
+Monitoring the heap usage to manage them safely.
+
+%package devel
+Summary: Files for implementaion of the heap monitor.
+Group: Development/Libraries
+Requires: %{name} = %{version}-%{release}
+
+%description devel
+Monitoring the heap usage to manage them safely.(dev)
+
+%prep
+%setup -q
+
+%build
+cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix}
+CFLAGS+="${CFLAGS} -fvisibility=hidden -Wall -Werror -Winline -fno-builtin-malloc" make %{?jobs:-j%jobs}
+
+%install
+rm -rf %{buildroot}
+%make_install
+mkdir -p %{buildroot}/usr/share/license
+
+%post
+
+%files
+%manifest libheap-monitor.manifest
+%defattr(-,root,root,-)
+/usr/lib/*.so*
+/usr/share/license/*
+
+%files devel
+%defattr(-,root,root,-)
+/usr/include/heap-monitor/heap-monitor.h
+/usr/lib/pkgconfig/*.pc
diff --git a/sample/Makefile b/sample/Makefile
new file mode 100644
index 0000000..3fd37c9
--- /dev/null
+++ b/sample/Makefile
@@ -0,0 +1,2 @@
+all:
+ gcc sample.c -o sample `pkg-config heap-monitor --cflags --libs`
diff --git a/sample/sample.c b/sample/sample.c
new file mode 100644
index 0000000..0060c4e
--- /dev/null
+++ b/sample/sample.c
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2012 Samsung Electronics Co., Ltd
+ *
+ * Licensed under the Flora License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.tizenopensource.org/license
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <malloc.h>
+#include <errno.h>
+
+#include <heap-monitor.h>
+
+#define LIBC "/lib/libc-2.13.so"
+
+int errno;
+
+int main(int argc, char *argv[])
+{
+ void *ptr;
+ void *o_ptr;
+ int i;
+ int reused;
+ int cnt;
+ unsigned long align;
+
+ heap_monitor_add_target(argv[0]);
+ heap_monitor_add_target(LIBC);
+ heap_monitor_init();
+ heap_monitor_start();
+
+ o_ptr = NULL;
+ reused = 0;
+ cnt = 1000;
+ for (i = 0; i < cnt; i++) {
+ o_ptr = malloc(1000);
+ memset(o_ptr, 0, 1000);
+ free(o_ptr);
+
+ ptr = malloc(2000);
+ memset(ptr, 0, 1000);
+ free(ptr);
+
+ reused += (o_ptr == ptr);
+ }
+
+ align = 1024;
+ if (posix_memalign(&ptr, align, 100)) {
+ printf("Failed to allocate aligned memory\n");
+ } else {
+ void *abc;
+ printf("posix_memalign aligned: %lu, %lu\n", (unsigned long)ptr, (unsigned long)ptr % align);
+
+ abc = realloc(ptr, 200);
+ if (abc) {
+ printf("realloc aligned: %lu, %lu\n", (unsigned long)abc, (unsigned long)abc % align);
+ ptr = abc;
+ }
+ free(ptr);
+ }
+
+ ptr = memalign(align, 100);
+ if (!ptr) {
+ printf("Failed to allocate aligned memory\n");
+ } else {
+ printf("memalign aligned: %lu, %lu\n", (unsigned long)ptr, (unsigned long)ptr % align);
+ printf("memalign aligned: %lu, %lu\n", (unsigned long)ptr, (unsigned long)ptr % 4);
+ free(ptr);
+ }
+
+ align = 100;
+ ptr = memalign(align, 100);
+ if (!ptr) {
+ printf("Failed to allocate aligned memory\n");
+ } else {
+ printf(">> aligned: %lu, %lu\n", (unsigned long)ptr, (unsigned long)ptr % align);
+ free(ptr);
+ }
+
+ ptr = malloc(100);
+ printf("[%s] uses %d\n", argv[0], heap_monitor_target_usage(argv[0]));
+ printf("[%s] uses %d\n", LIBC, heap_monitor_target_usage(LIBC));
+ ptr = realloc(ptr, 200);
+ printf("[%s] uses %d\n", argv[0], heap_monitor_target_usage(argv[0]));
+ printf("[%s] uses %d\n", LIBC, heap_monitor_target_usage(LIBC));
+ free(ptr);
+
+ heap_monitor_stop();
+
+ printf("[%s] uses %d\n", argv[0], heap_monitor_target_usage(argv[0]));
+ printf("[%s] uses %d\n", LIBC, heap_monitor_target_usage(LIBC));
+ if (heap_monitor_target_usage(argv[0]))
+ printf("LEAK detected\n");
+
+ printf("heap chunk resuing rates (%d/%d) %.0lf%%\n", reused, cnt, (double)reused * 100.0f/(double)cnt);
+ heap_monitor_del_target(argv[0]);
+ heap_monitor_del_target(LIBC);
+ return 0;
+}
+
+/* End of a file */
diff --git a/src/dlist.c b/src/dlist.c
new file mode 100644
index 0000000..56ff060
--- /dev/null
+++ b/src/dlist.c
@@ -0,0 +1,180 @@
+/*
+ * Copyright 2012 Samsung Electronics Co., Ltd
+ *
+ * Licensed under the Flora License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.tizenopensource.org/license
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "dlist.h"
+
+/*!
+ * \brief
+ * This dlist is called Modified Doubly Linked List.
+ *
+ * Noramlly, The dobule linked list contains address of previous and next element.
+ * This dlist also contains them, but the tail element only contains prev address.
+ *
+ * The head element's prev pointer indicates the last element.
+ * But the last element's next pointer indicates NIL.
+ *
+ * So we can find the last element while crawling this DList
+ * But we have to remember the address of the head element.
+ */
+
+struct dlist {
+ struct dlist *next;
+ struct dlist *prev;
+ void *data;
+};
+
+struct dlist *dlist_append(struct dlist *list, void *data)
+{
+ struct dlist *item;
+
+ item = malloc(sizeof(*item));
+ if (!item)
+ return NULL;
+
+ item->next = NULL;
+ item->data = data;
+
+ if (!list) {
+ item->prev = item;
+
+ list = item;
+ } else {
+ item->prev = list->prev;
+ item->prev->next = item;
+ list->prev = item;
+ }
+
+ assert(!list->prev->next && "item NEXT");
+
+ return list;
+}
+
+struct dlist *dlist_prepend(struct dlist *list, void *data)
+{
+ struct dlist *item;
+
+ item = malloc(sizeof(*item));
+ if (!item)
+ return NULL;
+
+ item->data = data;
+
+ if (!list) {
+ item->prev = item;
+ item->next = NULL;
+ } else {
+ if (list->prev->next)
+ list->prev->next = item;
+
+ item->prev = list->prev;
+ item->next = list;
+
+ list->prev = item;
+
+ }
+
+ return item;
+}
+
+struct dlist *dlist_remove(struct dlist *list, struct dlist *l)
+{
+ if (!list || !l)
+ return NULL;
+
+ if (l == list)
+ list = l->next;
+ else
+ l->prev->next = l->next;
+
+ if (l->next)
+ l->next->prev = l->prev;
+ /*!
+ * \note
+ * If the removed entry 'l' has no next element, it is the last element.
+ * In this case, check the existence of the list first,
+ * and if the list is not empty, update the 'prev' of the list (which is a head element of the list)
+ *
+ * If we didn't care about this, the head element(list) can indicates the invalid element.
+ */
+ else if (list)
+ list->prev = l->prev;
+
+ free(l);
+ return list;
+}
+
+struct dlist *dlist_find_data(struct dlist *list, void *data)
+{
+ struct dlist *l;
+ void *_data;
+
+ dlist_foreach(list, l, _data) {
+ if (data == _data)
+ return l;
+ }
+
+ return NULL;
+}
+
+void *dlist_data(struct dlist *l)
+{
+ return l ? l->data : NULL;
+}
+
+struct dlist *dlist_next(struct dlist *l)
+{
+ return l ? l->next : NULL;
+}
+
+struct dlist *dlist_prev(struct dlist *l)
+{
+ return l ? l->prev : NULL;
+}
+
+int dlist_count(struct dlist *l)
+{
+ register int i;
+ struct dlist *n;
+ void *data;
+
+ i = 0;
+ dlist_foreach(l, n, data) {
+ i++;
+ }
+
+ return i;
+}
+
+struct dlist *dlist_nth(struct dlist *l, int nth)
+{
+ register int i;
+ struct dlist *n;
+
+ i = 0;
+ for (n = l; n; n = n->next) {
+ if (i == nth)
+ return n;
+ i++;
+ }
+
+ return NULL;
+}
+
+/* End of a file */
diff --git a/src/heap-monitor.c b/src/heap-monitor.c
new file mode 100644
index 0000000..ea08d39
--- /dev/null
+++ b/src/heap-monitor.c
@@ -0,0 +1,732 @@
+/*
+ * Copyright 2012 Samsung Electronics Co., Ltd
+ *
+ * Licensed under the Flora License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.tizenopensource.org/license
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <libgen.h>
+#include <stdio.h>
+#include <malloc.h>
+#include <errno.h>
+#include <dlfcn.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <sys/time.h>
+#include <pthread.h>
+#include <link.h>
+#include <elf.h>
+#include <mcheck.h>
+
+#include <dlog.h>
+
+#include "dlist.h"
+#include "heap-monitor.h"
+
+#if !defined(FLOG)
+#define DbgPrint(format, arg...) LOGD("[%s/%s:%d] " format, basename(__FILE__), __func__, __LINE__, ##arg)
+#define ErrPrint(format, arg...) LOGE("[%s/%s:%d] " format, basename(__FILE__), __func__, __LINE__, ##arg)
+#else
+extern FILE *__file_log_fp;
+#define DbgPrint(format, arg...) do { fprintf(__file_log_fp, "[LOG] [%s/%s:%d] " format, basename(__FILE__), __func__, __LINE__, ##arg); fflush(__file_log_fp); } while (0)
+
+#define ErrPrint(format, arg...) do { fprintf(__file_log_fp, "[ERR] [%s/%s:%d] " format, basename(__FILE__), __func__, __LINE__, ##arg); fflush(__file_log_fp); } while (0)
+#endif
+/* End of a file */
+
+#define container_of(ptr, type, member) \
+ ({ const typeof( ((type *)0)->member ) *__mptr = (ptr); \
+ (type *)( (char *)__mptr - offsetof(type,member) );})
+
+#define API __attribute__((visibility("default")))
+#define DUMP_DEPTH 80000
+
+#if defined(_ESTIMATE_PERFORMANCE)
+#define ESTIMATE_START() \
+do { \
+ struct timeval stv; \
+ struct timeval etv; \
+ struct timeval rtv; \
+ static struct timeval ttv; \
+ static int initialized = 0; \
+ if (!initialized) { \
+ timerclear(&ttv); \
+ initialized = 1; \
+ } \
+ gettimeofday(&stv, NULL)
+
+#define ESTIMATE_END() \
+ gettimeofday(&etv, NULL); \
+ gettimeofday(&etv, NULL); \
+ timersub(&etv, &stv, &rtv); \
+ timeradd(&rtv, &ttv, &ttv); \
+ DbgPrint("Elapsed time: %lu.%lf\n", rtv.tv_sec, (double)rtv.tv_usec / 1000000.0f); \
+ DbgPrint("Total: %lu.%lf\n", ttv.tv_sec, (double)ttv.tv_usec / 1000000.0f); \
+} while (0)
+#else
+#define ESTIMATE_START() // pthread_mutex_lock(&s_info.mutex)
+#define ESTIMATE_END() // pthread_mutex_unlock(&s_info.mutex)
+#endif
+
+#if defined(_THREAD_SAFETY)
+#define LOCK() pthread_mutex_lock(&s_info.mutex)
+#define UNLOCK() pthread_mutex_unlock(&s_info.mutex)
+#else
+#define LOCK()
+#define UNLOCK()
+#endif
+
+typedef void *(*malloc_t)(size_t size, const void *caller);
+typedef void *(*realloc_t)(void *ptr, size_t size, const void *caller);
+typedef void (*free_t)(void *ptr, const void *caller);
+typedef void *(*memalign_t)(size_t align, size_t size, const void *caller);
+
+int errno;
+
+struct chunk {
+ struct target *info;
+ int size;
+ int pad;
+ enum {
+ VALID = 0xbeefbeef,
+ INVALID = 0xdeaddead,
+ } state;
+ char data[];
+};
+
+#define SET_PAD(ptr, pad) (*(((int *)ptr) - 2) = (pad))
+#define SET_STATE(ptr, state) (*(((int *)ptr) - 1) = (state))
+#define PAD(ptr) (*(((int *)ptr) - 2))
+#define STATE(ptr) (*(((int *)ptr) - 1))
+
+struct target {
+ char *name;
+ int usage;
+ unsigned long begin;
+ unsigned long end;
+};
+
+static struct {
+ malloc_t _malloc;
+ realloc_t _realloc;
+ free_t _free;
+ memalign_t _memalign;
+ struct dlist *target_list;
+ int hook;
+ int dump_depth;
+ unsigned long stack_boundary;
+ unsigned long stack_base;
+ size_t stack_size;
+ pthread_mutex_t mutex;
+ int debugger;
+ int target_cnt;
+ pthread_t main_tid;
+ int initialized;
+ int m_check;
+} s_info = {
+ ._malloc = NULL,
+ ._realloc = NULL,
+ ._free = NULL,
+ ._memalign = NULL,
+ .target_list = NULL,
+ .hook = 0,
+ .dump_depth = DUMP_DEPTH,
+ .stack_boundary = 0,
+ .mutex = PTHREAD_MUTEX_INITIALIZER,
+ .debugger = 0,
+ .target_cnt = 0,
+ .initialized = 0,
+ .m_check = 0,
+};
+
+static void unhook(void);
+static void hook(void);
+
+static inline struct target *find_target_by_name(const char *name)
+{
+ struct dlist *l;
+ struct target *target;
+
+ dlist_foreach(s_info.target_list, l, target) {
+ if (!strcmp(target->name, name))
+ return target;
+ }
+
+ return NULL;
+}
+
+static inline struct target *find_target_by_addr(unsigned long addr)
+{
+ struct dlist *l;
+ struct target *target;
+
+ dlist_foreach(s_info.target_list, l, target) {
+ if (target->begin <= addr && addr < target->end)
+ return target;
+ }
+
+ return NULL;
+}
+
+/*!
+ * \node deprecated
+ Dl_info info;
+ ret = dladdr((void *)*stack, &info);
+ if (!ret)
+ continue;
+
+ target = find_target_by_name(info.dli_fname);
+*/
+static struct target *find_target_info(void)
+{
+ int ret;
+ register struct target *target;
+ register unsigned long *stack;
+ register int i;
+
+ if (s_info.target_cnt <= 0)
+ return NULL;
+
+ stack = (unsigned long *)&ret;
+
+ if (s_info.stack_boundary) {
+ pthread_t tid;
+ unsigned long base;
+ unsigned long boundary;
+
+ tid = pthread_self();
+ if (!pthread_equal(tid, s_info.main_tid)) {
+ pthread_attr_t attr;
+ size_t size = 0;
+ base = 0;
+ boundary = 0;
+ if (!pthread_getattr_np(tid, &attr)) {
+ if (!pthread_attr_getstack(&attr, (void *)&base, &size))
+ boundary = base + size;
+ pthread_attr_destroy(&attr);
+ }
+ } else {
+ base = s_info.stack_base;
+ boundary = s_info.stack_boundary;
+ }
+
+ i = 0;
+ while ((unsigned long)stack >= base && (unsigned long)stack < boundary) {
+ i++;
+ if (s_info.debugger) {
+ DbgPrint("FP: %p, boundary: %p, INDEX: %d, ret: 0x%X\n",
+ stack, boundary, i, *stack);
+ }
+
+ target = find_target_by_addr(*stack++);
+ if (!target)
+ continue;
+
+ if (s_info.debugger)
+ DbgPrint("Target[%s]: %d\n", target->name, target->usage);
+
+ return target;
+ }
+ } else {
+ for (i = 0; i < s_info.dump_depth; i++) {
+ target = find_target_by_addr(*(stack++));
+ if (!target)
+ continue;
+
+ if (s_info.debugger)
+ DbgPrint("[%d] Target[%s]: %d\n", i, target->name, target->usage);
+
+ return target;
+ }
+ }
+
+ return NULL;
+}
+
+static void mcheck_cb(enum mcheck_status status)
+{
+ struct target *target;
+ switch (status) {
+ case MCHECK_DISABLED:
+ ErrPrint("mcheck is disabled\n");
+ break;
+ case MCHECK_OK:
+ ErrPrint("Consitency is ok\n");
+ break;
+ case MCHECK_HEAD:
+ target = find_target_info();
+ if (target)
+ ErrPrint("[HEAD] Inconsistency: %s\n", target->name);
+ break;
+ case MCHECK_TAIL:
+ target = find_target_info();
+ if (target)
+ ErrPrint("[HEAD] Inconsistency: %s\n", target->name);
+ break;
+ case MCHECK_FREE:
+ target = find_target_info();
+ if (target)
+ ErrPrint("[FREE] Inconsistency: %s\n", target->name);
+ break;
+ default:
+ break;
+ }
+}
+
+static inline int MPROBE(void *ptr)
+{
+ enum mcheck_status status;
+
+ status = mprobe(ptr);
+ if (status == MCHECK_DISABLED)
+ return 1;
+
+ if (status != MCHECK_OK) {
+ mcheck_cb(status);
+ return 0;
+ }
+
+ return 1;
+}
+
+static void *heap_monitor_malloc(size_t size, const void *caller)
+{
+ struct chunk *chunk;
+ void *ptr = NULL;
+
+ LOCK();
+ unhook();
+ ESTIMATE_START();
+ chunk = malloc(size + sizeof(*chunk));
+ if (chunk) {
+ chunk->info = find_target_info();
+ chunk->size = size;
+
+ ptr = chunk->data;
+ SET_PAD(ptr, 0);
+ SET_STATE(ptr, VALID);
+
+ if (chunk->info)
+ chunk->info->usage += size;
+ }
+
+ ESTIMATE_END();
+ hook();
+ UNLOCK();
+ return ptr;
+}
+
+static void heap_monitor_free(void *ptr, const void *caller)
+{
+ struct chunk *chunk;
+
+ if (!ptr)
+ return;
+
+ LOCK();
+ unhook();
+ ESTIMATE_START();
+
+ if (STATE(ptr) != VALID) {
+ DbgPrint("Unrecognizable chunk, do default operation\n");
+ chunk = ptr;
+ goto out;
+ }
+
+ chunk = container_of((void *)(((char *)ptr) - PAD(ptr)), struct chunk, data);
+ if (chunk->info)
+ chunk->info->usage -= chunk->size;
+
+ if (MPROBE(chunk)) {
+ SET_STATE(ptr, INVALID);
+ } else {
+ chunk = ptr;
+ if (MPROBE(chunk)) {
+ DbgPrint("Successfully recovered\n");
+ } else {
+ ErrPrint("Failed to recover\n");
+ chunk = NULL; /* Do nothing */
+ goto out;
+ }
+ }
+
+out:
+ free(chunk);
+ ESTIMATE_END();
+ hook();
+ UNLOCK();
+ return;
+}
+
+static void *heap_monitor_realloc(void *__ptr, size_t size, const void *caller)
+{
+ void *ptr = NULL;
+ struct chunk *chunk;
+
+ LOCK();
+ unhook();
+ ESTIMATE_START();
+ if (!__ptr) {
+ if (!size)
+ goto out;
+
+ /* Allocation */
+ chunk = realloc(__ptr, size + sizeof(*chunk));
+ if (chunk) {
+ chunk->info = find_target_info();
+ chunk->size = size;
+ ptr = chunk->data;
+
+ SET_PAD(ptr, 0);
+ SET_STATE(ptr, VALID);
+
+ if (chunk->info)
+ chunk->info->usage += size;
+ }
+ } else if (size == 0) {
+ /* Free */
+ if (STATE(__ptr) != VALID) {
+ DbgPrint("Unrecognizable chunk, do default operation\n");
+ ptr = realloc(__ptr, size);
+ } else {
+ chunk = container_of((void *)(((char *)__ptr) - PAD(__ptr)), struct chunk, data);
+ if (chunk->info)
+ chunk->info->usage -= chunk->size;
+
+ if (MPROBE(chunk)) {
+ SET_STATE(__ptr, INVALID);
+ } else {
+ chunk = __ptr;
+ if (MPROBE(chunk)) {
+ DbgPrint("Successfully recovered\n");
+ } else {
+ ErrPrint("Failed to recover\n");
+ ptr = NULL;
+ goto out;
+ }
+ }
+
+ ptr = realloc(chunk, size);
+ }
+ } else {
+ if (STATE(__ptr) != VALID) {
+ DbgPrint("Unrecognizable chunk, do default operation\n");
+ ptr = realloc(__ptr, size);
+ } else {
+ int pad = PAD(__ptr);
+
+ chunk = container_of((void *)(((char *)__ptr) - pad), struct chunk, data);
+ if (MPROBE(chunk)) {
+ ptr = realloc(chunk, size + sizeof(*chunk) + pad);
+ if (ptr) {
+ struct chunk *new_chunk = ptr;
+
+ if (new_chunk->info) {
+ new_chunk->info->usage -= new_chunk->size;
+ new_chunk->info->usage += size;
+ }
+ new_chunk->size = size;
+ ptr = new_chunk->data + pad;
+
+ SET_STATE(ptr, VALID);
+ SET_PAD(ptr, pad);
+ /* Consider this, do we need to keep the alignment for realloc? */
+ }
+ } else {
+ chunk = __ptr;
+ if (!MPROBE(chunk)) {
+ ErrPrint("Failed to recover\n");
+ ptr = NULL;
+ goto out;
+ }
+
+ ptr = realloc(chunk, size + sizeof(*chunk));
+ if (ptr) {
+ void *tmp;
+ struct chunk *new_chunk;
+
+ tmp = malloc(size);
+ if (!tmp) {
+ ErrPrint("Heap: %s\n", strerror(errno));
+ ptr = NULL;
+ goto out;
+ }
+
+ memcpy(tmp, ptr, size);
+ memcpy(((char *)ptr) + sizeof(*chunk), tmp, size);
+ free(tmp);
+
+ new_chunk = ptr;
+ new_chunk->info = find_target_info();
+ if (new_chunk->info)
+ new_chunk->info->usage += size;
+ new_chunk->size = size;
+ ptr = new_chunk->data;
+ SET_STATE(ptr, VALID);
+ SET_PAD(ptr, 0);
+
+ DbgPrint("Successfully recovered\n");
+ } else {
+ DbgPrint("Failed to recover\n");
+ }
+ }
+ }
+ }
+
+out:
+ ESTIMATE_END();
+ hook();
+ UNLOCK();
+ return ptr;
+}
+
+static void *heap_monitor_memalign(size_t align, size_t __size, const void *caller)
+{
+ void *ptr = NULL;
+ struct chunk *chunk;
+ int pad;
+ int size;
+
+ if (!__size)
+ return NULL;
+
+ LOCK();
+ unhook();
+ ESTIMATE_START();
+
+ pad = align - (sizeof(*chunk) % align);
+ size = sizeof(*chunk) + pad;
+ chunk = memalign(align, size + __size);
+ if (!chunk)
+ goto out;
+
+ chunk->info = find_target_info();
+ if (chunk->info)
+ chunk->info->usage += __size;
+
+ chunk->size = __size;
+
+ ptr = chunk->data + pad;
+ SET_PAD(ptr, pad);
+ SET_STATE(ptr, VALID);
+
+out:
+ ESTIMATE_END();
+ hook();
+ UNLOCK();
+ return ptr;
+}
+
+static void hook(void)
+{
+ s_info.hook++;
+ if (s_info.hook == 1) {
+ __malloc_hook = heap_monitor_malloc;
+ __realloc_hook = heap_monitor_realloc;
+ __memalign_hook = heap_monitor_memalign;
+ __free_hook = heap_monitor_free;
+ }
+}
+
+static void unhook(void)
+{
+ s_info.hook--;
+ if (s_info.hook == 0) {
+ __malloc_hook = s_info._malloc;
+ __realloc_hook = s_info._realloc;
+ __memalign_hook = s_info._memalign;
+ __free_hook = s_info._free;
+ }
+}
+
+void (*__malloc_initialize_hook)(void) = heap_monitor_init;
+
+static int iterator_cb(struct dl_phdr_info *info, size_t size, void *data)
+{
+ struct target *target;
+ register int i;
+ const ElfW(Phdr) *phdr;
+
+ target = data;
+
+ if (strcmp(info->dlpi_name, target->name))
+ return 0;
+
+ for (i = 0; i < info->dlpi_phnum; i++) {
+ phdr = info->dlpi_phdr + i;
+ if (phdr->p_type == PT_LOAD && (phdr->p_flags & PF_X)) {
+ target->begin = info->dlpi_addr + (unsigned long)phdr->p_vaddr;
+ target->end = target->begin + phdr->p_memsz;
+ if (s_info.debugger)
+ DbgPrint("Target: %s - [%s] 0x%lX - 0x%lX\n",
+ target->name, info->dlpi_name, target->begin, target->end);
+ break;
+ }
+ }
+
+ return 1;
+}
+
+API int heap_monitor_del_target(const char *name)
+{
+ struct dlist *l;
+ struct dlist *n;
+ struct target *target;
+ int ret;
+
+ LOCK();
+ unhook();
+ ret = -ENOENT;
+ dlist_foreach_safe(s_info.target_list, l, n, target) {
+ if (!strcmp(target->name, name)) {
+ s_info.target_list = dlist_remove(s_info.target_list, l);
+ free(target->name);
+ free(target);
+ s_info.target_cnt--;
+ ret = 0;
+ break;
+ }
+ }
+ hook();
+ UNLOCK();
+
+ return ret;
+}
+
+API int heap_monitor_add_target(const char *name)
+{
+ struct target *target;
+ int ret;
+
+ LOCK();
+ unhook();
+
+ ret = 0;
+ target = find_target_by_name(name);
+ if (target)
+ goto out;
+
+ target = malloc(sizeof(*target));
+ if (!target) {
+ DbgPrint("Heap: %s\n", strerror(errno));
+ ret = -ENOMEM;
+ goto out;
+ }
+
+ target->name = strdup(name);
+ if (!target->name) {
+ DbgPrint("Heap: %s\n", strerror(errno));
+ free(target);
+ ret = -ENOMEM;
+ goto out;
+ }
+
+ target->usage = 0;
+ target->begin = 0;
+ target->end = 0;
+
+ dl_iterate_phdr(iterator_cb, target);
+
+ s_info.target_cnt++;
+ s_info.target_list = dlist_append(s_info.target_list, target);
+out:
+ hook();
+ UNLOCK();
+ return ret;
+}
+
+API size_t heap_monitor_target_usage(const char *name)
+{
+ struct target *target;
+ LOCK();
+ unhook();
+ target = find_target_by_name(name);
+ hook();
+ UNLOCK();
+ return target ? target->usage : 0;
+}
+
+API int heap_monitor_initialized(void)
+{
+ return s_info.initialized;
+}
+
+API void heap_monitor_set_stack_boundary(unsigned long stack_boundary)
+{
+ s_info.stack_boundary = stack_boundary;
+}
+
+API void heap_monitor_init(void)
+{
+ const char *var;
+ pthread_attr_t attr;
+
+ if (s_info.initialized)
+ return;
+
+#if defined(_ENABLE_MCHECK)
+ s_info.m_check = mcheck(mcheck_cb);
+ if (s_info.m_check < 0)
+ ErrPrint("Failed to install mcheck[%d]\n", s_info.m_check);
+ else
+ DbgPrint("mcheck installed: %d\n", s_info.m_check);
+#endif
+
+ s_info._malloc = __malloc_hook;
+ s_info._realloc = __realloc_hook;
+ s_info._free = __free_hook;
+ s_info._memalign = __memalign_hook;
+
+ var = getenv("HEAP_MONITOR_DUMP_DEPTH");
+ if (var)
+ s_info.dump_depth = atoi(var);
+
+ var = getenv("HEAP_MONITOR_DEBUGGER");
+ if (var)
+ s_info.debugger = atoi(var);
+
+ s_info.main_tid = pthread_self();
+ s_info.initialized = 1;
+
+ if (pthread_getattr_np(s_info.main_tid, &attr))
+ return;
+
+ if (pthread_attr_getstack(&attr, (void *)&s_info.stack_base, &s_info.stack_size)) {
+ s_info.stack_base = 0;
+ s_info.stack_size = 0;
+ } else {
+ s_info.stack_boundary = s_info.stack_base + s_info.stack_size;
+ }
+
+ pthread_attr_destroy(&attr);
+ DbgPrint("Initialized\n");
+}
+
+API void heap_monitor_start(void)
+{
+ if (!s_info.initialized)
+ return;
+
+ hook();
+}
+
+API void heap_monitor_stop(void)
+{
+ if (!s_info.initialized)
+ return;
+
+ unhook();
+}
+
+/* End of a file */