diff --git a/plugins/AgentTools/agenttools.h b/plugins/AgentTools/agenttools.h index d58ee5164..4b3c25cfd 100644 --- a/plugins/AgentTools/agenttools.h +++ b/plugins/AgentTools/agenttools.h @@ -172,6 +172,7 @@ typedef enum _AT_ACTION AtActionGetCpuInfo, AtActionGetHardwareSensors, AtActionGetHardwareReport, + AtActionGetHardwareSensorHistory, AtActionListLogonSessions, AtActionListTerminalSessions, AtActionLookupAccount, diff --git a/plugins/AgentTools/schema.c b/plugins/AgentTools/schema.c index 582eb9e85..612d2365c 100644 --- a/plugins/AgentTools/schema.c +++ b/plugins/AgentTools/schema.c @@ -403,6 +403,10 @@ CONST AT_ACTION_INFO AtActionInfo[AtActionMaximum] = AtActionGetHardwareReport, AtTierSensitiveRead, AtConsentClassNone, AtTargetNone, 0, SETTING_NAME_TOOL_CONFIRM(L"get_hardware_report"), L"create the hardware report", L"Allow creating the hardware report", L"get_hardware_report" }, + { + AtActionGetHardwareSensorHistory, AtTierRead, AtConsentClassNone, AtTargetNone, 0, SETTING_NAME_TOOL_CONFIRM(L"get_hardware_sensor_history"), + L"read the history of the hardware sensors", L"Allow reading hardware sensor history", L"get_hardware_sensor_history" + }, { AtActionListLogonSessions, AtTierSensitiveRead, AtConsentClassNone, AtTargetNone, 0, SETTING_NAME_TOOL_CONFIRM(L"list_logon_sessions"), L"list who is logged on", L"List the logon sessions", L"list_logon_sessions" @@ -4331,6 +4335,75 @@ CONST AT_TOOL AtTools[] = "},\"required\":[\"report\"]}," AT_ANNOTATIONS("Get hardware report", AT_READ_HINTS) "}" }, + { + "get_hardware_sensor_history", L"Get hardware sensor history", AtTierRead, AtActionGetHardwareSensorHistory, + SETTING_NAME_TOOL_ACCESS(L"get_hardware_sensor_history"), SETTING_NAME_TOOL_CONFIRM(L"get_hardware_sensor_history"), + "{\"name\":\"get_hardware_sensor_history\",\"title\":\"Get hardware sensor history\"," + "\"description\":\"What the hardware sensors read over time: per sensor, the average, minimum, maximum " + "and last reading over a window, and optionally every sample. System Informer records every sensor " + "for as long as it has run, whether or not its Hardware sensors window is open, up to history_slots " + "samples of update_interval_ms each. Pass ids from get_hardware_sensors to read particular sensors; " + "ids change when System Informer restarts or a plugin source re-registers, so fetch them again from " + "get_hardware_sensors rather than keeping them. A sensor that disappeared, for example because its " + "driver was unloaded, is still returned by id with listed false. For throttling, throttle counts how " + "many samples each reason held the processor back. Sample times have one-second resolution. To find " + "what caused a spike, pair the sample times with get_system_history's max_cpu_pid. " + AT_PAGE_NOTE AT_SNAPSHOT_NOTE "\"," + "\"inputSchema\":{\"type\":\"object\",\"properties\":{" + "\"ids\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"Sensor ids from get_hardware_sensors, returned in this order; the filters are ignored when given\"}," + "\"component\":{\"type\":\"string\",\"enum\":[\"cpu\",\"memory\",\"chipset\",\"system\",\"windows\",\"source\"],\"description\":\"Only rows of this kind of component\"}," + "\"group\":{\"type\":\"string\",\"enum\":[\"temperatures\",\"powers\",\"limits\",\"clocks\",\"bandwidth\",\"active_clocks\",\"multipliers\",\"voltages\",\"currents\",\"residency\",\"fans\",\"controls\",\"throttling\"],\"description\":\"Only rows of this group\"}," + "\"name_contains\":{\"type\":\"string\",\"description\":\"Only rows whose sensor or component name contains this, case-insensitive\"}," + "\"window_seconds\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"How far back to look; default 60, capped by the history\"}," + "\"include_samples\":{\"type\":\"boolean\",\"description\":\"Also return every sample in the window\"}," + AT_PAGE_INPUT_PROPERTIES + "},\"additionalProperties\":false}," + "\"outputSchema\":{\"type\":\"object\",\"properties\":{" + "\"update_interval_ms\":{\"type\":\"integer\",\"description\":\"Time between samples\"}," + "\"history_slots\":{\"type\":\"integer\",\"description\":\"How many samples each sensor's history holds\"}," + "\"window_seconds\":{\"type\":\"integer\",\"description\":\"The seconds the window actually covers\"}," + "\"sensors\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{" + "\"id\":{\"type\":\"string\",\"description\":\"As get_hardware_sensors returns it\"}," + "\"component\":{\"type\":\"object\",\"properties\":{" + "\"kind\":{\"type\":\"string\",\"description\":\"cpu, memory, chipset, system, windows or source\"}," + "\"index\":{\"type\":\"integer\"}," + "\"source_id\":{\"type\":[\"integer\",\"null\"],\"description\":\"Null unless kind is source\"}," + "\"name\":{\"type\":[\"string\",\"null\"]}" + "},\"required\":[\"kind\",\"index\",\"source_id\",\"name\"]}," + "\"group\":{\"type\":\"string\"}," + "\"name\":{\"type\":[\"string\",\"null\"]}," + "\"unit\":{\"type\":\"string\",\"description\":\"celsius, watts, mhz, mt_per_s, multiplier, volts, throttle, mb_per_s, gear, amperes, rpm or percent\"}," + "\"listed\":{\"type\":\"boolean\",\"description\":\"The sensor was listed in the last update; false once it has disappeared\"}," + "\"sample_count\":{\"type\":\"integer\",\"description\":\"This sensor's samples in the window; fewer than the window for a sensor that appeared later\"}," + "\"stats\":{\"type\":[\"object\",\"null\"],\"description\":\"Over the samples with a reading; null when there were none, and always null for unit throttle\",\"properties\":{" + "\"average\":{\"type\":\"number\"}," + "\"minimum\":{\"type\":\"number\"}," + "\"maximum\":{\"type\":\"number\"}," + "\"last\":{\"type\":\"number\",\"description\":\"The most recent reading\"}," + "\"reading_count\":{\"type\":\"integer\"}" + "},\"required\":[\"average\",\"minimum\",\"maximum\",\"last\",\"reading_count\"]}," + "\"throttle\":{\"type\":[\"object\",\"null\"],\"description\":\"Unit throttle only\",\"properties\":{" + "\"throttled_count\":{\"type\":\"integer\",\"description\":\"Samples in which any reason applied\"}," + "\"reasons\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"integer\"},\"description\":\"Samples per reason, for the reasons that occurred\"}" + "},\"required\":[\"throttled_count\",\"reasons\"]}," + "\"samples\":{\"type\":[\"array\",\"null\"],\"description\":\"Null unless include_samples; most recent first\",\"items\":{\"type\":\"object\",\"properties\":{" + "\"time\":{\"type\":[\"string\",\"null\"]}," + "\"value\":{\"type\":[\"number\",\"null\"],\"description\":\"Null when the sensor did not report; absent for unit throttle\"}," + "\"throttle\":{\"type\":[\"array\",\"null\"],\"items\":{\"type\":\"string\"},\"description\":\"Unit throttle only, in place of value: the reasons that applied, or null when the sensor did not report\"}" + "},\"required\":[\"time\"]}}" + "},\"required\":[\"id\",\"component\",\"group\",\"name\",\"unit\",\"listed\",\"sample_count\",\"stats\",\"throttle\",\"samples\"]}}," + AT_PAGE_OUTPUT_PROPERTIES "," + "\"collector\":{\"type\":\"object\",\"description\":\"As get_hardware_sensors returns it\",\"properties\":{" + "\"sensors_enabled\":{\"type\":\"boolean\"}," + "\"kernel_sensors_available\":{\"type\":\"boolean\"}," + "\"windows_counters_present\":{\"type\":\"boolean\"}," + "\"source_sensors_present\":{\"type\":\"boolean\"}," + "\"unavailable_reason\":{\"type\":[\"string\",\"null\"]}" + "},\"required\":[\"sensors_enabled\",\"kernel_sensors_available\",\"windows_counters_present\",\"source_sensors_present\",\"unavailable_reason\"]}," + AT_SNAPSHOT_SCHEMA + "},\"required\":[\"update_interval_ms\",\"history_slots\",\"window_seconds\",\"sensors\",\"count\",\"total_count\",\"truncated\",\"collector\"]}," + AT_ANNOTATIONS("Get hardware sensor history", AT_READ_HINTS) "}" + }, { "list_logon_sessions", L"List logon sessions", AtTierSensitiveRead, AtActionListLogonSessions, SETTING_NAME_TOOL_ACCESS(L"list_logon_sessions"), SETTING_NAME_TOOL_CONFIRM(L"list_logon_sessions"), diff --git a/plugins/AgentTools/toolhw.c b/plugins/AgentTools/toolhw.c index 98f269e89..7ff20e67e 100644 --- a/plugins/AgentTools/toolhw.c +++ b/plugins/AgentTools/toolhw.c @@ -96,23 +96,55 @@ static CONST PWSTR AtpHwThrottleNames[] = }; C_ASSERT(RTL_NUMBER_OF(AtpHwThrottleFlags) == RTL_NUMBER_OF(AtpHwThrottleNames)); -// A copy of a PH_HW_SENSOR_ENTRY that outlives the enumeration. +// The same names as JSON keys, which must be literals. +static CONST PCSTR AtpHwThrottleKeys[] = +{ + "thermal", + "prochot", + "critical", + "power_limit", + "pl1", + "pl2", + "vr_thermal", + "vr_current", + "electrical", + "max_turbo", + "turbo_attenuation", + "running_average_thermal", + "residency", + "graphics", + "autonomous", +}; +C_ASSERT(RTL_NUMBER_OF(AtpHwThrottleFlags) == RTL_NUMBER_OF(AtpHwThrottleKeys)); + +#define AT_HW_HISTORY_DEFAULT_WINDOW_SECONDS 60 +#define AT_HW_SENSOR_ID_LENGTH (16 + 1 + 2 + 1 + 16) + +// A copy of a PH_HW_SENSOR_ENTRY that outlives the enumeration, or of a stored history's info. typedef struct _AT_HW_SENSOR { PH_HW_COMPONENT_KIND ComponentKind; ULONG ComponentIndex; ULONG SourceId; ULONG64 ComponentKey; - PPH_STRING ComponentName; + PPH_STRING ComponentName; // NULL only for a stored history without a name PH_HW_SENSOR_GROUP Group; PH_HW_SENSOR_UNIT Unit; ULONG64 SensorKey; - PPH_STRING SensorName; + PPH_STRING SensorName; // NULL only for a stored history without a name + BOOLEAN Listed; BOOLEAN Current; FLOAT Value; ULONG ThrottleFlags; } AT_HW_SENSOR, *PAT_HW_SENSOR; +typedef struct _AT_HW_HISTORY_KEY +{ + ULONG64 ComponentKey; + PH_HW_SENSOR_GROUP Group; + ULONG64 SensorKey; +} AT_HW_HISTORY_KEY, *PAT_HW_HISTORY_KEY; + _Function_class_(PH_HW_SENSOR_ENUM_CALLBACK) static VOID NTAPI AtpHwCollectSensor( _In_ PCPH_HW_SENSOR_ENTRY Entry, @@ -140,6 +172,7 @@ static VOID NTAPI AtpHwCollectSensor( sensor->Unit = Entry->Unit; sensor->SensorKey = Entry->SensorKey; sensor->SensorName = PhReferenceObject(Entry->SensorName); + sensor->Listed = TRUE; sensor->Current = Entry->Current; sensor->Value = Entry->Value; sensor->ThrottleFlags = Entry->ThrottleFlags; @@ -147,6 +180,22 @@ static VOID NTAPI AtpHwCollectSensor( PhAddItemList(sensors, sensor); } +static VOID AtpHwFreeSensors( + _In_ PPH_LIST Sensors + ) +{ + for (ULONG i = 0; i < Sensors->Count; i++) + { + PAT_HW_SENSOR sensor = Sensors->Items[i]; + + PhClearReference(&sensor->ComponentName); + PhClearReference(&sensor->SensorName); + PhFree(sensor); + } + + PhDereferenceObject(Sensors); +} + static int __cdecl AtpHwCompareSensors( _In_ void* Context, _In_ CONST void* Left, @@ -218,18 +267,16 @@ static BOOLEAN AtpHwGetEnumArgument( return TRUE; } -static PVOID AtpHwCreateSensorRow( +static VOID AtpHwAddSensorIdentity( + _In_ PVOID Row, _In_ PAT_HW_SENSOR Sensor ) { - PVOID row; PVOID component; PPH_STRING id; - row = PhCreateJsonObject(); - id = PhFormatString(L"%016I64x.%02lx.%016I64x", Sensor->ComponentKey, (ULONG)Sensor->Group, Sensor->SensorKey); - AtJsonAddString(row, "id", id); + AtJsonAddString(Row, "id", id); PhDereferenceObject(id); component = PhCreateJsonObject(); @@ -242,11 +289,21 @@ static PVOID AtpHwCreateSensorRow( AtJsonAddNull(component, "source_id"); AtJsonAddString(component, "name", Sensor->ComponentName); - PhAddJsonObjectValue(row, "component", component); + PhAddJsonObjectValue(Row, "component", component); - PhAddJsonObject(row, "group", AtpHwGroups[Sensor->Group]); - AtJsonAddString(row, "name", Sensor->SensorName); - PhAddJsonObject(row, "unit", AtpHwUnits[Sensor->Unit]); + PhAddJsonObject(Row, "group", AtpHwGroups[Sensor->Group]); + AtJsonAddString(Row, "name", Sensor->SensorName); + PhAddJsonObject(Row, "unit", AtpHwUnits[Sensor->Unit]); +} + +static PVOID AtpHwCreateSensorRow( + _In_ PAT_HW_SENSOR Sensor + ) +{ + PVOID row; + + row = PhCreateJsonObject(); + AtpHwAddSensorIdentity(row, Sensor); if (Sensor->Current && Sensor->Unit != PhHwUnitThrottle) PhAddJsonObjectDouble(row, "value", Sensor->Value); @@ -272,6 +329,21 @@ static PVOID AtpHwCreateSensorRow( return row; } +static VOID AtpHwAddCollector( + _In_ PVOID Object + ) +{ + PVOID collector; + + collector = PhCreateJsonObject(); + PhAddJsonObjectBoolean(collector, "sensors_enabled", !!PhGetIntegerSetting(L"EnableHardwareSensors")); + PhAddJsonObjectBoolean(collector, "kernel_sensors_available", PhHwSensorsAvailable()); + PhAddJsonObjectBoolean(collector, "windows_counters_present", PhHwCounterSensorsPresent()); + PhAddJsonObjectBoolean(collector, "source_sensors_present", PhHwSourceSensorsPresent()); + AtJsonAddStringRef(collector, "unavailable_reason", PhHwGetSensorsUnavailableReason()); + PhAddJsonObjectValue(Object, "collector", collector); +} + VOID AtpGetHardwareSensors( _In_ PAT_TOOL_CALL Call, _Inout_ PAT_TOOL_RESULT Result @@ -283,8 +355,6 @@ VOID AtpGetHardwareSensors( PPH_LIST sensors; AT_ROWS rows; PVOID structured; - PVOID collector; - PCPH_STRINGREF reason; ULONG i; if (!AtpHwGetEnumArgument( @@ -339,31 +409,463 @@ VOID AtpGetHardwareSensors( AtAddRows(structured, "sensors", &rows); - collector = PhCreateJsonObject(); - PhAddJsonObjectBoolean(collector, "sensors_enabled", !!PhGetIntegerSetting(L"EnableHardwareSensors")); - PhAddJsonObjectBoolean(collector, "kernel_sensors_available", PhHwSensorsAvailable()); - PhAddJsonObjectBoolean(collector, "windows_counters_present", PhHwCounterSensorsPresent()); - PhAddJsonObjectBoolean(collector, "source_sensors_present", PhHwSourceSensorsPresent()); - reason = PhHwGetSensorsUnavailableReason(); - AtJsonAddStringRef(collector, "unavailable_reason", reason); - PhAddJsonObjectValue(structured, "collector", collector); + AtpHwAddCollector(structured); AtAddSnapshot(structured); Result->StructuredContent = structured; AtDeleteRows(&rows); + AtpHwFreeSensors(sensors); + PhClearReference(&nameContains); +} - for (i = 0; i < sensors->Count; i++) +_Success_(return) +static BOOLEAN AtpHwParseHex( + _In_reads_(Digits) PCWCH Buffer, + _In_ ULONG Digits, + _Out_ PULONG64 Value + ) +{ + ULONG64 value = 0; + + for (ULONG i = 0; i < Digits; i++) { - PAT_HW_SENSOR sensor = sensors->Items[i]; + WCHAR c = Buffer[i]; + ULONG digit; - PhDereferenceObject(sensor->ComponentName); - PhDereferenceObject(sensor->SensorName); - PhFree(sensor); + if (c >= L'0' && c <= L'9') + digit = c - L'0'; + else if (c >= L'a' && c <= L'f') + digit = c - L'a' + 10; + else if (c >= L'A' && c <= L'F') + digit = c - L'A' + 10; + else + return FALSE; + + value = (value << 4) | digit; } - PhDereferenceObject(sensors); + *Value = value; + return TRUE; +} + +// Accepts exactly the id get_hardware_sensors formats: 16 hex digits, '.', 2, '.', 16. +_Success_(return) +BOOLEAN AtpHwParseSensorId( + _In_ PPH_STRING Id, + _Out_ PULONG64 ComponentKey, + _Out_ PH_HW_SENSOR_GROUP* Group, + _Out_ PULONG64 SensorKey + ) +{ + ULONG64 componentKey; + ULONG64 group; + ULONG64 sensorKey; + + if (Id->Length / sizeof(WCHAR) != AT_HW_SENSOR_ID_LENGTH) + return FALSE; + if (Id->Buffer[16] != L'.' || Id->Buffer[19] != L'.') + return FALSE; + if (!AtpHwParseHex(&Id->Buffer[0], 16, &componentKey)) + return FALSE; + if (!AtpHwParseHex(&Id->Buffer[17], 2, &group) || group >= PhHwGroupMaximum) + return FALSE; + if (!AtpHwParseHex(&Id->Buffer[20], 16, &sensorKey)) + return FALSE; + + *ComponentKey = componentKey; + *Group = (PH_HW_SENSOR_GROUP)group; + *SensorKey = sensorKey; + return TRUE; +} + +_Function_class_(PH_HW_SENSOR_HISTORY_ENUM_CALLBACK) +static VOID NTAPI AtpHwCollectHistoryKey( + _In_ ULONG64 ComponentKey, + _In_ PH_HW_SENSOR_GROUP Group, + _In_ ULONG64 SensorKey, + _In_ BOOLEAN Listed, + _In_opt_ PVOID Context + ) +{ + PPH_ARRAY keys = Context; + AT_HW_HISTORY_KEY key; + + UNREFERENCED_PARAMETER(Listed); + + if (!keys) + return; + + key.ComponentKey = ComponentKey; + key.Group = Group; + key.SensorKey = SensorKey; + PhAddItemArray(keys, &key); +} + +// Searches the first Count sensors, which are sorted by key. +static PAT_HW_SENSOR AtpHwFindSensor( + _In_ PPH_LIST Sensors, + _In_ ULONG Count, + _In_ ULONG64 ComponentKey, + _In_ PH_HW_SENSOR_GROUP Group, + _In_ ULONG64 SensorKey + ) +{ + AT_HW_SENSOR key; + PAT_HW_SENSOR keyPointer = &key; + PAT_HW_SENSOR* found; + + key.ComponentKey = ComponentKey; + key.Group = Group; + key.SensorKey = SensorKey; + + found = bsearch_s(&keyPointer, Sensors->Items, Count, sizeof(PVOID), AtpHwCompareSensors, NULL); + + return found ? *found : NULL; +} + +// A sensor described by what the history store kept, for one the provider no longer lists. +static PAT_HW_SENSOR AtpHwCreateStoredSensor( + _In_ ULONG64 ComponentKey, + _In_ PH_HW_SENSOR_GROUP Group, + _In_ ULONG64 SensorKey + ) +{ + PH_HW_SENSOR_HISTORY_INFO info; + PAT_HW_SENSOR sensor; + FLOAT value; + ULONG count; + + if (!PhHwCopySensorHistory(ComponentKey, Group, SensorKey, 0, &value, NULL, &count, &info)) + return NULL; + + if ((ULONG)info.ComponentKind >= PhHwComponentMaximum || (ULONG)info.Unit >= PhHwUnitMaximum) + { + PhClearReference(&info.ComponentName); + PhClearReference(&info.SensorName); + return NULL; + } + + sensor = PhAllocateZero(sizeof(AT_HW_SENSOR)); + sensor->ComponentKind = info.ComponentKind; + sensor->ComponentIndex = info.ComponentIndex; + sensor->SourceId = info.SourceId; + sensor->ComponentKey = ComponentKey; + sensor->ComponentName = info.ComponentName; + sensor->Group = Group; + sensor->Unit = info.Unit; + sensor->SensorKey = SensorKey; + sensor->SensorName = info.SensorName; + sensor->Listed = info.Listed; + + return sensor; +} + +static PVOID AtpHwCreateHistoryRow( + _In_ PAT_HW_SENSOR Sensor, + _In_ ULONG WindowSamples, + _In_ BOOLEAN IncludeSamples, + _Out_writes_(WindowSamples) PFLOAT Values, + _Out_writes_(WindowSamples) PLARGE_INTEGER Times + ) +{ + BOOLEAN throttle = Sensor->Unit == PhHwUnitThrottle; + ULONG reasonCounts[RTL_NUMBER_OF(AtpHwThrottleFlags)] = { 0 }; + ULONG throttledCount = 0; + ULONG readings = 0; + DOUBLE total = 0.0; + FLOAT minimum = 0.0f; + FLOAT maximum = 0.0f; + FLOAT last = 0.0f; + ULONG count; + PVOID row; + + if (!PhHwCopySensorHistory(Sensor->ComponentKey, Sensor->Group, Sensor->SensorKey, WindowSamples, Values, Times, &count, NULL)) + count = 0; + + for (ULONG i = 0; i < count; i++) + { + FLOAT value = Values[i]; + + if (isnan(value)) + continue; + + if (throttle) + { + ULONG flags = (ULONG)value; + + if (flags) + throttledCount++; + + for (ULONG j = 0; j < RTL_NUMBER_OF(AtpHwThrottleFlags); j++) + { + if (flags & AtpHwThrottleFlags[j]) + reasonCounts[j]++; + } + } + else if (readings == 0) + { + minimum = value; + maximum = value; + last = value; // most recent first + } + else + { + minimum = min(minimum, value); + maximum = max(maximum, value); + } + + total += value; + readings++; + } + + row = PhCreateJsonObject(); + AtpHwAddSensorIdentity(row, Sensor); + PhAddJsonObjectBoolean(row, "listed", Sensor->Listed); + PhAddJsonObjectUInt64(row, "sample_count", count); + + if (!throttle && readings) + { + PVOID stats = PhCreateJsonObject(); + + PhAddJsonObjectDouble(stats, "average", total / readings); + PhAddJsonObjectDouble(stats, "minimum", minimum); + PhAddJsonObjectDouble(stats, "maximum", maximum); + PhAddJsonObjectDouble(stats, "last", last); + PhAddJsonObjectUInt64(stats, "reading_count", readings); + PhAddJsonObjectValue(row, "stats", stats); + } + else + { + AtJsonAddNull(row, "stats"); + } + + if (throttle) + { + PVOID summary = PhCreateJsonObject(); + PVOID reasons = PhCreateJsonObject(); + + PhAddJsonObjectUInt64(summary, "throttled_count", throttledCount); + + for (ULONG j = 0; j < RTL_NUMBER_OF(AtpHwThrottleFlags); j++) + { + if (reasonCounts[j]) + PhAddJsonObjectUInt64(reasons, AtpHwThrottleKeys[j], reasonCounts[j]); + } + + PhAddJsonObjectValue(summary, "reasons", reasons); + PhAddJsonObjectValue(row, "throttle", summary); + } + else + { + AtJsonAddNull(row, "throttle"); + } + + if (IncludeSamples) + { + PVOID samples = PhCreateJsonArray(); + + for (ULONG i = 0; i < count; i++) + { + PVOID sample = PhCreateJsonObject(); + + AtJsonAddTime(sample, "time", &Times[i]); + + if (isnan(Values[i])) + AtJsonAddNull(sample, throttle ? "throttle" : "value"); + else if (throttle) + AtJsonAddFlagStrings(sample, "throttle", (ULONG)Values[i], AtpHwThrottleFlags, AtpHwThrottleNames, RTL_NUMBER_OF(AtpHwThrottleFlags)); + else + PhAddJsonObjectDouble(sample, "value", Values[i]); + + PhAddJsonArrayObject(samples, sample); + } + + PhAddJsonObjectValue(row, "samples", samples); + } + else + { + AtJsonAddNull(row, "samples"); + } + + return row; +} + +VOID AtpGetHardwareSensorHistory( + _In_ PAT_TOOL_CALL Call, + _Inout_ PAT_TOOL_RESULT Result + ) +{ + ULONG componentFilter; + ULONG groupFilter; + PPH_STRING nameContains = NULL; + ULONG64 windowSeconds; + ULONG interval; + ULONG slots; + ULONG windowSamples; + BOOLEAN includeSamples; + PVOID ids; + PPH_LIST sensors; + ULONG listedCount; + PPH_LIST selected; + PFLOAT values; + PLARGE_INTEGER times; + AT_ROWS rows; + PVOID structured; + ULONG i; + + if (!AtpHwGetEnumArgument( + Call->Arguments, + "component", + AtpHwComponentKinds, + RTL_NUMBER_OF(AtpHwComponentKinds), + L"cpu, memory, chipset, system, windows or source", + &componentFilter, + Result + )) + { + return; + } + + if (!AtpHwGetEnumArgument( + Call->Arguments, + "group", + AtpHwGroups, + RTL_NUMBER_OF(AtpHwGroups), + L"temperatures, powers, limits, clocks, bandwidth, active_clocks, multipliers, voltages, currents, residency, fans, controls or throttling", + &groupFilter, + Result + )) + { + return; + } + + interval = AtGetUpdateInterval(); + slots = PhHwGetSensorHistorySlots(); + + if (!AtGetArgumentUInt64(Call->Arguments, "window_seconds", &windowSeconds) || windowSeconds == 0) + windowSeconds = AT_HW_HISTORY_DEFAULT_WINDOW_SECONDS; + + windowSamples = (ULONG)min(windowSeconds * 1000 / interval, slots); + + if (windowSamples == 0) + windowSamples = 1; + + includeSamples = AtJsonGetObjectBoolean(Call->Arguments, "include_samples"); + ids = AtJsonGetObjectMember(Call->Arguments, "ids", PH_JSON_OBJECT_TYPE_ARRAY); + + // Copied out first so that no row is built while the provider or the store holds a lock. + sensors = PhCreateList(64); + PhHwEnumerateSensors(AtpHwCollectSensor, sensors); + qsort_s(sensors->Items, sensors->Count, sizeof(PVOID), AtpHwCompareSensors, NULL); + listedCount = sensors->Count; + + // The rows in the order they are returned; sensors owns them. + selected = PhCreateList(64); + + if (ids) + { + ULONG count = PhGetJsonArrayLength(ids); + + for (i = 0; i < count; i++) + { + PPH_STRING id = PhGetJsonObjectString(PhGetJsonArrayIndexObject(ids, i)); + ULONG64 componentKey; + PH_HW_SENSOR_GROUP group; + ULONG64 sensorKey; + PAT_HW_SENSOR sensor; + + if (!id || !AtpHwParseSensorId(id, &componentKey, &group, &sensorKey)) + { + AtSetToolError(Result, "invalid_arguments", STATUS_INVALID_PARAMETER, L"ids[%lu] is not a sensor id from get_hardware_sensors.", i); + PhClearReference(&id); + goto CleanupExit; + } + + if (!(sensor = AtpHwFindSensor(sensors, listedCount, componentKey, group, sensorKey))) + { + if (!(sensor = AtpHwCreateStoredSensor(componentKey, group, sensorKey))) + { + AtSetToolError(Result, "not_found", STATUS_NOT_FOUND, L"No sensor or history has the id %s.", id->Buffer); + PhDereferenceObject(id); + goto CleanupExit; + } + + PhAddItemList(sensors, sensor); + } + + PhAddItemList(selected, sensor); + PhDereferenceObject(id); + } + } + else + { + PH_ARRAY keys; + + nameContains = AtGetArgumentString(Call->Arguments, "name_contains"); + + // The histories of sensors that are no longer listed are rows too. + PhInitializeArray(&keys, sizeof(AT_HW_HISTORY_KEY), 64); + PhHwEnumerateSensorHistories(AtpHwCollectHistoryKey, &keys); + + for (i = 0; i < keys.Count; i++) + { + PAT_HW_HISTORY_KEY key = PhItemArray(&keys, i); + PAT_HW_SENSOR sensor; + + if ((ULONG)key->Group >= PhHwGroupMaximum) + continue; + if (AtpHwFindSensor(sensors, listedCount, key->ComponentKey, key->Group, key->SensorKey)) + continue; + + if (sensor = AtpHwCreateStoredSensor(key->ComponentKey, key->Group, key->SensorKey)) + PhAddItemList(sensors, sensor); + } + + PhDeleteArray(&keys); + qsort_s(sensors->Items, sensors->Count, sizeof(PVOID), AtpHwCompareSensors, NULL); + + for (i = 0; i < sensors->Count; i++) + { + PAT_HW_SENSOR sensor = sensors->Items[i]; + + if (componentFilter != ULONG_MAX && (ULONG)sensor->ComponentKind != componentFilter) + continue; + if (groupFilter != ULONG_MAX && (ULONG)sensor->Group != groupFilter) + continue; + if (nameContains && !AtContainsString(sensor->SensorName, nameContains) && !AtContainsString(sensor->ComponentName, nameContains)) + continue; + + PhAddItemList(selected, sensor); + } + } + + values = PhAllocate(windowSamples * sizeof(FLOAT)); + times = PhAllocate(windowSamples * sizeof(LARGE_INTEGER)); + + structured = PhCreateJsonObject(); + AtInitializeRows(&rows, Call->Arguments); + + for (i = 0; i < selected->Count; i++) + AtAddRow(&rows, AtpHwCreateHistoryRow(selected->Items[i], windowSamples, includeSamples, values, times)); + + PhAddJsonObjectUInt64(structured, "update_interval_ms", interval); + PhAddJsonObjectUInt64(structured, "history_slots", slots); + PhAddJsonObjectUInt64(structured, "window_seconds", (ULONG64)windowSamples * interval / 1000); + AtAddRows(structured, "sensors", &rows); + AtpHwAddCollector(structured); + AtAddSnapshot(structured); + + Result->StructuredContent = structured; + + AtDeleteRows(&rows); + PhFree(times); + PhFree(values); + +CleanupExit: + PhDereferenceObject(selected); + AtpHwFreeSensors(sensors); PhClearReference(&nameContains); } @@ -405,6 +907,9 @@ VOID AtHardwareInvokeTool( case AtActionGetHardwareReport: AtpGetHardwareReport(Call, Result); break; + case AtActionGetHardwareSensorHistory: + AtpGetHardwareSensorHistory(Call, Result); + break; default: AtSetToolError(Result, "failed", STATUS_NOT_IMPLEMENTED, L"This tool is not implemented."); break; diff --git a/plugins/AgentTools/tools.c b/plugins/AgentTools/tools.c index 08bd0fe4f..613f42724 100644 --- a/plugins/AgentTools/tools.c +++ b/plugins/AgentTools/tools.c @@ -1871,6 +1871,7 @@ VOID AtInvokeTool( break; case AtActionGetHardwareSensors: case AtActionGetHardwareReport: + case AtActionGetHardwareSensorHistory: AtHardwareInvokeTool(Tool, Call, Target, Result); break; case AtActionListLogonSessions: