Skip to content

Commit

Permalink
Fix read access violation in psutil.cpu_count(logical=False) (#1480)
Browse files Browse the repository at this point in the history
Fix read access violation in psutil.cpu_count(logical=False) by
stopping the iteration through the
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer when we hit the last
item.
  • Loading branch information
samertm authored and giampaolo committed Apr 5, 2019
1 parent e471e7c commit 0056ffe
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions psutil/_psutil_windows.c
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ psutil_cpu_count_phys(PyObject *self, PyObject *args) {
DWORD length = 0;
DWORD offset = 0;
DWORD ncpus = 0;
DWORD prev_processor_info_size = 0;

// GetLogicalProcessorInformationEx() is available from Windows 7
// onward. Differently from GetLogicalProcessorInformation()
Expand Down Expand Up @@ -533,13 +534,20 @@ psutil_cpu_count_phys(PyObject *self, PyObject *args) {
}

ptr = buffer;
while (ptr->Size > 0 && offset + ptr->Size <= length) {
while (offset < length) {
// Advance ptr by the size of the previous
// SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX struct.
ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)\
(((char*)ptr) + prev_processor_info_size);

if (ptr->Relationship == RelationProcessorCore) {
ncpus += 1;
}

// When offset == length, we've reached the last processor
// info struct in the buffer.
offset += ptr->Size;
ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)\
(((char*)ptr) + ptr->Size);
prev_processor_info_size = ptr->Size;
}

free(buffer);
Expand Down

0 comments on commit 0056ffe

Please sign in to comment.