| 1 | //===-- MemoryMonitorMacOSX.mm --------------------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "lldb/Host/MemoryMonitor.h" |
| 10 | #include <cassert> |
| 11 | #include <dispatch/dispatch.h> |
| 12 | |
| 13 | using namespace lldb_private; |
| 14 | |
| 15 | class MemoryMonitorMacOSX : public MemoryMonitor { |
| 16 | using MemoryMonitor::MemoryMonitor; |
| 17 | void Start() override { |
| 18 | m_memory_pressure_source = dispatch_source_create( |
| 19 | DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, 0, |
| 20 | DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_CRITICAL, |
| 21 | dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); |
| 22 | |
| 23 | if (!m_memory_pressure_source) |
| 24 | return; |
| 25 | |
| 26 | dispatch_source_set_event_handler(m_memory_pressure_source, ^{ |
| 27 | dispatch_source_memorypressure_flags_t pressureLevel = |
| 28 | dispatch_source_get_data(m_memory_pressure_source); |
| 29 | if (pressureLevel & |
| 30 | (DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_CRITICAL)) { |
| 31 | m_callback(); |
| 32 | } |
| 33 | }); |
| 34 | dispatch_activate(m_memory_pressure_source); |
| 35 | } |
| 36 | |
| 37 | void Stop() override { |
| 38 | if (m_memory_pressure_source) { |
| 39 | dispatch_source_cancel(m_memory_pressure_source); |
| 40 | dispatch_release(m_memory_pressure_source); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | private: |
| 45 | dispatch_source_t m_memory_pressure_source; |
| 46 | }; |
| 47 | |
| 48 | std::unique_ptr<MemoryMonitor> MemoryMonitor::Create(Callback callback) { |
| 49 | return std::make_unique<MemoryMonitorMacOSX>(args&: callback); |
| 50 | } |
| 51 | |