Merge "perfetto: switch to being a C++17 only project"
diff --git a/test/cts/Android.bp b/test/cts/Android.bp
index 3eef756..1400a6e 100644
--- a/test/cts/Android.bp
+++ b/test/cts/Android.bp
@@ -17,9 +17,11 @@
     "reporter_test_cts.cc",
     "traced_perf_test_cts.cc",
     ":perfetto_protos_perfetto_config_cpp_gen",
+    ":perfetto_protos_perfetto_common_cpp_gen"
   ],
   generated_headers: [
     "perfetto_protos_perfetto_config_cpp_gen_headers",
+    "perfetto_protos_perfetto_common_cpp_gen_headers",
   ],
   static_libs: [
     "libgmock",
diff --git a/test/cts/BUILD.gn b/test/cts/BUILD.gn
index e821de8..9294cdb 100644
--- a/test/cts/BUILD.gn
+++ b/test/cts/BUILD.gn
@@ -26,6 +26,7 @@
     "../../gn:gtest_and_gmock",
     "../../include/perfetto/ext/tracing/core",
     "../../protos/perfetto/config:cpp",
+    "../../protos/perfetto/config/process_stats:cpp",
     "../../protos/perfetto/config/profiling:cpp",
     "../../protos/perfetto/trace:cpp",
     "../../protos/perfetto/trace/profiling:cpp",
diff --git a/test/cts/heapprofd_test_cts.cc b/test/cts/heapprofd_test_cts.cc
index 510bc7b..fb5e78f 100644
--- a/test/cts/heapprofd_test_cts.cc
+++ b/test/cts/heapprofd_test_cts.cc
@@ -28,6 +28,7 @@
 #include "test/gtest_and_gmock.h"
 #include "test/test_helper.h"
 
+#include "protos/perfetto/config/process_stats/process_stats_config.gen.h"
 #include "protos/perfetto/config/profiling/heapprofd_config.gen.h"
 #include "protos/perfetto/trace/profiling/profile_common.gen.h"
 #include "protos/perfetto/trace/profiling/profile_packet.gen.h"
@@ -210,9 +211,7 @@
   ASSERT_TRUE(found_alloc);
 }
 
-// Check that `packets` contain some allocations performed by
-// kJavaAllocActivity.
-void AssertExpectedArtAllocsPresent(
+void AssertHasSampledAllocs(
     const std::vector<protos::gen::TracePacket>& packets) {
   ASSERT_GT(packets.size(), 0u);
 
@@ -322,7 +321,7 @@
   std::string app_name = "android.perfetto.cts.app.debuggable";
   const auto& packets = ProfileRuntime(app_name, kJavaAllocActivity,
                                        /*heap_names=*/{"com.android.art"});
-  AssertExpectedArtAllocsPresent(packets);
+  AssertHasSampledAllocs(packets);
   StopApp(app_name);
 }
 
@@ -330,9 +329,60 @@
   std::string app_name = "android.perfetto.cts.app.debuggable";
   const auto& packets = ProfileStartup(app_name, kJavaAllocActivity,
                                        /*heap_names=*/{"com.android.art"});
-  AssertExpectedArtAllocsPresent(packets);
+  AssertHasSampledAllocs(packets);
   StopApp(app_name);
 }
 
+TEST(HeapprofdCtsTest, ProfilePlatformProcess) {
+  int target_pid = PidForProcessName("/system/bin/traced_probes");
+  ASSERT_GT(target_pid, 0) << "failed to find pid for target process";
+
+  // Construct config.
+  TraceConfig trace_config;
+  trace_config.add_buffers()->set_size_kb(20 * 1024);
+  trace_config.set_duration_ms(3000);
+  trace_config.set_data_source_stop_timeout_ms(8000);
+  trace_config.set_unique_session_name(RandomSessionName().c_str());
+
+  // process.stats to cause work in traced_probes
+  protos::gen::ProcessStatsConfig ps_config;
+  ps_config.set_proc_stats_poll_ms(100);
+  ps_config.set_record_thread_names(true);
+
+  auto* ds_config = trace_config.add_data_sources()->mutable_config();
+  ds_config->set_name("linux.process_stats");
+  ds_config->set_process_stats_config_raw(ps_config.SerializeAsString());
+
+  // profile native heap of traced_probes
+  protos::gen::HeapprofdConfig heapprofd_config;
+  heapprofd_config.set_sampling_interval_bytes(kTestSamplingInterval);
+  heapprofd_config.add_pid(static_cast<uint64_t>(target_pid));
+  heapprofd_config.set_block_client(true);
+
+  ds_config = trace_config.add_data_sources()->mutable_config();
+  ds_config->set_name("android.heapprofd");
+  ds_config->set_heapprofd_config_raw(heapprofd_config.SerializeAsString());
+
+  // Collect trace.
+  base::TestTaskRunner task_runner;
+  TestHelper helper(&task_runner);
+  helper.ConnectConsumer();
+  helper.WaitForConsumerConnect();
+
+  helper.StartTracing(trace_config);
+  helper.WaitForTracingDisabled(15000 /*ms*/);
+  helper.ReadData();
+  helper.WaitForReadData();
+  auto packets = helper.trace();
+
+  int target_pid_after = PidForProcessName("/system/bin/traced_probes");
+  ASSERT_EQ(target_pid, target_pid_after) << "traced_probes died during test";
+
+  if (IsUserBuild())
+    AssertNoProfileContents(packets);
+  else
+    AssertHasSampledAllocs(packets);
+}
+
 }  // namespace
 }  // namespace perfetto
diff --git a/test/cts/traced_perf_test_cts.cc b/test/cts/traced_perf_test_cts.cc
index d7bd60e..aaa2178 100644
--- a/test/cts/traced_perf_test_cts.cc
+++ b/test/cts/traced_perf_test_cts.cc
@@ -27,6 +27,8 @@
 #include "test/gtest_and_gmock.h"
 #include "test/test_helper.h"
 
+#include "protos/perfetto/common/perf_events.gen.h"
+#include "protos/perfetto/config/process_stats/process_stats_config.gen.h"
 #include "protos/perfetto/config/profiling/perf_event_config.gen.h"
 #include "protos/perfetto/trace/profiling/profile_common.gen.h"
 #include "protos/perfetto/trace/profiling/profile_packet.gen.h"
@@ -54,6 +56,20 @@
   return result;
 }
 
+std::vector<protos::gen::TracePacket> CollectTrace(
+    base::TestTaskRunner* task_runner,
+    const TraceConfig& trace_config) {
+  TestHelper helper(task_runner);
+  helper.ConnectConsumer();
+  helper.WaitForConsumerConnect();
+
+  helper.StartTracing(trace_config);
+  helper.WaitForTracingDisabled(15000 /*ms*/);
+  helper.ReadData();
+  helper.WaitForReadData();
+  return helper.trace();
+}
+
 std::vector<protos::gen::TracePacket> ProfileSystemWide(std::string app_name) {
   base::TestTaskRunner task_runner;
 
@@ -67,11 +83,7 @@
                    /*delay_ms=*/100);
   task_runner.RunUntilCheckpoint("target.app.running", 10000 /*ms*/);
 
-  // set up tracing
-  TestHelper helper(&task_runner);
-  helper.ConnectConsumer();
-  helper.WaitForConsumerConnect();
-
+  // build config
   TraceConfig trace_config;
   trace_config.add_buffers()->set_size_kb(20 * 1024);
   trace_config.set_duration_ms(3000);
@@ -83,18 +95,11 @@
   ds_config->set_target_buffer(0);
 
   protos::gen::PerfEventConfig perf_config;
