1 /*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 /*
17 * Common string pool for the profiler
18 */
19 #include "Hprof.h"
20
21 static HashTable *gStringHashTable;
22
23 int
hprofStartup_String()24 hprofStartup_String()
25 {
26 gStringHashTable = dvmHashTableCreate(512, free);
27 if (gStringHashTable == NULL) {
28 return UNIQUE_ERROR();
29 }
30 return 0;
31 }
32
33 int
hprofShutdown_String()34 hprofShutdown_String()
35 {
36 dvmHashTableFree(gStringHashTable);
37 return 0;
38 }
39
40 static u4
computeUtf8Hash(const char * str)41 computeUtf8Hash(const char *str)
42 {
43 u4 hash = 0;
44 const char *cp;
45 char c;
46
47 cp = str;
48 while ((c = *cp++) != '\0') {
49 hash = hash * 31 + c;
50 }
51
52 return hash;
53 }
54
55 hprof_string_id
hprofLookupStringId(const char * str)56 hprofLookupStringId(const char *str)
57 {
58 void *val;
59 u4 hashValue;
60
61 dvmHashTableLock(gStringHashTable);
62
63 hashValue = computeUtf8Hash(str);
64 val = dvmHashTableLookup(gStringHashTable, hashValue, (void *)str,
65 (HashCompareFunc)strcmp, false);
66 if (val == NULL) {
67 const char *newStr;
68
69 newStr = strdup(str);
70 val = dvmHashTableLookup(gStringHashTable, hashValue, (void *)newStr,
71 (HashCompareFunc)strcmp, true);
72 assert(val != NULL);
73 }
74
75 dvmHashTableUnlock(gStringHashTable);
76
77 return (hprof_string_id)val;
78 }
79
80 int
hprofDumpStrings(hprof_context_t * ctx)81 hprofDumpStrings(hprof_context_t *ctx)
82 {
83 HashIter iter;
84 hprof_record_t *rec = &ctx->curRec;
85 int err;
86
87 dvmHashTableLock(gStringHashTable);
88
89 for (err = 0, dvmHashIterBegin(gStringHashTable, &iter);
90 err == 0 && !dvmHashIterDone(&iter);
91 dvmHashIterNext(&iter))
92 {
93 err = hprofStartNewRecord(ctx, HPROF_TAG_STRING, HPROF_TIME);
94 if (err == 0) {
95 const char *str;
96
97 str = (const char *)dvmHashIterData(&iter);
98 assert(str != NULL);
99
100 /* STRING format:
101 *
102 * ID: ID for this string
103 * [u1]*: UTF8 characters for string (NOT NULL terminated)
104 * (the record format encodes the length)
105 *
106 * We use the address of the string data as its ID.
107 */
108 err = hprofAddU4ToRecord(rec, (u4)str);
109 if (err == 0) {
110 err = hprofAddUtf8StringToRecord(rec, str);
111 }
112 }
113 }
114
115 dvmHashTableUnlock(gStringHashTable);
116
117 return err;
118 }
119