1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325

base / android / native_uma_recorder.cc [blame]

// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/android/callback_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/format_macros.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/sparse_histogram.h"
#include "base/metrics/statistics_recorder.h"
#include "base/metrics/user_metrics.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "build/robolectric_buildflags.h"

// Must come after all headers that specialize FromJniType() / ToJniType().
#if BUILDFLAG(IS_ROBOLECTRIC)
#include "base/base_robolectric_jni/NativeUmaRecorder_jni.h"  // nogncheck
#else
#include "base/metrics_jni/NativeUmaRecorder_jni.h"
#endif

namespace base {
namespace android {

namespace {

using HistogramsSnapshot =
    std::map<std::string, std::unique_ptr<HistogramSamples>>;

std::string HistogramConstructionParamsToString(HistogramBase* histogram) {
  std::string params_str = histogram->histogram_name();
  switch (histogram->GetHistogramType()) {
    case HISTOGRAM:
    case LINEAR_HISTOGRAM:
    case BOOLEAN_HISTOGRAM:
    case CUSTOM_HISTOGRAM: {
      Histogram* hist = static_cast<Histogram*>(histogram);
      params_str += StringPrintf("/%d/%d/%" PRIuS, hist->declared_min(),
                                 hist->declared_max(), hist->bucket_count());
      break;
    }
    case SPARSE_HISTOGRAM:
    case DUMMY_HISTOGRAM:
      break;
  }
  return params_str;
}

// Convert a jlong |histogram_hint| from Java to a HistogramBase* via a cast.
// The Java side caches these in a map (see NativeUmaRecorder.java), which is
// safe to do since C++ Histogram objects are never freed.
static HistogramBase* HistogramFromHint(jlong j_histogram_hint) {
  return reinterpret_cast<HistogramBase*>(j_histogram_hint);
}

void CheckHistogramArgs(JNIEnv* env,
                        std::string& histogram_name,
                        int32_t expected_min,
                        int32_t expected_max,
                        size_t expected_bucket_count,
                        HistogramBase* histogram) {
  bool valid_arguments = Histogram::InspectConstructionArguments(
      histogram_name, &expected_min, &expected_max, &expected_bucket_count);
  DCHECK(valid_arguments);
  DCHECK(histogram->HasConstructionArguments(expected_min, expected_max,
                                             expected_bucket_count))
      << histogram_name << "/" << expected_min << "/" << expected_max << "/"
      << expected_bucket_count << " vs. "
      << HistogramConstructionParamsToString(histogram);
}

HistogramBase* BooleanHistogram(JNIEnv* env,
                                std::string& histogram_name,
                                jlong j_histogram_hint) {
  HistogramBase* histogram = HistogramFromHint(j_histogram_hint);
  if (histogram)
    return histogram;

  histogram = BooleanHistogram::FactoryGet(
      histogram_name, HistogramBase::kUmaTargetedHistogramFlag);
  return histogram;
}

HistogramBase* ExponentialHistogram(JNIEnv* env,
                                    std::string& histogram_name,
                                    jlong j_histogram_hint,
                                    jint j_min,
                                    jint j_max,
                                    jint j_num_buckets) {
  int32_t min = static_cast<int32_t>(j_min);
  int32_t max = static_cast<int32_t>(j_max);
  size_t num_buckets = static_cast<size_t>(j_num_buckets);
  HistogramBase* histogram = HistogramFromHint(j_histogram_hint);
  if (histogram) {
    CheckHistogramArgs(env, histogram_name, min, max, num_buckets, histogram);
    return histogram;
  }

  DCHECK_GE(min, 1) << "The min expected sample must be >= 1";

  histogram = Histogram::FactoryGet(histogram_name, min, max, num_buckets,
                                    HistogramBase::kUmaTargetedHistogramFlag);
  return histogram;
}

HistogramBase* LinearHistogram(JNIEnv* env,
                               std::string& j_histogram_name,
                               jlong j_histogram_hint,
                               jint j_min,
                               jint j_max,
                               jint j_num_buckets) {
  int32_t min = static_cast<int32_t>(j_min);
  int32_t max = static_cast<int32_t>(j_max);
  size_t num_buckets = static_cast<size_t>(j_num_buckets);
  HistogramBase* histogram = HistogramFromHint(j_histogram_hint);
  if (histogram) {
    CheckHistogramArgs(env, j_histogram_name, min, max, num_buckets, histogram);
    return histogram;
  }

  std::string histogram_name = j_histogram_name;
  histogram =
      LinearHistogram::FactoryGet(histogram_name, min, max, num_buckets,
                                  HistogramBase::kUmaTargetedHistogramFlag);
  return histogram;
}

HistogramBase* SparseHistogram(JNIEnv* env,
                               std::string& histogram_name,
                               jlong j_histogram_hint) {
  HistogramBase* histogram = HistogramFromHint(j_histogram_hint);
  if (histogram)
    return histogram;

  histogram = SparseHistogram::FactoryGet(
      histogram_name, HistogramBase::kUmaTargetedHistogramFlag);
  return histogram;
}

struct ActionCallbackWrapper {
  base::ActionCallback action_callback;
};

static void OnActionRecorded(const JavaRef<jobject>& callback,
                             const std::string& action,
                             TimeTicks action_time) {
  RunStringCallbackAndroid(callback, action);
}

}  // namespace

jlong JNI_NativeUmaRecorder_RecordBooleanHistogram(
    JNIEnv* env,
    std::string& j_histogram_name,
    jlong j_histogram_hint,
    jboolean j_sample) {
  bool sample = static_cast<bool>(j_sample);
  HistogramBase* histogram =
      BooleanHistogram(env, j_histogram_name, j_histogram_hint);
  histogram->AddBoolean(sample);
  return reinterpret_cast<jlong>(histogram);
}

jlong JNI_NativeUmaRecorder_RecordExponentialHistogram(
    JNIEnv* env,
    std::string& j_histogram_name,
    jlong j_histogram_hint,
    jint j_sample,
    jint j_min,
    jint j_max,
    jint j_num_buckets) {
  int sample = static_cast<int>(j_sample);
  HistogramBase* histogram = ExponentialHistogram(
      env, j_histogram_name, j_histogram_hint, j_min, j_max, j_num_buckets);
  histogram->Add(sample);
  return reinterpret_cast<jlong>(histogram);
}

jlong JNI_NativeUmaRecorder_RecordLinearHistogram(JNIEnv* env,
                                                  std::string& j_histogram_name,
                                                  jlong j_histogram_hint,
                                                  jint j_sample,
                                                  jint j_min,
                                                  jint j_max,
                                                  jint j_num_buckets) {
  int sample = static_cast<int>(j_sample);
  HistogramBase* histogram = LinearHistogram(
      env, j_histogram_name, j_histogram_hint, j_min, j_max, j_num_buckets);
  histogram->Add(sample);
  return reinterpret_cast<jlong>(histogram);
}

jlong JNI_NativeUmaRecorder_RecordSparseHistogram(JNIEnv* env,
                                                  std::string& j_histogram_name,
                                                  jlong j_histogram_hint,
                                                  jint j_sample) {
  int sample = static_cast<int>(j_sample);
  HistogramBase* histogram =
      SparseHistogram(env, j_histogram_name, j_histogram_hint);
  histogram->Add(sample);
  return reinterpret_cast<jlong>(histogram);
}

void JNI_NativeUmaRecorder_RecordUserAction(JNIEnv* env,
                                            std::string& user_action_name,
                                            jlong j_millis_since_event) {
  // Time values coming from Java need to be synchronized with TimeTick clock.
  RecordComputedActionSince(user_action_name,
                            Milliseconds(j_millis_since_event));
}

// This backs a Java test util for testing histograms -
// MetricsUtils.HistogramDelta. It should live in a test-specific file, but we
// currently can't have test-specific native code packaged in test-specific Java
// targets - see http://crbug.com/415945.
jint JNI_NativeUmaRecorder_GetHistogramValueCountForTesting(
    JNIEnv* env,
    std::string& name,
    jint sample,
    jlong snapshot_ptr) {
  HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
  if (histogram == nullptr) {
    // No samples have been recorded for this histogram (yet?).
    return 0;
  }

  int actual_count = histogram->SnapshotSamples()->GetCount(sample);
  if (snapshot_ptr) {
    auto* snapshot = reinterpret_cast<HistogramsSnapshot*>(snapshot_ptr);
    auto snapshot_data = snapshot->find(name);
    if (snapshot_data != snapshot->end())
      actual_count -= snapshot_data->second->GetCount(sample);
  }

  return actual_count;
}

jint JNI_NativeUmaRecorder_GetHistogramTotalCountForTesting(
    JNIEnv* env,
    std::string& name,
    jlong snapshot_ptr) {
  HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
  if (histogram == nullptr) {
    // No samples have been recorded for this histogram.
    return 0;
  }

  int actual_count = histogram->SnapshotSamples()->TotalCount();
  if (snapshot_ptr) {
    auto* snapshot = reinterpret_cast<HistogramsSnapshot*>(snapshot_ptr);
    auto snapshot_data = snapshot->find(name);
    if (snapshot_data != snapshot->end())
      actual_count -= snapshot_data->second->TotalCount();
  }
  return actual_count;
}

// Returns an array with 3 entries for each bucket, representing (min, max,
// count).
ScopedJavaLocalRef<jlongArray>
JNI_NativeUmaRecorder_GetHistogramSamplesForTesting(JNIEnv* env,
                                                    std::string& name) {
  HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
  std::vector<int64_t> buckets;

  if (histogram == nullptr) {
    // No samples have been recorded for this histogram.
    return base::android::ToJavaLongArray(env, buckets);
  }

  std::unique_ptr<HistogramSamples> samples = histogram->SnapshotSamples();
  for (auto sampleCountIterator = samples->Iterator();
       !sampleCountIterator->Done(); sampleCountIterator->Next()) {
    HistogramBase::Sample min;
    int64_t max;
    HistogramBase::Count count;
    sampleCountIterator->Get(&min, &max, &count);
    buckets.push_back(min);
    buckets.push_back(max);
    buckets.push_back(count);
  }

  return base::android::ToJavaLongArray(env, buckets);
}

jlong JNI_NativeUmaRecorder_CreateHistogramSnapshotForTesting(JNIEnv* env) {
  HistogramsSnapshot* snapshot = new HistogramsSnapshot();
  for (const auto* const histogram : StatisticsRecorder::GetHistograms()) {
    (*snapshot)[histogram->histogram_name()] = histogram->SnapshotSamples();
  }
  return reinterpret_cast<intptr_t>(snapshot);
}

void JNI_NativeUmaRecorder_DestroyHistogramSnapshotForTesting(
    JNIEnv* env,
    jlong snapshot_ptr) {
  delete reinterpret_cast<HistogramsSnapshot*>(snapshot_ptr);
}

static jlong JNI_NativeUmaRecorder_AddActionCallbackForTesting(
    JNIEnv* env,
    const JavaParamRef<jobject>& callback) {
  // Create a wrapper for the ActionCallback, so it can life on the heap until
  // RemoveActionCallbackForTesting() is called.
  auto* wrapper = new ActionCallbackWrapper{base::BindRepeating(
      &OnActionRecorded, ScopedJavaGlobalRef<jobject>(env, callback))};
  base::AddActionCallback(wrapper->action_callback);
  return reinterpret_cast<intptr_t>(wrapper);
}

static void JNI_NativeUmaRecorder_RemoveActionCallbackForTesting(
    JNIEnv* env,
    jlong callback_id) {
  DCHECK(callback_id);
  auto* wrapper = reinterpret_cast<ActionCallbackWrapper*>(callback_id);
  base::RemoveActionCallback(wrapper->action_callback);
  delete wrapper;
}

}  // namespace android
}  // namespace base