-
   perf_config.set_all_cpus(true);
   perf_config.set_sampling_frequency(10);  // Hz
   ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());
 
-  // start tracing
-  helper.StartTracing(trace_config);
-  helper.WaitForTracingDisabled(15000 /*ms*/);
-  helper.ReadData();
-  helper.WaitForReadData();
-
-  return helper.trace();
+  return CollectTrace(&task_runner, trace_config);
 }
 
 void AssertHasSampledStacksForPid(std::vector<protos::gen::TracePacket> packets,
@@ -216,5 +221,55 @@
   StopApp(app_name);
 }
 
+// Loads a platform process with work (we use traced_probes which runs as
+// AID_NOBODY), and profiles it.
+TEST(TracedPerfCtsTest, ProfilePlatformProcess) {
+  if (!HasPerfLsmHooks())
+    GTEST_SKIP() << "skipped due to lack of perf_event_open LSM hooks";
+
+  int target_pid = PidForProcessName("/system/bin/traced_probes");
+  ASSERT_GT(target_pid, 0) << "failed to find pid for target process";
+
+  // Construct config.
+  TraceConfig trace_config;
+  trace_config.add_buffers()->set_size_kb(20 * 1024);
+  trace_config.set_duration_ms(3000);
+  trace_config.set_data_source_stop_timeout_ms(8000);
+  trace_config.set_unique_session_name(RandomSessionName().c_str());
+
+  // process.stats to cause work in traced_probes
+  protos::gen::ProcessStatsConfig ps_config;
+  ps_config.set_proc_stats_poll_ms(100);
+  ps_config.set_record_thread_names(true);
+
+  auto* ds_config = trace_config.add_data_sources()->mutable_config();
+  ds_config->set_name("linux.process_stats");
+  ds_config->set_process_stats_config_raw(ps_config.SerializeAsString());
+
+  // profile traced_probes
+  protos::gen::PerfEventConfig perf_config;
+  auto* timebase = perf_config.mutable_timebase();
+  timebase->set_frequency(100);
+  auto* callstacks = perf_config.mutable_callstack_sampling();
+  auto* scope = callstacks->mutable_scope();
+  scope->add_target_pid(target_pid);
+
+  ds_config = trace_config.add_data_sources()->mutable_config();
+  ds_config->set_name("linux.perf");
+  ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());
+
+  // Collect trace.
+  base::TestTaskRunner task_runner;
+  auto packets = CollectTrace(&task_runner, trace_config);
+
+  int target_pid_after = PidForProcessName("/system/bin/traced_probes");
+  ASSERT_EQ(target_pid, target_pid_after) << "traced_probes died during test";
+
+  if (!IsUserBuild())
+    AssertHasSampledStacksForPid(packets, target_pid);
+  else
+    AssertNoStacksForPid(packets, target_pid);
+}
+
 }  // namespace
 }  // namespace perfetto
diff --git a/ui/src/assets/perfetto.scss b/ui/src/assets/perfetto.scss
index c6d03b4..820ee59 100644
--- a/ui/src/assets/perfetto.scss
+++ b/ui/src/assets/perfetto.scss
@@ -25,3 +25,4 @@
 @import "trace_info_page";
 @import "flags_page";
 @import "hiring_banner";
