diff --git a/include/dap_common.h b/include/dap_common.h index cc9a9cbe5ae26b42aeec97fa508fc235ebdadff4..042a37746afde25e722b8b47f4efaebb74acdcc4 100755 --- a/include/dap_common.h +++ b/include/dap_common.h @@ -32,6 +32,8 @@ #include <stdlib.h> #include <time.h> +#include "portable_endian.h" + #define DAP_NEW( a ) ( (a*) malloc(sizeof(a)) ) #define DAP_NEW_SIZE( a, b ) ( (a*) malloc(b) ) #define DAP_NEW_Z( a ) ( (a*) calloc(1,sizeof(a)) ) @@ -64,11 +66,35 @@ #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif - #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif +#ifndef min + #define min MIN +#endif +#ifndef max + #define max MAX +#endif + +#ifndef LOWORD + #define LOWORD( l ) ((uint16_t) (((uintptr_t) (l)) & 0xFFFF)) + #define HIWORD( l ) ((uint16_t) ((((uintptr_t) (l)) >> 16) & 0xFFFF)) + #define LOBYTE( w ) ((uint8_t) (((uintptr_t) (w)) & 0xFF)) + #define HIBYTE( w ) ((uint8_t) ((((uintptr_t) (w)) >> 8) & 0xFF)) +#endif + +#ifndef RGB + #define RGB(r,g,b) ((uint32_t)(((uint8_t)(r)|((uint16_t)((uint8_t)(g))<<8))|(((uint32_t)(uint8_t)(b))<<16))) + #define RGBA(r, g, b, a) ((uint32_t) ((uint32_t)RGB(r,g,b) | (uint32_t)(a) << 24)) + #define GetRValue(rgb) (LOBYTE(rgb)) + #define GetGValue(rgb) (LOBYTE(((uint16_t)(rgb)) >> 8)) + #define GetBValue(rgb) (LOBYTE((rgb)>>16)) + #define GetAValue(rgb) (LOBYTE((rgb)>>24)) +#endif + +#define QBYTE RGBA + #define DAP_LOG_HISTORY_STR_SIZE 128 #define DAP_LOG_HISTORY_MAX_STRINGS 1024 #define DAP_LOG_HISTORY_BUFFER_SIZE (DAP_LOG_HISTORY_STR_SIZE * DAP_LOG_HISTORY_MAX_STRINGS) @@ -83,7 +109,7 @@ typedef enum dap_log_level { L_DEBUG = 0, L_INFO = 1, L_NOTICE = 2, - L_MESSAGE = 3, + L_MSG = 3, L_DAP = 4, L_WARNING = 5, L_ATT = 6, @@ -144,7 +170,9 @@ static const uint16_t s_ascii_table_data[256] = { #define dap_ascii_isspace(c) (s_ascii_table_data[(unsigned char) (c)] & DAP_ASCII_SPACE) != 0 #define dap_ascii_isalpha(c) (s_ascii_table_data[(unsigned char) (c)] & DAP_ASCII_ALPHA) != 0 -int dap_common_init( const char * a_log_file ); +//int dap_common_init( const char * a_log_file ); +int dap_common_init( const char *console_title, const char *a_log_file ); + void dap_common_deinit(void); // set max items in log list diff --git a/include/portable_endian.h b/include/portable_endian.h new file mode 100644 index 0000000000000000000000000000000000000000..31c0809d913194de891b8498dc9a1a4d03fc7b5b --- /dev/null +++ b/include/portable_endian.h @@ -0,0 +1,122 @@ + +// "License": Public Domain +// I, Mathias Panzenb?ck, place this file hereby into the public domain. Use it at your own risk for whatever you like. +// In case there are jurisdictions that don't support putting things in the public domain you can also consider it to +// be "dual licensed" under the BSD, MIT and Apache licenses, if you want to. This code is trivial anyway. Consider it +// an example on how to get the endian conversion functions on different platforms. + +#ifndef PORTABLE_ENDIAN_H__ +#define PORTABLE_ENDIAN_H__ + +#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__) + +# define __WINDOWS__ + +#endif + +#if defined(__linux__) || defined(__CYGWIN__) + +# include <endian.h> + +#elif defined(__APPLE__) + +# include <libkern/OSByteOrder.h> + +# define htobe16(x) OSSwapHostToBigInt16(x) +# define htole16(x) OSSwapHostToLittleInt16(x) +# define be16toh(x) OSSwapBigToHostInt16(x) +# define le16toh(x) OSSwapLittleToHostInt16(x) + +# define htobe32(x) OSSwapHostToBigInt32(x) +# define htole32(x) OSSwapHostToLittleInt32(x) +# define be32toh(x) OSSwapBigToHostInt32(x) +# define le32toh(x) OSSwapLittleToHostInt32(x) + +# define htobe64(x) OSSwapHostToBigInt64(x) +# define htole64(x) OSSwapHostToLittleInt64(x) +# define be64toh(x) OSSwapBigToHostInt64(x) +# define le64toh(x) OSSwapLittleToHostInt64(x) + +# define __BYTE_ORDER BYTE_ORDER +# define __BIG_ENDIAN BIG_ENDIAN +# define __LITTLE_ENDIAN LITTLE_ENDIAN +# define __PDP_ENDIAN PDP_ENDIAN + +#elif defined(__OpenBSD__) + +# include <sys/endian.h> + +#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) + +# include <sys/endian.h> + +# define be16toh(x) betoh16(x) +# define le16toh(x) letoh16(x) + +# define be32toh(x) betoh32(x) +# define le32toh(x) letoh32(x) + +# define be64toh(x) betoh64(x) +# define le64toh(x) letoh64(x) + +#elif defined(__WINDOWS__) + +# include <windows.h> + +# if BYTE_ORDER == LITTLE_ENDIAN + +# if defined(_MSC_VER) +# include <stdlib.h> +# define htobe16(x) _byteswap_ushort(x) +# define htole16(x) (x) +# define be16toh(x) _byteswap_ushort(x) +# define le16toh(x) (x) + +# define htobe32(x) _byteswap_ulong(x) +# define htole32(x) (x) +# define be32toh(x) _byteswap_ulong(x) +# define le32toh(x) (x) + +# define htobe64(x) _byteswap_uint64(x) +# define htole64(x) (x) +# define be64toh(x) _byteswap_uint64(x) +# define le64toh(x) (x) + +# elif defined(__GNUC__) || defined(__clang__) + +# define htobe16(x) __builtin_bswap16(x) +# define htole16(x) (x) +# define be16toh(x) __builtin_bswap16(x) +# define le16toh(x) (x) + +# define htobe32(x) __builtin_bswap32(x) +# define htole32(x) (x) +# define be32toh(x) __builtin_bswap32(x) +# define le32toh(x) (x) + +# define htobe64(x) __builtin_bswap64(x) +# define htole64(x) (x) +# define be64toh(x) __builtin_bswap64(x) +# define le64toh(x) (x) +# else +# error platform not supported +# endif + +# else + +# error byte order not supported + +# endif + +# define __BYTE_ORDER BYTE_ORDER +# define __BIG_ENDIAN BIG_ENDIAN +# define __LITTLE_ENDIAN LITTLE_ENDIAN +# define __PDP_ENDIAN PDP_ENDIAN + +#else + +# error platform not supported + +#endif + +#endif diff --git a/src/dap_common.c b/src/dap_common.c index d4e83b850a625b77819d73a0c27768d33aa7e8c6..c79dc8d6471e70b65606711a0fa648ece3a26f41 100755 --- a/src/dap_common.c +++ b/src/dap_common.c @@ -40,17 +40,14 @@ #include <pthread.h> #include <syslog.h> - // Quick and dirty, I'm not sure but afair somewhere it was in UNIX systems too - #define min(a,b) (((a)<(b))?(a):(b)) - #define max(a,b) (((a)>(b))?(a):(b)) - #else // WIN32 #include <stdlib.h> #include <windows.h> #include <process.h> #include <pthread.h> - ///typedef HANDLE pthread_mutex_t; + + #include "win32/dap_console_manager.h" #define popen _popen #define pclose _pclose @@ -186,10 +183,14 @@ void dap_set_log_tag_width(size_t width) { * @param[in] a_log_file * @return */ -int dap_common_init( const char *a_log_file ) +int dap_common_init( const char *console_title, const char *a_log_file ) { srand( (unsigned int)time(NULL) ); + #ifdef _WIN32 + SetupConsole( console_title, L"Lucida Console", 12, 20 ); + #endif + // init default log tag 8 width strcpy( log_tag_fmt_str, "[%8s]\t"); @@ -254,6 +255,8 @@ err: */ void dap_common_deinit( ) { + printf("dap_common_deinit( )\n"); + if ( s_log_file ) fclose( s_log_file ); @@ -450,7 +453,7 @@ void _log_it( const char *log_tag, enum dap_log_level ll, const char *fmt,... ) { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; uint8_t *buf0 = temp_buffer; - uint32_t len, + uint32_t len, tmp, time_offset, tag_offset, msg_offset; @@ -501,22 +504,16 @@ void _log_it( const char *log_tag, enum dap_log_level ll, const char *fmt,... ) log_log( (char *)(buf0 + time_offset), len - time_offset, t ); #ifdef _WIN32 -// if ( !bUseANSIEscapeSequences ) + // if ( !bUseANSIEscapeSequences ) SetConsoleTextAttribute( hWin32ConOut, log_level_colors[ll] ); - // printf( "%s", (char *)(buf0 + time_offset) ); + // WriteConsole( hWin32ConOut, buf0 + time_offset, len - time_offset, &tmp, NULL ); + // fwrite( buf0 + time_offset, len - time_offset, 1, stdout ); + WriteFile( hWin32ConOut, buf0 + time_offset, len - time_offset, (LPDWORD)&tmp, NULL ); #else - -// memcpy( buf0, len, -// printf( "%s", (char *)buf0 ); fwrite( buf0, len, 1, stdout ); - #endif -///stdout - // printf("\x1b[0m\n"); -// "\x1b[0;37;40m", // L_DEBUG = 0 - pthread_mutex_unlock( &mutex ); } @@ -601,7 +598,9 @@ int dap_time_to_str_rfc822(char * out, size_t out_size_max, time_t t) static int breaker_set[2] = { -1, -1 }; static int initialized = 0; +#ifndef _WIN32 static struct timespec break_latency = { 0, BREAK_LATENCY * 1000 * 1000 }; +#endif int get_select_breaker( ) { diff --git a/src/win32/dap_console_manager.c b/src/win32/dap_console_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..2322a3ae3a3b03735b455479c106fa1f8fced056 --- /dev/null +++ b/src/win32/dap_console_manager.c @@ -0,0 +1,242 @@ +/* + Copyright (c) 2017-2019 (c) Project "DeM Labs Inc" https://github.com/demlabsinc + All rights reserved. + + This file is part of DAP (Deus Applications Prototypes) the open source project + + DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + DAP is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with any DAP based project. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <stdlib.h> +#include <stdio.h> +#include <stdlib.h> +#include <stddef.h> +#include <stdint.h> +#include <memory.h> + +#include <windows.h> + +#define WM_SETCONSOLEINFO (WM_USER + 201) + +#pragma pack(push, 1) +typedef struct _CONSOLE_INFO +{ + DWORD Length; + COORD ScreenBufferSize; + COORD WindowSize; + DWORD WindowPosX; + DWORD WindowPosY; + COORD FontSize; + DWORD FontFamily; + DWORD FontWeight; + WCHAR FaceName[32]; + DWORD CursorSize; + DWORD FullScreen; + DWORD QuickEdit; + DWORD AutoPosition; + DWORD InsertMode; + USHORT ScreenColors; + USHORT PopupColors; + DWORD HistoryNoDup; + DWORD HistoryBufferSize; + DWORD NumberOfHistoryBuffers; + COLORREF ColorTable[16]; + DWORD CodePage; + HWND Hwnd; + WCHAR ConsoleTitle[0x100]; +} CONSOLE_INFO; +#pragma pack(pop) + +static uint32_t palette[ 16 ] = { + + RGB( 0, 0, 0 ), // 0 black + RGB( 0, 0, 170 ), // 1 blue + RGB( 0, 170, 0 ), // 2 green + RGB( 170, 170, 0 ), // 3 cyan + RGB( 170, 0, 0 ), // 4 red + RGB( 170, 0, 170 ), // 5 magenta + RGB( 0, 85, 170 ), // 6 yellow / brown + RGB( 170, 170, 170 ), // 7 white / light gray + RGB( 85, 85, 85 ), // 8 dark gray / bright black + RGB( 85, 85, 255 ), // 9 bright blue + RGB( 0, 255, 0 ), // 10 bright green + RGB( 0, 255, 255 ), // 11 bright cyan + RGB( 255, 0, 0 ), // 12 bright red + RGB( 255, 85, 255 ), // 13 bright magenta + RGB( 255, 255, 85 ), // 14 bright yellow + RGB( 255, 255, 255 ) // 15 bright white +}; + +static void GetConsoleSizeInfo( CONSOLE_INFO *pci, HANDLE hConOut ) +{ + CONSOLE_SCREEN_BUFFER_INFO csbi; + + GetConsoleScreenBufferInfo( hConOut, &csbi ); + + pci->ScreenBufferSize = csbi.dwSize; + pci->WindowSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1; + pci->WindowSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; + pci->WindowPosX = csbi.srWindow.Left; + pci->WindowPosY = csbi.srWindow.Top; +} + +static BOOL SetConsoleInfo( HWND hwndConsole, CONSOLE_INFO *pci ) +{ + DWORD dwConsoleOwnerPid; + HANDLE hProcess; + HANDLE hSection, hDupSection; + PVOID ptrView = 0; + HANDLE hThread; + + GetWindowThreadProcessId( hwndConsole, &dwConsoleOwnerPid ); + + hProcess = OpenProcess( MAXIMUM_ALLOWED, FALSE, dwConsoleOwnerPid ); + hSection = CreateFileMapping( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, pci->Length, 0 ); + ptrView = MapViewOfFile( hSection, FILE_MAP_WRITE|FILE_MAP_READ, 0, 0, pci->Length ); + + memcpy( ptrView, pci, pci->Length ); + UnmapViewOfFile( ptrView ); + + DuplicateHandle( GetCurrentProcess(), hSection, hProcess, &hDupSection, 0, FALSE, DUPLICATE_SAME_ACCESS ); + + SendMessage( hwndConsole, WM_SETCONSOLEINFO, (WPARAM)hDupSection, 0 ); + + hThread = CreateRemoteThread( hProcess, 0, 0, (LPTHREAD_START_ROUTINE)CloseHandle, hDupSection, 0, 0 ); + + CloseHandle( hThread ); + CloseHandle( hSection ); + CloseHandle( hProcess ); + + return TRUE; +} + +typedef BOOL (WINAPI *PGetCurrentConsoleFontEx)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); +typedef BOOL (WINAPI *PSetCurrentConsoleFontEx)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); +typedef BOOL (WINAPI *PGetConsoleScreenBufferInfoEx)(HANDLE hConsoleOutput, PCONSOLE_SCREEN_BUFFER_INFOEX lpConsoleScreenBufferInfoEx); +typedef BOOL (WINAPI *PSetConsoleScreenBufferInfoEx)(HANDLE hConsoleOutput, PCONSOLE_SCREEN_BUFFER_INFOEX lpConsoleScreenBufferInfoEx); + +////Lucida Console 12 20 + +void SetupConsole( const char *title, const uint16_t *fontName, int fontx, int fonty ) +{ + HANDLE hConOut; + HANDLE hConIn; + + HWND hwndConsole = GetConsoleWindow( ); + if ( !hwndConsole ) { // daemon ? + return; + } + + uint32_t console_owner_proc_id; + + GetWindowThreadProcessId( hwndConsole, (LPDWORD)&console_owner_proc_id ); + + if ( console_owner_proc_id != GetCurrentProcessId() ) { +// return; + } + + SetConsoleTitleA( (LPCSTR)title ); + + hConOut = GetStdHandle( STD_OUTPUT_HANDLE ); + hConIn = GetStdHandle( STD_INPUT_HANDLE ); + + int sx = GetSystemMetrics( SM_CXSCREEN ); + int sy = GetSystemMetrics( SM_CYSCREEN ); + +// COORD conmax = GetLargestConsoleWindowSize( hConOut ); + + PGetCurrentConsoleFontEx pGetCurrentConsoleFontEx = (PGetCurrentConsoleFontEx) + GetProcAddress( GetModuleHandleA("kernel32.dll"), "GetCurrentConsoleFontEx" ); + PSetCurrentConsoleFontEx pSetCurrentConsoleFontEx = (PSetCurrentConsoleFontEx) + GetProcAddress( GetModuleHandleA("kernel32.dll"), "SetCurrentConsoleFontEx" ); + PGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx = (PGetConsoleScreenBufferInfoEx) + GetProcAddress( GetModuleHandleA("kernel32.dll"), "GetConsoleScreenBufferInfoEx" ); + PSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx = (PSetConsoleScreenBufferInfoEx) + GetProcAddress( GetModuleHandleA("kernel32.dll"), "SetConsoleScreenBufferInfoEx" ); + + if ( pGetCurrentConsoleFontEx && pSetCurrentConsoleFontEx && + pGetConsoleScreenBufferInfoEx && pSetConsoleScreenBufferInfoEx ) + { + CONSOLE_SCREEN_BUFFER_INFOEX conBufferInfo; + CONSOLE_FONT_INFOEX conFontInfo = {sizeof(CONSOLE_FONT_INFOEX)}; + + conFontInfo.cbSize = sizeof( CONSOLE_FONT_INFOEX ); + pGetCurrentConsoleFontEx( hConOut, TRUE, &conFontInfo ); + +// printf("conFontInfo.nFont %u \n", conFontInfo.nFont ); +// printf("conFontInfo.dwFontSize.X %u \n", conFontInfo.dwFontSize.X ); +// printf("conFontInfo.dwFontSize.Y %u \n", conFontInfo.dwFontSize.Y ); +// printf("conFontInfo.FontFamily %u \n", conFontInfo.FontFamily ); +// printf("conFontInfo.FontWeight %u \n", conFontInfo.FontWeight ); + + conFontInfo.nFont = 20; + conFontInfo.dwFontSize.X = 12; + conFontInfo.dwFontSize.Y = 20; + conFontInfo.FontFamily = 0; + conFontInfo.FontWeight = 0; + lstrcpyW( conFontInfo.FaceName, fontName ); + + pSetCurrentConsoleFontEx( hConOut, TRUE, &conFontInfo ); + + conBufferInfo.cbSize = sizeof( CONSOLE_SCREEN_BUFFER_INFOEX ); + pGetConsoleScreenBufferInfoEx( hConOut, &conBufferInfo ); + + memcpy( &conBufferInfo.ColorTable[0], &palette[0], 4 * 16 ); + pSetConsoleScreenBufferInfoEx( hConOut, &conBufferInfo ); + } + else { +// printf("XP ?...\n" ); + + CONSOLE_INFO ci = { sizeof(ci) }; + + GetConsoleSizeInfo( &ci, hConOut ); + + ci.FontSize.X = 12; + ci.FontSize.Y = 20; + ci.FontFamily = 0; + ci.FontWeight = 0; + + lstrcpyW( ci.FaceName, fontName ); + +// ci.CursorSize = 100; + ci.FullScreen = FALSE; + ci.QuickEdit = FALSE; + ci.AutoPosition = 0x10000; + ci.InsertMode = TRUE; + ci.ScreenColors = MAKEWORD(0x7, 0x0); + ci.PopupColors = MAKEWORD(0x5, 0xf); + ci.HistoryNoDup = TRUE; + ci.HistoryBufferSize = 50; + ci.NumberOfHistoryBuffers = 4; + + memcpy( &ci.ColorTable[0], &palette[0], 4 * 16 ); + + ci.CodePage = 0; + ci.Hwnd = hwndConsole; + + SetConsoleInfo( hwndConsole, &ci ); + } + + int bx = sx / 12; + int by = sy / 20; + + SMALL_RECT Rect = { 0, 0, bx, by }; + COORD coord = { bx, by }; + + SetConsoleWindowInfo( hConOut, TRUE, &Rect ); + SetConsoleScreenBufferSize( hConOut, coord ); + + SetWindowPos( hwndConsole, HWND_TOP, 0, 0, sx-1, sy-1, SWP_NOSIZE ); + ShowWindow( hwndConsole, SW_MAXIMIZE ); +} diff --git a/src/win32/dap_console_manager.h b/src/win32/dap_console_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..a1508068f047d8de04d810ccbcbedf5d7be97a1e --- /dev/null +++ b/src/win32/dap_console_manager.h @@ -0,0 +1,11 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +void SetupConsole( const char *title, const uint16_t *fontName, int fontx, int fonty ); + +#ifdef __cplusplus +} +#endif diff --git a/src/win32/dap_cpu_monitor.c b/src/win32/dap_cpu_monitor.c new file mode 100644 index 0000000000000000000000000000000000000000..c8374e96e35f1bb480a59fd75cb849e8dad39cb2 --- /dev/null +++ b/src/win32/dap_cpu_monitor.c @@ -0,0 +1,148 @@ +/* + Copyright (c) 2017-2019 (c) Project "DeM Labs Inc" https://github.com/demlabsinc + All rights reserved. + + This file is part of DAP (Deus Applications Prototypes) the open source project + + DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + DAP is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with any DAP based project. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <windows.h> +#include <winnt.h> +#include <winternl.h> + +#include <stdio.h> +#include <stdint.h> +#include <string.h> +#include <stdlib.h> + +#include "dap_cpu_monitor.h" +#include "dap_common.h" + +#define LOG_TAG "dap_cpu_monitor" + +//static FILE * _proc_stat = NULL; +static dap_cpu_stats_t _cpu_stats = {0}; + +static dap_cpu_t _cpu_old_stats[MAX_CPU_COUNT] = {0}; +static dap_cpu_t _cpu_summary_old = {0}; + +typedef struct proc_stat_line +{ + /* http://man7.org/linux/man-pages/man5/proc.5.html */ + char cpu[10]; + uint64_t user; + uint64_t nice; + uint64_t system; + uint64_t idle; + uint64_t iowait; + uint64_t irq; + uint64_t softirq; + uint64_t steal; + uint64_t guest; + uint64_t guest_nice; + uint64_t total; // summary all parameters +} proc_stat_line_t; + +int dap_cpu_monitor_init() +{ + SYSTEM_INFO si; + + GetSystemInfo( &si ); + _cpu_stats.cpu_cores_count = si.dwNumberOfProcessors; + + log_it( L_DEBUG, "dap_cpu_monitor_init(): Cpu core count: %d", _cpu_stats.cpu_cores_count ); + + dap_cpu_get_stats( ); // init prev parameters + + return 0; +} + +void dap_cpu_monitor_deinit() +{ + +} +/* +static void _deserealize_proc_stat(char *line, proc_stat_line_t *stat) +{ + sscanf(line,"%s %zu %zu %zu %zu %zu %zu %zu %zu %zu %zu", + stat->cpu, &stat->user, &stat->nice, &stat->system, &stat->idle, + &stat->iowait, &stat->irq, &stat->softirq, &stat->steal, + &stat->guest, &stat->guest_nice); + + stat->total = stat->user + stat->system + stat->idle + + stat->iowait + stat->irq + stat->softirq + + stat->steal + stat->guest + stat->guest_nice; +} +*/ +static float _calculate_load( uint64_t idle_time, uint64_t prev_idle_time, + uint64_t total_time, uint64_t prev_total_time ) { + return ( 1 - (1.0 * idle_time - prev_idle_time) / (total_time - prev_total_time) ) * 100.0; +} + +dap_cpu_stats_t dap_cpu_get_stats() +{ + FILETIME idleTime, kernelTime, userTime; + GetSystemTimes( &idleTime, &kernelTime, &userTime ); + + #define WINNT_FILETIME_TO_UINT64(t) (((uint64_t)(t.dwHighDateTime)<<32) | (uint64_t)(t.dwLowDateTime)) + _cpu_stats.cpu_summary.idle_time = WINNT_FILETIME_TO_UINT64(idleTime); + _cpu_stats.cpu_summary.total_time = WINNT_FILETIME_TO_UINT64(kernelTime) + WINNT_FILETIME_TO_UINT64(userTime); + + /*********************************************/ + + SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION pinfo[64]; + ULONG outsize; + uint32_t ntstatus_error; + + ntstatus_error = NtQuerySystemInformation( SystemProcessorPerformanceInformation, &pinfo, + sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * 64, &outsize ); + + if ( ntstatus_error ) { + log_it(L_ERROR, "NtQuerySystemInformation returned an error %u", ntstatus_error ); + return (dap_cpu_stats_t){0}; + } + + if ( outsize < sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * _cpu_stats.cpu_cores_count ) { + log_it(L_WARNING, "NtQuerySystemInformation: data size less than expected"); + } + + for( uint32_t i = 0; i < _cpu_stats.cpu_cores_count; i++ ) { + + _cpu_stats.cpus[i].idle_time = pinfo[i].IdleTime.QuadPart; + _cpu_stats.cpus[i].total_time = pinfo[i].KernelTime.QuadPart + pinfo[i].UserTime.QuadPart; + _cpu_stats.cpus[i].ncpu = i; + + _cpu_stats.cpus[i].load = _calculate_load(_cpu_stats.cpus[i].idle_time, + _cpu_old_stats[i].idle_time, + _cpu_stats.cpus[i].total_time, + _cpu_old_stats[i].total_time); + + // log_it(L_WARNING, "CPU %d %f", i, _cpu_stats.cpus[i].load); + } + + _cpu_stats.cpu_summary.load = _calculate_load(_cpu_stats.cpu_summary.idle_time, + _cpu_summary_old.idle_time, + _cpu_stats.cpu_summary.total_time, + _cpu_summary_old.total_time); + + // log_it(L_WARNING, "%f", _cpu_stats.cpu_summary.load); + + memcpy(&_cpu_summary_old, &_cpu_stats.cpu_summary, sizeof (dap_cpu_t)); + + memcpy(_cpu_old_stats, _cpu_stats.cpus, + sizeof (dap_cpu_t) * _cpu_stats.cpu_cores_count); + + return _cpu_stats; +} diff --git a/src/win32/dap_cpu_monitor.h b/src/win32/dap_cpu_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..efec16511a597a4bb970d20f463d55f64c76a2aa --- /dev/null +++ b/src/win32/dap_cpu_monitor.h @@ -0,0 +1,34 @@ +#pragma once + +#define MAX_CPU_COUNT 64 + +typedef struct dap_cpu { + uint32_t ncpu; // number of cpu core + float load; // percent of load + uint64_t total_time; + uint64_t idle_time; +} dap_cpu_t; + +typedef struct dap_cpu_stats +{ + uint32_t cpu_cores_count; + dap_cpu_t cpu_summary; // average statistic for all cpu + dap_cpu_t cpus[MAX_CPU_COUNT]; // list of cpu with stat +} dap_cpu_stats_t; + +/** + * @brief dap_cpu_monitor_init Monitor CPU initialization + * @return + */ +int dap_cpu_monitor_init(void); + +/** + * @brief dap_cpu_monitor_deinit Monitor CPU deinitialization + */ +void dap_cpu_monitor_deinit(void); + +/** + * @brief dap_cpu_get_stats Getting processor information + * @return + */ +dap_cpu_stats_t dap_cpu_get_stats(void); diff --git a/src/win32/dap_network_monitor.h b/src/win32/dap_network_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..5c6aa8024df190debc67d7f35f9701b7ff98d611 --- /dev/null +++ b/src/win32/dap_network_monitor.h @@ -0,0 +1,93 @@ +/* + * Authors: + * Anatolii Kurotych <akurotych@gmail.com> + * DeM Labs Inc. https://demlabs.net + * DeM Labs Open source community https://github.com/demlabsinc + * Copyright (c) 2017-2019 + * All rights reserved. + + This file is part of DAP (Deus Applications Prototypes) the open source project + + DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + DAP is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with any DAP based project. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +#pragma once + +#include <stdint.h> +#include <stdbool.h> + +//#include <net/if.h> +//#include <linux/rtnetlink.h> + +#define MAX_IP_STR_LEN 15 +#define DAP_ADRESS_UNDEFINED (uint64_t)-1 + +typedef enum { + // like in rtnetlink defines + IP_ADDR_ADD, + IP_ADDR_REMOVE, + IP_ROUTE_ADD, + IP_ROUTE_REMOVE, + IP_LINK_NEW, + IP_LINK_DEL +} dap_network_monitor_notification_type_t; + + +typedef struct { + dap_network_monitor_notification_type_t type; + union { + struct { + char interface_name[IF_NAMESIZE]; + char s_ip[MAX_IP_STR_LEN + 1]; + uint32_t ip; // inet_ntoa(*((struct in_addr *)&ipaddr)) for cast to char* + } addr; // for IP_ADDR_ADD, IP_ADDR_REMOVE + struct { + uint64_t destination_address; // 64 bit for checking -1 like not filled variable + char s_destination_address[MAX_IP_STR_LEN + 1]; + uint64_t gateway_address; + char s_gateway_address[MAX_IP_STR_LEN + 1]; + uint8_t protocol; + uint8_t netmask; + } route; // for IP_ROUTE_ADD, IP_ROUTE_REMOVE + struct { + char interface_name[IF_NAMESIZE]; + bool is_up; + bool is_running; + } link; // for RTM_NEWLINK, RTM_DELLINK + }; +} dap_network_notification_t; + +typedef void (*dap_network_monitor_notification_callback_t) + (const dap_network_notification_t notification); + +/** + * @brief dap_network_monitor_init + * @param callback + * @details starts network monitorting + * @return 0 if successful + */ +int dap_network_monitor_init(dap_network_monitor_notification_callback_t callback); + +/** + * @brief dap_network_monitor_deinit + */ +void dap_network_monitor_deinit(void); + +#ifdef __cplusplus +} +#endif diff --git a/src/win32/dap_process_manager.c b/src/win32/dap_process_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..a052017fb3def286a3c48742e0ba70ff7478fdb0 --- /dev/null +++ b/src/win32/dap_process_manager.c @@ -0,0 +1,169 @@ +/* + Copyright (c) 2017-2019 (c) Project "DeM Labs Inc" https://github.com/demlabsinc + All rights reserved. + + This file is part of DAP (Deus Applications Prototypes) the open source project + + DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + DAP is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with any DAP based project. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <windows.h> +#include <winnt.h> +#include <winternl.h> + +#include <stdio.h> +#include <stdint.h> +#include <string.h> +#include <stdlib.h> +#include <stdbool.h> + +#include "dap_process_manager.h" +#include "dap_common.h" + +#undef LOG_TAG +#define LOG_TAG "dap_process_manager" + +/** + * @brief is_process_running Check whether the process is running + * @param[in] pid PID + * @return + */ +bool is_process_running( pid_t pid ) { + + DWORD ExitCode = 0; + + HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid ); + + if ( !hProcess ) + return false; + + if ( !GetExitCodeProcess( hProcess, &ExitCode ) || ExitCode != STILL_ACTIVE ) { + CloseHandle( hProcess ); + return false; + } + + CloseHandle( hProcess ); + + return true; +} + +/** + * @brief save_process_pid_in_file Saves process pid into file by file_path + * @param[in] file_path File path + * @return Execution result + * + * Saves process pid into file by file_path. + * If file exists he will be overwritten + */ +bool save_process_pid_in_file( const char* file_path ) +{ + FILE *fpid = fopen( file_path, "wb" ); + + if ( fpid == NULL ) { + log_it( L_ERROR, "Cant create/open file by path %s",file_path ); + return false; + } + + fprintf( fpid, "%u", GetCurrentProcessId() ); + fclose( fpid ); + + return true; +} + +/** + * @brief get_pid_from_file File must consist only PID. Return 0 if file is clear. + * @param[in] file_path File path + * @return Execution result + */ +pid_t get_pid_from_file( const char* file_path ) { + + FILE *fpid = fopen( file_path, "rb"); + + if ( fpid == NULL ) { + log_it( L_ERROR, "Cant create/open file by path %s", file_path ); + return false; + } + + pid_t f_pid = 0; + + fscanf( fpid, "%u", &f_pid ); + fclose( fpid ); + + return f_pid; +} + +/** + * @brief daemonize_process Demonizes current process and exit from program + * @return + */ +bool daemonize_process( ) { + + STARTUPINFO start_info; + PROCESS_INFORMATION proc_info; + char fn_exe[256]; + DWORD status; + + memset( &start_info, 0, sizeof(STARTUPINFO) ); + memset( &proc_info, 0, sizeof(PROCESS_INFORMATION) ); + memset( &fn_exe[0], 0, 256 ); + + status = GetModuleFileName( NULL, fn_exe, sizeof(fn_exe) ); + + if ( !status || status == sizeof(fn_exe) ) { + return false; + } + + GetStartupInfo( &start_info ); + + if ( CreateProcess(fn_exe, NULL, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &start_info, &proc_info) ) { + + CloseHandle( proc_info.hThread ); + CloseHandle( proc_info.hProcess ); + ExitProcess( 0 ); + } + + return false; +} + +/** + * @brief kill_process Sends SIGKILL to process + * @param[in] pid + * @return + */ +bool kill_process( pid_t pid ) { + + DWORD ExitCode; + bool rezult = false; + + HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE, FALSE, pid ); + + if ( !hProcess ) { + + return false; + } + + if ( !GetExitCodeProcess( hProcess, &ExitCode ) ) { + + return false; + CloseHandle( hProcess ); + } + + if ( ExitCode == STILL_ACTIVE ) { + rezult = TerminateProcess( hProcess, 0 ); + } + + CloseHandle( hProcess ); + + return rezult; +} diff --git a/src/win32/dap_process_manager.h b/src/win32/dap_process_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..4627c84f0a8062dfd734d8835d5f326b042410fb --- /dev/null +++ b/src/win32/dap_process_manager.h @@ -0,0 +1,21 @@ + +#include <stdbool.h> +#include <unistd.h> +#include <stdint.h> + +/* Saves process pid into file by file_path. + * If file exists he will be overwritten */ +extern bool save_process_pid_in_file( const char* file_path ); + +/* File must consist only PID. Return 0 if file is clear. */ +extern pid_t get_pid_from_file( const char* file_path ); + +/* Return true if process running */ +extern bool is_process_running( pid_t pid ); + +/* Demonizes current process and exit from program */ +extern bool daemonize_process( void ); + +/* Sends SIGKILL to process */ +extern bool kill_process( pid_t pid ); + diff --git a/src/win32/dap_process_memory.c b/src/win32/dap_process_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..d57db9e9a3c323443a884a02dc040c26aeb74f86 --- /dev/null +++ b/src/win32/dap_process_memory.c @@ -0,0 +1,64 @@ +/* + Copyright (c) 2017-2019 (c) Project "DeM Labs Inc" https://github.com/demlabsinc + All rights reserved. + + This file is part of DAP (Deus Applications Prototypes) the open source project + + DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + DAP is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with any DAP based project. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <windows.h> +#include <winnt.h> +#include <winternl.h> +#include <stdint.h> +#include <pdh.h> +#include <stdio.h> +#include <psapi.h> + +#include "dap_process_memory.h" +#include "dap_common.h" + +#define LOG_TAG "dap_process_mem" + +static dap_process_memory_t _get_process_memory( uint32_t pid ) +{ + HANDLE hProcess; + PROCESS_MEMORY_COUNTERS pmc; + dap_process_memory_t proc_mem = { 0, 0 }; + + hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid ); + if ( !hProcess ) + return proc_mem; + + if ( !GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) { + CloseHandle( hProcess ); + return proc_mem; + } + + proc_mem.vsz = pmc.PagefileUsage; + proc_mem.rss = pmc.WorkingSetSize; + + CloseHandle( hProcess ); + return proc_mem; +} + +dap_process_memory_t get_proc_mem_current( void ) +{ + return _get_process_memory( GetCurrentProcessId() ); +} + +dap_process_memory_t get_proc_mem_by_pid( uint32_t pid ) +{ + return _get_process_memory( pid ); +} diff --git a/src/win32/dap_process_memory.h b/src/win32/dap_process_memory.h new file mode 100644 index 0000000000000000000000000000000000000000..d2f13c86a851a6e9654d6317ff16454d283bef26 --- /dev/null +++ b/src/win32/dap_process_memory.h @@ -0,0 +1,23 @@ + +//#include <stdint.h> +//#include <sys/types.h> + + +typedef struct dap_process_memory { + size_t vsz; // virtual memory (kb) + size_t rss; // physical memory (kb) +} dap_process_memory_t; + + +/** + * @brief get_proc_mem_current Get information about the amount of RAM consumed for the current process + * @return + */ +dap_process_memory_t get_proc_mem_current(void); + +/** + * @brief get_proc_mem_by_pid Obtain information about the amount of RAM consumed for a particular process + * @param[in] pid PID + * @return + */ +dap_process_memory_t get_proc_mem_by_pid( uint32_t pid );