+@import "widgets/button";
diff --git a/ui/src/assets/widgets/button.scss b/ui/src/assets/widgets/button.scss
new file mode 100644
index 0000000..4ab5b55
--- /dev/null
+++ b/ui/src/assets/widgets/button.scss
@@ -0,0 +1,90 @@
+// Copyright (C) 2023 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
+//
+// 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.
+
+@import "theme";
+
+.pf-button {
+  font-family: $pf-font;
+  line-height: 1;
+  user-select: none;
+  color: $pf-primary-foreground;
+  background: $pf-primary-background;
+  transition: background $pf-anim-timing, box-shadow $pf-anim-timing;
+  border-radius: $pf-border-radius;
+  padding: 4px 8px;
+
+  & > .material-icons {
+    font-size: inherit;
+    line-height: inherit;
+    float: left;
+    margin-right: 4px; // Make some room between the icon and label
+  }
+
+  &:hover {
+    background: $pf-primary-background-hover;
+  }
+
+  &:active,
+  &.pf-active {
+    transition: none;
+    background: $pf-primary-background-active;
+    box-shadow: inset 1px 1px 4px #00000040;
+  }
+
+  &[disabled] {
+    background: $pf-primary-background-disabled;
+    color: $pf-primary-foreground-disabled;
+    box-shadow: none;
+    cursor: not-allowed;
+  }
+
+  // Remove default background in minimal mode, showing only the text
+  &.pf-minimal {
+    background: $pf-minimal-background;
+    color: $pf-minimal-foreground;
+
+    &:hover {
+      background: $pf-minimal-background-hover;
+    }
+
+    &:active,
+    &.pf-active {
+      background: $pf-minimal-background-active;
+    }
+
+    &[disabled] {
+      color: $pf-minimal-foreground-disabled;
+      background: $pf-minimal-background-disabled;
+      cursor: not-allowed;
+    }
+  }
+
+  // Reduce padding when compact
+  &.pf-compact {
+    padding: 2px 4px;
+  }
+
+  // Reduce padding when we are icon-only
+  &.pf-icon-only {
+    & > i {
+      margin: 0;
+    }
+
+    padding: 4px 4px;
+
+    &.pf-compact {
+      padding: 0;
+    }
+  }
+}
diff --git a/ui/src/assets/widgets/theme.scss b/ui/src/assets/widgets/theme.scss
new file mode 100644
index 0000000..38d9107
--- /dev/null
+++ b/ui/src/assets/widgets/theme.scss
@@ -0,0 +1,41 @@
+// Copyright (C) 2023 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
+//
+// 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.
+
+// Standard theme settings for widgets
+
+$pf-font: "Roboto Condensed", sans-serif;
+$pf-border-radius: 3px;
+$pf-anim-timing: 250ms cubic-bezier(0.4, 0, 0.2, 1);
+
+// Here we describe two colour schemes: primary and minimal
+// It is assumed widgets exist on a light background
+// Primary is to be used for things like buttons and checkboxes
+// Minimal is to be used for things like inputs and labels
+// Some controls (i.e. checkboxes) may mix and match both in the same widget.
+// Other controls might use the primary scheme by default, but have a minimal
+// configuration which makes them use the minimal colour scheme.
+
+$pf-primary-foreground: #fff;
+$pf-primary-foreground-disabled: #aaa;
+$pf-primary-background: #3d5688;
+$pf-primary-background-hover: #4966a2;
+$pf-primary-background-active: #243e71;
+$pf-primary-background-disabled: #666;
+
+$pf-minimal-foreground: #19212b;
+$pf-minimal-foreground-disabled: #aaa;
+$pf-minimal-background: none;
+$pf-minimal-background-hover: #0001;
+$pf-minimal-background-active: #0002;
+$pf-minimal-background-disabled: none;
diff --git a/ui/src/frontend/classnames.ts b/ui/src/frontend/classnames.ts
new file mode 100644
index 0000000..b2f6007
--- /dev/null
+++ b/ui/src/frontend/classnames.ts
@@ -0,0 +1,25 @@
+// Copyright (C) 2023 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
+//
+// 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.
+
+// It's common to want to have a class depending on a boolean flag, in which
+// case we use `flag && className` which evaluates to either false or a string,
+// which is why false is included in definition of ArgType.
+type ArgType = string|false|undefined|ArgType[];
+
+// Join class names together into valid HTML class attributes
+// Falsey elements are ignored
+// Nested arrays are flattened
+export function classNames(...args: ArgType[]): string {
+  return args.flat().filter((x) => x).join(' ');
+}
diff --git a/ui/src/frontend/classnames_unittest.ts b/ui/src/frontend/classnames_unittest.ts
new file mode 100644
index 0000000..29546db
--- /dev/null
+++ b/ui/src/frontend/classnames_unittest.ts
@@ -0,0 +1,46 @@
+// Copyright (C) 2023 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
+//
+// 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.
+
+import {classNames} from './classnames';
+
+test('classnames', () => {
+  expect(classNames('foo', 'bar')).toEqual('foo bar');
+  expect(classNames('foo', '', 'bar')).toEqual('foo bar');
+  expect(classNames(false, 'foo', 'bar')).toEqual('foo bar');
+  expect(classNames(undefined, 'foo', 'bar')).toEqual('foo bar');
+  expect(classNames('foo', 'bar', ['baz', 'qux'])).toEqual('foo bar baz qux');
+  expect(classNames('foo bar', 'baz')).toEqual('foo bar baz');
+});
+
+test('example usecase with flags', () => {
+  const foo = true;
+  const bar = false;
+  const baz = true;
+  expect(classNames(
+             foo && 'foo',
+             bar && 'bar',
+             baz && 'baz',
+             ))
+      .toEqual('foo baz');
+});
+
+test('example usecase with possibly undefined classnames', () => {
+  let fooClass: string|undefined;
+  const barClass = 'bar';
+  expect(classNames(
+             fooClass,
+             barClass,
+             ))
+      .toEqual('bar');
+});
diff --git a/ui/src/frontend/widgets/button.ts b/ui/src/frontend/widgets/button.ts
new file mode 100644
index 0000000..2e6f3d6
--- /dev/null
+++ b/ui/src/frontend/widgets/button.ts
@@ -0,0 +1,83 @@
+// Copyright (C) 2023 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
+//
+// 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.
+
+import * as m from 'mithril';
+import {classNames} from '../classnames';
+
+interface CommonAttrs {
+  // Always show the button as if the "active" pseudo class were applied, which
+  // makes the button look permanently pressed.
+  // Useful for when the button represents some toggleable state, such as
+  // showing/hiding a popup menu.
+  // Defaults to false.
+  active?: boolean;
+  // Use minimal padding, reducing the overall size of the button by a few px.
+  // Defaults to false.
+  compact?: boolean;
+  // Reduces button decorations.
+  // Defaults to false.
+  minimal?: boolean;
+  // Make the button appear greyed out block any interaction with it. No events
+  // will be fired.
+  // Defaults to false.
+  disabled?: boolean;
+  // Remaining attributes forwarded to the underlying HTML <button>.
+  [htmlAttrs: string]: any;
+}
+
+interface IconButtonAttrs extends CommonAttrs {
+  // Icon buttons require an icon.
+  icon: string;
+}
+
+interface LabelButtonAttrs extends CommonAttrs {
+  // Label buttons require a label.
+  label: string;
+  // Label buttons can have an optional icon.
+  icon?: string;
+}
+
+export type ButtonAttrs = LabelButtonAttrs|IconButtonAttrs;
+
+export class Button implements m.ClassComponent<ButtonAttrs> {
+  view({attrs}: m.CVnode<ButtonAttrs>) {
+    const {
+      label,
+      icon,
+      active = false,
+      compact = false,
+      minimal = false,
+      disabled = false,
+      ...htmlAttrs
+    } = attrs;
+
+    const classes = classNames(
+        'pf-button',
+        active && 'pf-active',
+        compact && 'pf-compact',
+        minimal && 'pf-minimal',
+        (icon && !label) && 'pf-icon-only',
+    );
+
+    return m(
+        'button' + (disabled ? '[disabled]' : ''),
+        {
+          class: classes,
+          ...htmlAttrs,
+        },
+        icon && m('i.material-icons', icon),
+        label || '\u200B',  // Zero width space keeps button in-flow
+    );
+  }
+}