id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
16,095
input.cpp
AutoHotkey_AutoHotkey/source/lib/input.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" #include "application.h" /////////// // Input // /////////// ResultType input_type::Setup(LPCTSTR aOptions, LPCTSTR aEndKeys, LPCTSTR aMatchList) { ParseOptions(aOptions); if (!SetKeyFlags(aEndKeys)) return FAIL; if (!SetMatchList(aMatchList)) return FAIL; // For maintainability/simplicity/code size, it's allocated even if BufferLengthMax == 0. if ( !(Buffer = tmalloc(BufferLengthMax + 1)) ) return MemoryError(); *Buffer = '\0'; return OK; } void InputStart(input_type &input) { ASSERT(!input.InProgress()); // Keep the object alive while it is active, even if the script discards it. // The corresponding Release() is done when g_input is reset by InputRelease(). if (input.ScriptObject) input.ScriptObject->AddRef(); // Set or update the timeout timer if needed. The timer proc takes care to end // only those inputs which are due, and will reset or kill the timer as needed. if (input.Timeout > 0) input.SetTimeoutTimer(); // It is possible for &input to already be in the list if AHK_INPUT_END is still // in the message queue, in which case it must be removed from its current position // to prevent the list from looping back on itself. InputUnlinkIfStopped(&input); input.Prev = g_input; input.Start(); g_input = &input; // Signal the hook to start the input. if (input.BeforeHotkeys) ++g_inputBeforeHotkeysCount; Hotkey::InstallKeybdHook(); // Install the hook (if needed). } void input_type::ParseOptions(LPCTSTR aOptions) { for (auto cp = aOptions; *cp; ++cp) { switch(ctoupper(*cp)) { case 'B': BackspaceIsUndo = false; break; case 'C': CaseSensitive = true; break; case 'H': BeforeHotkeys = true; break; case 'I': MinSendLevel = (cp[1] <= '9' && cp[1] >= '0') ? (SendLevelType)_ttoi(cp + 1) : 1; break; case 'M': TranscribeModifiedKeys = true; break; case 'L': // Use atoi() vs. ATOI() to avoid interpreting something like 0x01C as hex // when in fact the C was meant to be an option letter: BufferLengthMax = _ttoi(cp + 1); if (BufferLengthMax < 0) BufferLengthMax = 0; break; case 'T': // Although ATOF() supports hex, it's been documented in the help file that hex should // not be used (see comment above) so if someone does it anyway, some option letters // might be misinterpreted: Timeout = (int)(ATOF(cp + 1) * 1000); break; case 'V': VisibleText = true; VisibleNonText = true; break; case '*': FindAnywhere = true; break; case 'E': // Interpret single-character keys as characters rather than converting them to VK codes. // This tends to work better when using multiple keyboard layouts, but changes behaviour: // for instance, an end char of "." cannot be triggered while holding Alt. EndCharMode = true; break; } } } void input_type::SetTimeoutTimer() { DWORD now = GetTickCount(); TimeoutAt = now + Timeout; if (!g_InputTimerExists || Timeout < int(g_InputTimeoutAt - now)) SET_INPUT_TIMER(Timeout, TimeoutAt) } ResultType input_type::SetKeyFlags(LPCTSTR aKeys, bool aEndKeyMode, UCHAR aFlagsRemove, UCHAR aFlagsAdd) { bool vk_by_number, sc_by_number; vk_type vk; sc_type sc = 0; modLR_type modifiersLR; size_t key_text_length; UINT single_char_count = 0; TCHAR single_char_string[2], key_text[32]; single_char_string[1] = '\0'; // Init its second character once, since the loop only changes the first char. const bool endchar_mode = aEndKeyMode && EndCharMode; UCHAR * const end_vk = KeyVK; UCHAR * const end_sc = KeySC; for (auto end_key = aKeys; *end_key; ++end_key) // This a modified version of the processing loop used in SendKeys(). { vk = 0; // Set default. Not strictly necessary but more maintainable. *single_char_string = '\0'; // Set default as "this key name is not a single-char string". switch (*end_key) { case '}': continue; // Important that these be ignored. case '{': { ++end_key; auto end_pos = _tcschr(end_key, '}'); if (!end_pos) continue; // Do nothing, just ignore the unclosed '{' and continue. if ( !(key_text_length = end_pos - end_key) ) { if (end_pos[1] == '}') // The string "{}}" has been encountered, which is interpreted as a single "}". { ++end_pos; key_text_length = 1; } else // Empty braces {} were encountered. continue; // do nothing: let it proceed to the }, which will then be ignored. } if (key_text_length == 1) // A single-char key name, such as {.} or {{}. { if (endchar_mode) // Handle this single-char key name by char code, not by VK. { // Although it might be sometimes useful to treat "x" as a character and "{x}" as a key, // "{{}" and "{}}" can't be included without the extra braces. {vkNN} can still be used // to handle the key by VK instead of by character. single_char_count++; continue; // It will be processed by another section. } *single_char_string = *end_key; // Only used when vk != 0. } tmemcpy(key_text, end_key, key_text_length); // Make a null-terminated copy. key_text[key_text_length] = '\0'; sc_by_number = false; // Set default. modifiersLR = 0; // Init prior to below. // Handle the key by VK if it was given by number, such as {vk26}. // Otherwise, for any key name which has a VK shared by two possible SCs // (such as Up and NumpadUp), handle it by SC so it's identified correctly. if (vk = TextToVK(key_text, &modifiersLR, true)) { vk_by_number = ctoupper(key_text[0]) == 'V' && ctoupper(key_text[1]) == 'K'; if (!vk_by_number && (sc = vk_to_sc(vk, true))) { sc ^= 0x100; // Convert sc to the primary scan code, which is the one named by end_key. vk = 0; // Handle it only by SC. } } else // No virtual key, so try to find a scan code. sc = TextToSC(key_text, &sc_by_number); end_key = end_pos; // In prep for ++end_key at the top of the loop. break; // Break out of the switch() and do the vk handling beneath it (if there is a vk). } default: if (endchar_mode) { single_char_count++; continue; // It will be processed by another section. } *single_char_string = *end_key; modifiersLR = 0; // Init prior to below. vk = TextToVK(single_char_string, &modifiersLR, true); vk_by_number = false; sc_by_number = false; } // switch() if (vk) // A valid virtual key code was discovered above. { // Insist the shift key be down to form genuinely different symbols -- // namely punctuation marks -- but not for alphabetic chars. if (*single_char_string && aEndKeyMode && !IsCharAlpha(*single_char_string)) // v1.0.46.05: Added check for "*single_char_string" so that non-single-char strings like {F9} work as end keys even when the Shift key is being held down (this fixes the behavior to be like it was in pre-v1.0.45). { // Now we know it's not alphabetic, and it's not a key whose name // is longer than one char such as a function key or numpad number. // That leaves mostly just the number keys (top row) and all // punctuation chars, which are the ones that we want to be // distinguished between shifted and unshifted: if (modifiersLR & (MOD_LSHIFT | MOD_RSHIFT)) end_vk[vk] |= END_KEY_WITH_SHIFT; else end_vk[vk] |= END_KEY_WITHOUT_SHIFT; } else { end_vk[vk] = (end_vk[vk] & ~aFlagsRemove) | aFlagsAdd; // Apply flag removal to this key's SC as well. This is primarily // to support combinations like {All} +E, {LCtrl}{RCtrl} -E. sc_type temp_sc; if (aFlagsRemove && !vk_by_number && (temp_sc = vk_to_sc(vk))) { end_sc[temp_sc] &= ~aFlagsRemove; // But apply aFlagsAdd only by VK. // Since aFlagsRemove implies ScriptObject != NULL and !vk_by_number // was also checked, that implies vk_to_sc(vk, true) was already called // and did not find a secondary SC. } } } if (sc || sc_by_number) // Fixed for v1.1.33.02: Allow sc000 for setting/unsetting flags for any events that lack a scan code. { end_sc[sc] = (end_sc[sc] & ~aFlagsRemove) | aFlagsAdd; // If specified by name, apply flag removal to this key's VK as well. if (aFlagsRemove && !sc_by_number && (vk = sc_to_vk(sc))) end_vk[vk] &= ~aFlagsRemove; } } // for() if (single_char_count) // See single_char_count++ above for comments. { if (single_char_count > EndCharsMax) { // Allocate a bigger buffer. if (EndCharsMax) // If zero, EndChars may point to static memory. free(EndChars); if ( !(EndChars = tmalloc(single_char_count + 1)) ) return MemoryError(); EndCharsMax = single_char_count; } TCHAR *dst = EndChars; for (auto src = aKeys; *src; ++src) { switch (*src) { case '{': if (auto end_pos = _tcschr(src + 1, '}')) { if (end_pos == src + 1 && end_pos[1] == '}') // {}} end_pos++; if (end_pos == src + 2) *dst++ = src[1]; // Copy the single character from between the braces. src = end_pos; // Skip '{key'. Loop does ++src to skip the '}'. } // Otherwise, just ignore the '{'. case '}': continue; } *dst++ = *src; } ASSERT(dst > EndChars); *dst = '\0'; } else if (aEndKeyMode) // single_char_count is false { if (EndCharsMax) *EndChars = '\0'; else EndChars = _T(""); } return OK; } ResultType input_type::SetMatchList(LPCTSTR aMatchList) { LPTSTR *realloc_temp; // Needed since realloc returns NULL on failure but leaves original block allocated. MatchCount = 0; // Set default. if (*aMatchList) { // If needed, create the array of pointers that points into MatchBuf to each match phrase: if (!match) { if ( !(match = (LPTSTR *)malloc(INPUT_ARRAY_BLOCK_SIZE * sizeof(LPTSTR))) ) return MemoryError(); // Short msg. since so rare. MatchCountMax = INPUT_ARRAY_BLOCK_SIZE; } // If needed, create or enlarge the buffer that contains all the match phrases: size_t space_needed = _tcslen(aMatchList) + 1; // +1 for the final zero terminator. if (space_needed > MatchBufSize) { MatchBufSize = (UINT)(space_needed > 4096 ? space_needed : 4096); if (MatchBuf) // free the old one since it's too small. free(MatchBuf); if ( !(MatchBuf = tmalloc(MatchBufSize)) ) { MatchBufSize = 0; return MemoryError(); // Short msg. since so rare. } } // Copy aMatchList into the match buffer: auto source = aMatchList; auto dest = match[MatchCount] = MatchBuf; for (; *source; ++source) { if (*source != ',') // Not a comma, so just copy it over. { *dest++ = *source; continue; } // Otherwise: it's a comma, which becomes the terminator of the previous key phrase unless // it's a double comma, in which case it's considered to be part of the previous phrase // rather than the next. if (*(source + 1) == ',') // double comma { *dest++ = *source; ++source; // Omit the second comma of the pair, i.e. each pair becomes a single literal comma. continue; } // Otherwise, this is a delimiting comma. *dest = '\0'; // If the previous item is blank -- which I think can only happen now if the MatchList // begins with an orphaned comma (since two adjacent commas resolve to one literal comma) // -- don't add it to the match list: if (*match[MatchCount]) { ++MatchCount; match[MatchCount] = ++dest; *dest = '\0'; // Init to prevent crash on orphaned comma such as "btw,otoh," } if (*(source + 1)) // There is a next element. { if (MatchCount >= MatchCountMax - 1) // Rarely needed, so just realloc() to expand. { // Expand the array by one block: if ( !(realloc_temp = (LPTSTR *)realloc(match // Must use a temp variable. , (MatchCountMax + INPUT_ARRAY_BLOCK_SIZE) * sizeof(LPTSTR))) ) return MemoryError(); // Short msg. since so rare. match = realloc_temp; MatchCountMax += INPUT_ARRAY_BLOCK_SIZE; } } } // for() *dest = '\0'; // Terminate the last item. // This check is necessary for only a single isolated case: When the match list // consists of nothing except a single comma. See above comment for details: if (*match[MatchCount]) // i.e. omit empty strings from the match list. ++MatchCount; } return OK; } LPTSTR input_type::GetEndReason(LPTSTR aKeyBuf, int aKeyBufSize) { switch (Status) { case INPUT_TIMED_OUT: return _T("Timeout"); case INPUT_TERMINATED_BY_MATCH: return _T("Match"); case INPUT_TERMINATED_BY_ENDKEY: { LPTSTR key_name = aKeyBuf; if (!key_name) return _T("EndKey"); if (EndingChar) { key_name[0] = EndingChar; key_name[1] = '\0'; } else if (EndingRequiredShift) { // Since the only way a shift key can be required in our case is if it's a key whose name // is a single char (such as a shifted punctuation mark), use a diff. method to look up the // key name based on fact that the shift key was down to terminate the input. We also know // that the key is an EndingVK because there's no way for the shift key to have been // required by a scan code based on the logic (above) that builds the end_key arrays. // MSDN: "Typically, ToAscii performs the translation based on the virtual-key code. // In some cases, however, bit 15 of the uScanCode parameter may be used to distinguish // between a key press and a key release. The scan code is used for translating ALT+ // number key combinations. BYTE state[256] = { 0 }; state[VK_SHIFT] |= 0x80; // Indicate that the neutral shift key is down for conversion purposes. Get_active_window_keybd_layout // Defines the variable active_window_keybd_layout for use below. int count = ToUnicodeOrAsciiEx(EndingVK, vk_to_sc(EndingVK), (PBYTE)&state // Nothing is done about ToAsciiEx's dead key side-effects here because it seems to rare to be worth it (assuming its even a problem). , key_name, g_MenuIsVisible ? 1 : 0, active_window_keybd_layout); // v1.0.44.03: Changed to call ToAsciiEx() so that active window's layout can be specified (see hook.cpp for details). key_name[count] = '\0'; // Terminate the string. } else { *key_name = '\0'; if (EndingBySC) SCtoKeyName(EndingSC, key_name, aKeyBufSize, false); if (!*key_name) VKtoKeyName(EndingVK, key_name, aKeyBufSize, !EndingBySC); if (!*key_name) sntprintf(key_name, aKeyBufSize, _T("sc%03X"), EndingSC); } return _T("EndKey"); } case INPUT_LIMIT_REACHED: return _T("Max"); case INPUT_OFF: return _T("Stopped"); default: // In progress. return _T(""); } } void input_type::Start() { ASSERT(!InProgress()); Status = INPUT_IN_PROGRESS; } void input_type::EndByMatch(UINT aMatchIndex) { ASSERT(InProgress()); EndingMatchIndex = aMatchIndex; EndByReason(INPUT_TERMINATED_BY_MATCH); } void input_type::EndByKey(vk_type aVK, sc_type aSC, bool aBySC, bool aRequiredShift) { ASSERT(InProgress()); EndingVK = aVK; EndingSC = aSC; EndingBySC = aBySC; EndingRequiredShift = aRequiredShift; EndingChar = 0; // Must be zero if the above are to be used. EndByReason(INPUT_TERMINATED_BY_ENDKEY); } void input_type::EndByChar(TCHAR aChar) { ASSERT(aChar && InProgress()); EndingChar = aChar; // The other EndKey related fields are ignored when Char is non-zero. EndByReason(INPUT_TERMINATED_BY_ENDKEY); } void input_type::EndByReason(InputStatusType aReason) { ASSERT(InProgress()); EndingMods = g_modifiersLR_logical; // Not relevant to all end reasons, but might be useful anyway. Status = aReason; if (BeforeHotkeys) --g_inputBeforeHotkeysCount; // It's done this way rather than calling InputRelease() directly... // ...so that we can rely on MsgSleep() to create a new thread for the OnEnd event. // ...because InputRelease() can't be called by the hook thread. // ...because some callers rely on the list not being broken by this call. PostMessage(g_hWnd, AHK_INPUT_END, (WPARAM)this, 0); } input_type **InputFindLink(input_type *aInput) { if (g_input == aInput) return &g_input; else for (auto *input = g_input; input; input = input->Prev) if (input->Prev == aInput) return &input->Prev; return NULL; // aInput is not valid (faked AHK_INPUT_END message?) or not active. } input_type *InputUnlinkIfStopped(input_type *aInput) { if (!aInput) return NULL; input_type **found = InputFindLink(aInput); if (!found) return NULL; // InProgress can be true if Start() is called while AHK_INPUT_END is in the queue. // In such cases, aInput was already moved to a new position in the list and must // not be removed yet. if (!aInput->InProgress()) { *found = aInput->Prev; WaitHookIdle(); // Ensure any pending use of aInput by the hook is finished. aInput->Prev = NULL; } return aInput; // Return non-null to indicate aInput was found in the list and is therefore valid. } input_type *InputRelease(input_type *aInput) { if (!InputUnlinkIfStopped(aInput)) return NULL; if (aInput->ScriptObject) { Hotkey::MaybeUninstallHook(); if (aInput->ScriptObject->onEnd) return aInput; // Return for caller to call OnEnd and Release. aInput->ScriptObject->Release(); // The following is not done because this Release() is only to counteract an AddRef() in // InputStart(). ScriptObject != NULL indicates this input_type is actually embedded in // the InputObject and as such the link should never be broken until both are deleted. //aInput->ScriptObject = NULL; g_script.ExitIfNotPersistent(EXIT_EXIT); // In case this InputHook was the only thing keeping the script running. } return NULL; } input_type *InputFind(InputObject *object) { for (auto *input = g_input; input; input = input->Prev) if (input->ScriptObject == object) return input; return NULL; }
18,418
C++
.cpp
501
33.447106
294
0.684458
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,096
Gui.TreeView.cpp
AutoHotkey_AutoHotkey/source/lib/Gui.TreeView.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "script_gui.h" #include "script_func_impl.h" #define CTRL_THROW_IF_DESTROYED if (!hwnd) return ControlDestroyedError() FResult ControlDestroyedError(); FResult GuiControlType::TV_AddModify(bool add_mode, UINT_PTR aItemID, UINT_PTR aParentItemID, optl<StrArg> aOptions, optl<StrArg> aName, UINT_PTR &aRetVal) // TV.Add(): // Returns the HTREEITEM of the item on success, zero on failure. // Parameters: // 1: Text/name of item. // 2: Parent of item. // 3: Options. // TV.Modify(): // Returns the HTREEITEM of the item on success (to allow nested calls in script, zero on failure or partial failure. // Parameters: // 1: ID of item to modify. // 2: Options. // 3: New name. { CTRL_THROW_IF_DESTROYED; GuiControlType &control = *this; // Since above didn't return, this is TV.Add() or TV.Modify(). TVINSERTSTRUCT tvi; // It contains a TVITEMEX, which is okay even if MSIE pre-4.0 on Win95/NT because those OSes will simply never access the new/bottommost item in the struct. // Suppress any events raised by the changes made below: control.attrib |= GUI_CONTROL_ATTRIB_SUPPRESS_EVENTS; if (add_mode) // TV.Add() { tvi.hParent = (HTREEITEM)aParentItemID; tvi.hInsertAfter = TVI_LAST; // i.e. default is to insert the new item underneath the bottommost sibling. } else // TV.Modify() { // NOTE: Must allow hitem==0 for TV.Modify, at least for the Sort option, because otherwise there would // be no way to sort the root-level items. tvi.item.hItem = (HTREEITEM)aItemID; aRetVal = (UINT_PTR)tvi.item.hItem; // In all cases, return the item ID. if (!aOptions.has_value() && !aName.has_value()) // In one-parameter mode, simply select the item. { TreeView_SelectItem(control.hwnd, tvi.item.hItem); control.attrib &= ~GUI_CONTROL_ATTRIB_SUPPRESS_EVENTS; // Re-enable events. return OK; } } // Set defaults prior to options-parsing, to cover all omitted defaults: tvi.item.mask = TVIF_STATE; // TVIF_STATE: The state and stateMask members are valid (all other members are ignored). tvi.item.stateMask = 0; // All bits in "state" below are ignored unless the corresponding bit is present here in the mask. tvi.item.state = 0; // It seems tvi.item.cChildren is typically maintained by the control, though one exception is I_CHILDRENCALLBACK // and TVN_GETDISPINFO as mentioned at MSDN. DWORD select_flag = 0; bool ensure_visible = false, ensure_visible_first = false; // Parse list of space-delimited options: auto options = aOptions.value_or_empty(); TCHAR option_word[16]; // Enough for any single option word or number, with room to avoid false positives due to truncation. LPCTSTR next_option, option_end; UINT_PTR option_uint; bool adding; // Whether this option is being added (+) or removed (-). for (next_option = options; *next_option; next_option = omit_leading_whitespace(option_end)) { if (*next_option == '-') { adding = false; // omit_leading_whitespace() is not called, which enforces the fact that the option word must // immediately follow the +/- sign. This is done to allow the flexibility to have options // omit the plus/minus sign, and also to reserve more flexibility for future option formats. ++next_option; // Point it to the option word itself. } else { // Assume option is being added in the absence of either sign. However, when we were // called by GuiControl(), the first option in the list must begin with +/- otherwise the cmd // would never have been properly detected as GUICONTROL_CMD_OPTIONS in the first place. adding = true; if (*next_option == '+') ++next_option; // Point it to the option word itself. //else do not increment, under the assumption that the plus has been omitted from a valid // option word and is thus an implicit plus. } if (!*next_option) // In case the entire option string ends in a naked + or -. break; // Find the end of this option item: for (option_end = next_option; *option_end && !IS_SPACE_OR_TAB(*option_end); ++option_end); if (option_end == next_option) continue; // i.e. the string contains a + or - with a space or tab after it, which is intentionally ignored. // if ((option_end[-1] == '1' || option_end[-1] == '0') && ) // Make a copy to simplify comparisons below. tcslcpy(option_word, next_option, min((option_end - next_option) + 1, _countof(option_word))); if (!_tcsicmp(option_word, _T("Select"))) // Could further allow "ed" suffix by checking for that inside, but "Selected" is getting long so it doesn't seem something many would want to use. { // Selection of an item apparently needs to be done via message for the control to update itself // properly. Otherwise, single-select isn't enforced via de-selecting previous item and the newly // selected item isn't revealed/shown. There may be other side-effects. if (adding) select_flag = TVGN_CARET; //else since "de-select" is not a supported action, no need to support "-Select". // Furthermore, since a TreeView is by its nature has only one item selected at a time, it seems // unnecessary to support Select%VarContainingOneOrZero%. This is because it seems easier for a // script to simply load the Tree then select the desired item afterward. } else if (!_tcsicmp(option_word, _T("Vis"))) { // Since this option much more typically used with TV.Modify than TV.Add, the technique of // Vis%VarContainingOneOrZero% isn't supported, to reduce code size. ensure_visible = adding; } else if (!_tcsicmp(option_word, _T("VisFirst"))) { ensure_visible_first = adding; } else if (!_tcsnicmp(option_word, _T("Bold"), 4)) { next_option += 4; if (next_option < option_end && !ATOI(next_option)) // If it's Bold0, invert the mode. adding = !adding; tvi.item.stateMask |= TVIS_BOLD; if (adding) tvi.item.state |= TVIS_BOLD; //else removing, so the fact that this TVIS flag has just been added to the stateMask above // but is absent from item.state should remove this attribute from the item. } else if (!_tcsnicmp(option_word, _T("Expand"), 6)) { next_option += 6; if (next_option < option_end && !ATOI(next_option)) // If it's Expand0, invert the mode to become "collapse". adding = !adding; if (add_mode) { if (adding) { // Don't expand via msg because it won't work: since the item is being newly added // now, by definition it doesn't have any children, and testing shows that sending // the expand message has no effect, but setting the state bit does: tvi.item.stateMask |= TVIS_EXPANDED; tvi.item.state |= TVIS_EXPANDED; // Since the script is deliberately expanding the item, it seems best not to send the // TVN_ITEMEXPANDING/-ED messages because: // 1) Sending TVN_ITEMEXPANDED without first sending a TVN_ITEMEXPANDING message might // decrease maintainability, and possibly even produce unwanted side-effects. // 2) Code size and performance (avoids generating extra message traffic). } //else removing, so nothing needs to be done because "collapsed" is the default state // of a TV item upon creation. } else // TV.Modify(): Expand and collapse both require a message to work properly on an existing item. // Strangely, this generates a notification sometimes (such as the first time) but not for subsequent // expands/collapses of that same item. Also, TVE_TOGGLE is not currently supported because it seems // like it would be too rarely used. TreeView_Expand(control.hwnd, tvi.item.hItem, adding ? TVE_EXPAND : TVE_COLLAPSE); } else if (!_tcsnicmp(option_word, _T("Check"), 5)) { // The rationale for not checking for an optional "ed" suffix here and incrementing next_option by 2 // is that: 1) It would be inconsistent with the lack of support for "selected" (see reason above); // 2) Checkboxes in a ListView are fairly rarely used, so code size reduction might be more important. next_option += 5; if (next_option < option_end && !ATOI(next_option)) // If it's Check0, invert the mode to become "unchecked". adding = !adding; //else removing, so the fact that this TVIS flag has just been added to the stateMask above // but is absent from item.state should remove this attribute from the item. tvi.item.stateMask |= TVIS_STATEIMAGEMASK; // Unlike ListViews, Tree checkmarks can be applied in the same step as creating a Tree item. tvi.item.state |= adding ? 0x2000 : 0x1000; // The #1 image is "unchecked" and the #2 is "checked". } else if (!_tcsnicmp(option_word, _T("Icon"), 4)) { if (adding) { // To me, having a different icon for when the item is selected seems rarely used. After all, // its obvious the item is selected because it's highlighted (unless it lacks a name?) So this // policy makes things easier for scripts that don't want to distinguish. If ever it is needed, // new options such as IconSel and IconUnsel can be added. tvi.item.mask |= TVIF_IMAGE|TVIF_SELECTEDIMAGE; tvi.item.iSelectedImage = tvi.item.iImage = ATOI(next_option + 4) - 1; // -1 to convert to zero-based. } //else removal of icon currently not supported (see comment above), so do nothing in order // to reserve "-Icon" in case a future way can be found to do it. } else if (!_tcsicmp(option_word, _T("Sort"))) { if (add_mode) tvi.hInsertAfter = TVI_SORT; // For simplicity, the value of "adding" is ignored. else // Somewhat debatable, but it seems best to report failure via the return value even though // failure probably only occurs when the item has no children, and the script probably // doesn't often care about such failures. It does result in the loss of the HTREEITEM return // value, but even if that call is nested in another, the zero should produce no effect in most cases. TreeView_SortChildren(control.hwnd, tvi.item.hItem, FALSE); // Best default seems no-recurse, since typically this is used after a user edits merely a single item. } // MUST BE LISTED LAST DUE TO "ELSE IF": Options valid only for TV.Add(). else if (add_mode && !_tcsicmp(option_word, _T("First"))) { tvi.hInsertAfter = TVI_FIRST; // For simplicity, the value of "adding" is ignored. } else if (add_mode && ParsePositiveInteger(option_word, option_uint)) { tvi.hInsertAfter = (HTREEITEM)option_uint; } else { control.attrib &= ~GUI_CONTROL_ATTRIB_SUPPRESS_EVENTS; // Re-enable events. return FValueError(ERR_INVALID_OPTION, option_word); } } // For TV.Modify(), an explicit empty string is allowed for aName, which sets it to a blank value. // By contrast, if the param is omitted, the name is left unchanged. if (aName.has_value()) { tvi.item.pszText = const_cast<LPTSTR>(aName.value_or_empty()); tvi.item.mask |= TVIF_TEXT; } if (add_mode) // TV.Add() { tvi.item.hItem = TreeView_InsertItem(control.hwnd, &tvi); // Update tvi.item.hItem for convenience/maint. It's for use in later sections because retval is overridden to be zero for partial failure in modify-mode. aRetVal = (UINT_PTR)tvi.item.hItem; // Set return value. } else // TV.Modify() { if (tvi.item.mask != LVIF_STATE || tvi.item.stateMask) // An item's property or one of the state bits needs changing. TreeView_SetItem(control.hwnd, &tvi.itemex); } if (ensure_visible) // Seems best to do this one prior to "select" below. SendMessage(control.hwnd, TVM_ENSUREVISIBLE, 0, (LPARAM)tvi.item.hItem); // Return value is ignored in this case, since its definition seems a little weird. if (ensure_visible_first) // Seems best to do this one prior to "select" below. TreeView_Select(control.hwnd, tvi.item.hItem, TVGN_FIRSTVISIBLE); // Return value is also ignored due to rarity, code size, and because most people wouldn't care about a failure even if for some reason it failed. if (select_flag) TreeView_Select(control.hwnd, tvi.item.hItem, select_flag); control.attrib &= ~GUI_CONTROL_ATTRIB_SUPPRESS_EVENTS; // Re-enable events. return OK; } FResult GuiControlType::TV_Delete(optl<UINT_PTR> aItemID) { CTRL_THROW_IF_DESTROYED; // If param #1 is present but is zero, for safety it seems best not to do a delete-all (in case a // script bug is so rare that it is never caught until the script is distributed). Another reason // is that a script might do something like TV.Delete(TV.GetSelection()), which would be desired // to fail not delete-all if there's ever any way for there to be no selection. if (aItemID.has_value() && aItemID.value() == 0) return FR_E_ARG(0); if (!SendMessage(hwnd, TVM_DELETEITEM, 0, aItemID.value_or(NULL))) return FR_E_FAILED; // Invalid parameter? return OK; } HTREEITEM GetNextTreeItem(HWND aTreeHwnd, HTREEITEM aItem) // Helper function for others below. // If aItem is NULL, caller wants topmost ROOT item returned. // Otherwise, the next child, sibling, or parent's sibling is returned in a manner that allows the caller // to traverse every item in the tree easily. { if (!aItem) return TreeView_GetRoot(aTreeHwnd); // Otherwise, do depth-first recursion. Must be done in the following order to allow full traversal: // Children first. // Then siblings. // Then parent's sibling(s). HTREEITEM hitem; if (hitem = TreeView_GetChild(aTreeHwnd, aItem)) return hitem; if (hitem = TreeView_GetNextSibling(aTreeHwnd, aItem)) return hitem; // The last stage is trickier than the above: parent's next sibling, or if none, its parent's parent's sibling, etc. for (HTREEITEM hparent = aItem;;) { if ( !(hparent = TreeView_GetParent(aTreeHwnd, hparent)) ) // No parent, so this is a root-level item. return NULL; // There is no next item. // Now it's known there is a parent. It's not necessary to check that parent's children because that // would have been done by a prior iteration in the script. if (hitem = TreeView_GetNextSibling(aTreeHwnd, hparent)) return hitem; // Otherwise, parent has no sibling, but does its parent (and so on)? Continue looping to find out. } } FResult GuiControlType::TV_GetChild(UINT_PTR aItemID, UINT_PTR &aRetVal) { CTRL_THROW_IF_DESTROYED; aRetVal = (UINT_PTR)TreeView_GetChild(hwnd, aItemID); return OK; } FResult GuiControlType::TV_GetCount(UINT &aRetVal) { CTRL_THROW_IF_DESTROYED; aRetVal = TreeView_GetCount(hwnd); return OK; } FResult GuiControlType::TV_GetParent(UINT_PTR aItemID, UINT_PTR &aRetVal) { CTRL_THROW_IF_DESTROYED; aRetVal = (UINT_PTR)TreeView_GetParent(hwnd, aItemID); return OK; } FResult GuiControlType::TV_GetPrev(UINT_PTR aItemID, UINT_PTR &aRetVal) { CTRL_THROW_IF_DESTROYED; aRetVal = (UINT_PTR)TreeView_GetPrevSibling(hwnd, aItemID); return OK; } FResult GuiControlType::TV_GetSelection(UINT_PTR &aRetVal) { CTRL_THROW_IF_DESTROYED; aRetVal = (UINT_PTR)TreeView_GetSelection(hwnd); return OK; } FResult GuiControlType::TV_GetNext(optl<UINT_PTR> aItemID, optl<StrArg> aItemType, UINT_PTR &aRetVal) { CTRL_THROW_IF_DESTROYED; HTREEITEM hitem = (HTREEITEM)aItemID.value_or(NULL); if (!aItemType.has_value()) { aRetVal = (UINT_PTR)SendMessage(hwnd, TVM_GETNEXTITEM, hitem ? TVGN_NEXT : TVGN_ROOT, (LPARAM)hitem); // Above: It seems best to treat hitem==0 as "get root", even though it sacrifices some error detection, // because not doing so would be inconsistent with the fact that TV.GetNext(0, "Full") does get the root // (which needs to be retained to make script loops to traverse entire tree easier). return OK; } // Since above didn't return, this TV.GetNext's 2-parameter mode, which has an expanded scope that includes // not just siblings, but also children and parents. This allows a tree to be traversed from top to bottom // without the script having to do something fancy. TCHAR first_char_upper = ctoupper(*omit_leading_whitespace(aItemType.value_or_empty())); bool search_checkmark; if (first_char_upper == 'C') search_checkmark = true; else if (first_char_upper == 'F') search_checkmark = false; else // Reserve other option letters/words for future use by being somewhat strict. return FR_E_ARG(1); // When an actual item was specified, search begins at the item *after* it. Otherwise (when NULL): // It's a special mode that always considers the root node first. Otherwise, there would be no way // to start the search at the very first item in the tree to find out whether it's checked or not. hitem = GetNextTreeItem(hwnd, hitem); // Handles the comment above. if (!search_checkmark) // Simple tree traversal, so just return the next item (if any). { aRetVal = (UINT_PTR)hitem; // OK if NULL. return OK; } // Otherwise, search for the next item having a checkmark. For performance, it seems best to assume that // the control has the checkbox style (the script would realistically never call it otherwise, so the // control's style isn't checked. for (; hitem; hitem = GetNextTreeItem(hwnd, hitem)) if (TreeView_GetCheckState(hwnd, hitem) == 1) // 0 means unchecked, -1 means "no checkbox image". break; aRetVal = (UINT_PTR)hitem; // OK if NULL. return OK; } // TV.Get() // Returns: Varies depending on param #2. // Parameters: // 1: HTREEITEM. // 2: Name of attribute to get. FResult GuiControlType::TV_Get(UINT_PTR aItemID, StrArg aAttribute, UINT_PTR &aRetVal) { CTRL_THROW_IF_DESTROYED; HTREEITEM hitem = (HTREEITEM)aItemID; UINT state_mask; switch (ctoupper(*omit_leading_whitespace(aAttribute))) { case 'E': state_mask = TVIS_EXPANDED; break; // Expanded case 'C': state_mask = TVIS_STATEIMAGEMASK; break; // Checked case 'B': state_mask = TVIS_BOLD; break; // Bold //case 'S' for "Selected" is not provided because TV.GetSelection() seems to cover that well enough. //case 'P' for "is item a parent?" is not provided because TV.GetChild() seems to cover that well enough. // (though it's possible that retrieving TVITEM's cChildren would perform a little better). } // Below seems to need a bit-AND with state_mask to work properly, at least on XP SP2. Otherwise, // extra bits are present such as 0x2002 for "expanded" when it's supposed to be either 0x00 or 0x20. UINT result = state_mask & (UINT)SendMessage(hwnd, TVM_GETITEMSTATE, (WPARAM)hitem, state_mask); if (state_mask == TVIS_STATEIMAGEMASK) { if (result != 0x2000) // It doesn't have a checkmark state image. hitem = 0; } else // For all others, anything non-zero means the flag is present. if (!result) // Flag not present. hitem = 0; aRetVal = (UINT_PTR)hitem; return OK; } // TV.GetText() // Returns: Text on success. // Throws on failure. // Parameters: // 1: HTREEITEM. FResult GuiControlType::TV_GetText(UINT_PTR aItemID, StrRet &aRetVal) { CTRL_THROW_IF_DESTROYED; HWND control_hwnd = hwnd; TCHAR text_buf[LV_TEXT_BUF_SIZE]; // i.e. uses same size as ListView. TVITEM tvi; tvi.hItem = (HTREEITEM)aItemID; tvi.mask = TVIF_TEXT; tvi.pszText = text_buf; tvi.cchTextMax = LV_TEXT_BUF_SIZE - 1; // -1 because of nagging doubt about size vs. length. Some MSDN examples subtract one), such as TabCtrl_GetItem()'s cchTextMax. if (SendMessage(control_hwnd, TVM_GETITEM, 0, (LPARAM)&tvi)) { // Must use tvi.pszText vs. text_buf because MSDN says: "Applications should not assume that the text will // necessarily be placed in the specified buffer. The control may instead change the pszText member // of the structure to point to the new text rather than place it in the buffer." return aRetVal.Copy(tvi.pszText) ? OK : FR_E_OUTOFMEM; } else { // On failure, it seems best to throw an exception. return FR_E_FAILED; } } FResult GuiControlType::TV_SetImageList(UINT_PTR aImageListID, optl<int> aIconType, UINT_PTR &aRetVal) // Returns (MSDN): "handle to the image list previously associated with the control if successful; NULL otherwise." // Parameters: // 1: HIMAGELIST obtained from somewhere such as IL_Create(). // 2: Optional: Type of list. { CTRL_THROW_IF_DESTROYED; HIMAGELIST himl = (HIMAGELIST)aImageListID; int list_type = aIconType.value_or(TVSIL_NORMAL); aRetVal = (UINT_PTR)TreeView_SetImageList(hwnd, himl, list_type); return OK; }
20,798
C++
.cpp
427
45.943794
214
0.728692
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,097
pixel.cpp
AutoHotkey_AutoHotkey/source/lib/pixel.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" // pre-compiled headers #include "script.h" #include "script_func_impl.h" LPCOLORREF getbits(HBITMAP ahImage, HDC hdc, LONG &aWidth, LONG &aHeight, bool &aIs16Bit, int aMinColorDepth = 8) // Helper function used by PixelSearch below. // Returns an array of pixels to the caller, which it must free when done. Returns NULL on failure, // in which case the contents of the output parameters is indeterminate. { HDC tdc = CreateCompatibleDC(hdc); if (!tdc) return NULL; // From this point on, "goto end" will assume tdc is non-NULL, but that the below // might still be NULL. Therefore, all of the following must be initialized so that the "end" // label can detect them: HGDIOBJ tdc_orig_select = NULL; LPCOLORREF image_pixel = NULL; bool success = false; // Confirmed: // Needs extra memory to prevent buffer overflow due to: "A bottom-up DIB is specified by setting // the height to a positive number, while a top-down DIB is specified by setting the height to a // negative number. THE BITMAP COLOR TABLE WILL BE APPENDED to the BITMAPINFO structure." // Maybe this applies only to negative height, in which case the second call to GetDIBits() // below uses one. struct BITMAPINFO3 { BITMAPINFOHEADER bmiHeader; RGBQUAD bmiColors[260]; // v1.0.40.10: 260 vs. 3 to allow room for color table when color depth is 8-bit or less. } bmi; bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biBitCount = 0; // i.e. "query bitmap attributes" only. if (!GetDIBits(tdc, ahImage, 0, 0, NULL, (LPBITMAPINFO)&bmi, DIB_RGB_COLORS) || bmi.bmiHeader.biBitCount < aMinColorDepth) // Relies on short-circuit boolean order. goto end; // Set output parameters for caller: aIs16Bit = (bmi.bmiHeader.biBitCount == 16); aWidth = bmi.bmiHeader.biWidth; aHeight = bmi.bmiHeader.biHeight; int image_pixel_count = aWidth * aHeight; if ( !(image_pixel = (LPCOLORREF)malloc(image_pixel_count * sizeof(COLORREF))) ) goto end; // v1.0.40.10: To preserve compatibility with callers who check for transparency in icons, don't do any // of the extra color table handling for 1-bpp images. Update: For code simplification, support only // 8-bpp images. If ever support lower color depths, use something like "bmi.bmiHeader.biBitCount > 1 // && bmi.bmiHeader.biBitCount < 9"; bool is_8bit = (bmi.bmiHeader.biBitCount == 8); if (!is_8bit) bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biHeight = -bmi.bmiHeader.biHeight; // Storing a negative inside the bmiHeader struct is a signal for GetDIBits(). // Must be done only after GetDIBits() because: "The bitmap identified by the hbmp parameter // must not be selected into a device context when the application calls GetDIBits()." // (Although testing shows it works anyway, perhaps because GetDIBits() above is being // called in its informational mode only). // Note that this seems to return NULL sometimes even though everything still works. // Perhaps that is normal. tdc_orig_select = SelectObject(tdc, ahImage); // Returns NULL when we're called the second time? // Apparently there is no need to specify DIB_PAL_COLORS below when color depth is 8-bit because // DIB_RGB_COLORS also retrieves the color indices. if ( !(GetDIBits(tdc, ahImage, 0, aHeight, image_pixel, (LPBITMAPINFO)&bmi, DIB_RGB_COLORS)) ) goto end; if (is_8bit) // This section added in v1.0.40.10. { // Convert the color indices to RGB colors by going through the array in reverse order. // Reverse order allows an in-place conversion of each 8-bit color index to its corresponding // 32-bit RGB color. LPDWORD palette = (LPDWORD)_alloca(256 * sizeof(PALETTEENTRY)); GetSystemPaletteEntries(tdc, 0, 256, (LPPALETTEENTRY)palette); // Even if failure can realistically happen, consequences of using uninitialized palette seem acceptable. // Above: GetSystemPaletteEntries() is the only approach that provided the correct palette. // The following other approaches didn't give the right one: // GetDIBits(): The palette it stores in bmi.bmiColors seems completely wrong. // GetPaletteEntries()+GetCurrentObject(hdc, OBJ_PAL): Returned only 20 entries rather than the expected 256. // GetDIBColorTable(): I think same as above or maybe it returns 0. // The following section is necessary because apparently each new row in the region starts on // a DWORD boundary. So if the number of pixels in each row isn't an exact multiple of 4, there // are between 1 and 3 zero-bytes at the end of each row. int remainder = aWidth % 4; int empty_bytes_at_end_of_each_row = remainder ? (4 - remainder) : 0; // Start at the last RGB slot and the last color index slot: BYTE *byte = (BYTE *)image_pixel + image_pixel_count - 1 + (aHeight * empty_bytes_at_end_of_each_row); // Pointer to 8-bit color indices. DWORD *pixel = image_pixel + image_pixel_count - 1; // Pointer to 32-bit RGB entries. int row, col; for (row = 0; row < aHeight; ++row) // For each row. { byte -= empty_bytes_at_end_of_each_row; for (col = 0; col < aWidth; ++col) // For each column. *pixel-- = rgb_to_bgr(palette[*byte--]); // Caller always wants RGB vs. BGR format. } } // Since above didn't "goto end", indicate success: success = true; end: if (tdc_orig_select) // i.e. the original call to SelectObject() didn't fail. SelectObject(tdc, tdc_orig_select); // Probably necessary to prevent memory leak. DeleteDC(tdc); if (!success && image_pixel) { free(image_pixel); image_pixel = NULL; } return image_pixel; } FResult PixelSearch(BOOL *aFound, ResultToken *aFoundX, ResultToken *aFoundY , int aLeft, int aTop, int aRight, int aBottom, COLORREF aColorRGB , int aVariation, LPTSTR aGetColor) // Author: The fast-mode PixelSearch was created by Aurelian Maga. { // For maintainability, get RGB/BGR conversion out of the way early. COLORREF aColorBGR = rgb_to_bgr(aColorRGB); // Many of the following sections are similar to those in ImageSearch(), so they should be // maintained together. POINT origin = {0}; CoordToScreen(origin, COORD_MODE_PIXEL); aLeft += origin.x; aTop += origin.y; aRight += origin.x; aBottom += origin.y; bool right_to_left = aLeft > aRight; bool bottom_to_top = aTop > aBottom; int left = aLeft; int top = aTop; int right = aRight; int bottom = aBottom; if (right_to_left) { left = aRight; right = aLeft; } if (bottom_to_top) { top = aBottom; bottom = aTop; } if (aVariation < 0) aVariation = 0; if (aVariation > 255) aVariation = 255; // Allow colors to vary within the spectrum of intensity, rather than having them // wrap around (which doesn't seem to make much sense). For example, if the user specified // a variation of 5, but the red component of aColorBGR is only 0x01, we don't want red_low to go // below zero, which would cause it to wrap around to a very intense red color: COLORREF pixel; // Used much further down. BYTE red, green, blue; // Used much further down. BYTE search_red, search_green, search_blue; BYTE red_low, green_low, blue_low, red_high, green_high, blue_high; if (aVariation > 0) { search_red = GetRValue(aColorBGR); search_green = GetGValue(aColorBGR); search_blue = GetBValue(aColorBGR); } //else leave uninitialized since they won't be used. HDC hdc = GetDC(NULL); if (!hdc) return FR_E_WIN32; bool found = false; // Must init here for use by "goto fast_end". // From this point on, "goto fast_end" will assume hdc is non-NULL but that the below might still be NULL. // Therefore, all of the following must be initialized so that the "fast_end" label can detect them: HDC sdc = NULL; HBITMAP hbitmap_screen = NULL; LPCOLORREF screen_pixel = NULL; HGDIOBJ sdc_orig_select = NULL; // Some explanation for the method below is contained in this quote from the newsgroups: // "you shouldn't really be getting the current bitmap from the GetDC DC. This might // have weird effects like returning the entire screen or not working. Create yourself // a memory DC first of the correct size. Then BitBlt into it and then GetDIBits on // that instead. This way, the provider of the DC (the video driver) can make sure that // the correct pixels are copied across." // Create an empty bitmap to hold all the pixels currently visible on the screen (within the search area): int search_width = right - left + 1; int search_height = bottom - top + 1; if ( !(sdc = CreateCompatibleDC(hdc)) || !(hbitmap_screen = CreateCompatibleBitmap(hdc, search_width, search_height)) ) goto fast_end; if ( !(sdc_orig_select = SelectObject(sdc, hbitmap_screen)) ) goto fast_end; // Copy the pixels in the search-area of the screen into the DC to be searched: if ( !(BitBlt(sdc, 0, 0, search_width, search_height, hdc, left, top, SRCCOPY)) ) goto fast_end; LONG screen_width, screen_height; bool screen_is_16bit; if ( !(screen_pixel = getbits(hbitmap_screen, sdc, screen_width, screen_height, screen_is_16bit)) ) goto fast_end; // Concerning 0xF8F8F8F8: "On 16bit and 15 bit color the first 5 bits in each byte are valid // (in 16bit there is an extra bit but i forgot for which color). And this will explain the // second problem [in the test script], since GetPixel even in 16bit will return some "valid" // data in the last 3bits of each byte." register int i; LONG screen_pixel_count = screen_width * screen_height; if (screen_is_16bit) for (i = 0; i < screen_pixel_count; ++i) screen_pixel[i] &= 0xF8F8F8F8; if (aGetColor) { COLORREF color = screen_pixel[0] & 0x00FFFFFF; // See other 0x00FFFFFF below for explanation. // In this case, aFoundX is a pointer to PixelGetColor's aResultToken. _stprintf(aGetColor, _T("0x%06X"), color); } else if (aVariation < 1) // Caller wants an exact match on one particular color. { if (screen_is_16bit) aColorRGB &= 0xF8F8F8F8; for (int j = 0; j < screen_pixel_count; ++j) { if (right_to_left && bottom_to_top) i = screen_pixel_count - j - 1; else if (right_to_left) i = j / screen_width * screen_width + screen_width - j % screen_width - 1; else if (bottom_to_top) i = (screen_pixel_count - j - 1) / screen_width * screen_width + j % screen_width; else i = j; // Note that screen pixels sometimes have a non-zero high-order byte. That's why // bit-and with 0x00FFFFFF is done. Otherwise, reddish/orangish colors are not properly // found: if ((screen_pixel[i] & 0x00FFFFFF) == aColorRGB) { found = true; break; } } } else { // It seems more appropriate to do the 16-bit conversion prior to SET_COLOR_RANGE, // rather than applying 0xF8 to each of the high/low values individually. if (screen_is_16bit) { search_red &= 0xF8; search_green &= 0xF8; search_blue &= 0xF8; } #define SET_COLOR_RANGE \ {\ red_low = (aVariation > search_red) ? 0 : search_red - aVariation;\ green_low = (aVariation > search_green) ? 0 : search_green - aVariation;\ blue_low = (aVariation > search_blue) ? 0 : search_blue - aVariation;\ red_high = (aVariation > 0xFF - search_red) ? 0xFF : search_red + aVariation;\ green_high = (aVariation > 0xFF - search_green) ? 0xFF : search_green + aVariation;\ blue_high = (aVariation > 0xFF - search_blue) ? 0xFF : search_blue + aVariation;\ } SET_COLOR_RANGE for (int j = 0; j < screen_pixel_count; ++j) { if (right_to_left && bottom_to_top) i = screen_pixel_count - j - 1; else if (right_to_left) i = j / screen_width * screen_width + screen_width - j % screen_width - 1; else if (bottom_to_top) i = (screen_pixel_count - j - 1) / screen_width * screen_width + j % screen_width; else i = j; // Note that screen pixels sometimes have a non-zero high-order byte. But it doesn't // matter with the below approach, since that byte is not checked in the comparison. pixel = screen_pixel[i]; red = GetBValue(pixel); // Because pixel is in RGB vs. BGR format, red is retrieved with green = GetGValue(pixel); // GetBValue() and blue is retrieved with GetRValue(). blue = GetRValue(pixel); if (red >= red_low && red <= red_high && green >= green_low && green <= green_high && blue >= blue_low && blue <= blue_high) { found = true; break; } } } fast_end: DWORD error = GetLastError(); // Might help to ensure the correct error number is thrown on failure. ReleaseDC(NULL, hdc); if (sdc) { if (sdc_orig_select) // i.e. the original call to SelectObject() didn't fail. SelectObject(sdc, sdc_orig_select); // Probably necessary to prevent memory leak. DeleteDC(sdc); } if (hbitmap_screen) DeleteObject(hbitmap_screen); if (screen_pixel) free(screen_pixel); else // One of the GDI calls failed and the search wasn't carried out. return FR_E_WIN32(error); if (aGetColor) return OK; // Return value was already set. // Otherwise, success. Calculate xpos and ypos of where the match was found and adjust // coords to make them relative to the position of the target window (rect will contain // zeroes if this doesn't need to be done): if (found) { if (aFoundX) aFoundX->SetValue((left + i%screen_width) - origin.x); if (aFoundY) aFoundY->SetValue((top + i/screen_width) - origin.y); } *aFound = found; return OK; } bif_impl FResult PixelSearch(BOOL &aFound, ResultToken *aFoundX, ResultToken *aFoundY , int aLeft, int aTop, int aRight, int aBottom, UINT aColor, optl<int> aVariation) { return PixelSearch(&aFound, aFoundX, aFoundY, aLeft, aTop, aRight, aBottom, aColor , aVariation.value_or(0), nullptr); } bif_impl FResult ImageSearch(ResultToken *aFoundX, ResultToken *aFoundY , int aLeft, int aTop, int aRight, int aBottom, StrArg aImageFile , BOOL &aRetVal) // Author: ImageSearch was created by Aurelian Maga. { // Many of the following sections are similar to those in PixelSearch(), so they should be // maintained together. // Set default results (output variables), in case of early return: //aFoundX.SetValue(_T(""), 0); // Init to empty string regardless of whether we succeed here. //aFoundY.SetValue(_T(""), 0); // Same. POINT origin = {0}; CoordToScreen(origin, COORD_MODE_PIXEL); aLeft += origin.x; aTop += origin.y; aRight += origin.x; aBottom += origin.y; // Options are done as asterisk+option to permit future expansion. // Set defaults to be possibly overridden by any specified options: int aVariation = 0; // This is named aVariation vs. variation for use with the SET_COLOR_RANGE macro. COLORREF trans_color = CLR_NONE; // The default must be a value that can't occur naturally in an image. int icon_number = 0; // Zero means "load icon or bitmap (doesn't matter)". int width = 0, height = 0; // For icons, override the default to be 16x16 because that is what is sought 99% of the time. // This new default can be overridden by explicitly specifying w0 h0: auto cp = _tcsrchr(aImageFile, '.'); if (cp) { ++cp; if (!(_tcsicmp(cp, _T("ico")) && _tcsicmp(cp, _T("exe")) && _tcsicmp(cp, _T("dll")))) width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON); } TCHAR color_name[32], *dp; cp = omit_leading_whitespace(aImageFile); // But don't alter aImageFile yet in case it contains literal whitespace we want to retain. while (*cp == '*') { ++cp; switch (_totupper(*cp)) { case 'W': width = ATOI(cp + 1); break; case 'H': height = ATOI(cp + 1); break; default: if (!_tcsnicmp(cp, _T("Icon"), 4)) { cp += 4; // Now it's the character after the word. icon_number = ATOI(cp); // LoadPicture() correctly handles any negative value. } else if (!_tcsnicmp(cp, _T("Trans"), 5)) { cp += 5; // Now it's the character after the word. // Isolate the color name/number for ColorNameToBGR(): tcslcpy(color_name, cp, _countof(color_name)); if (dp = StrChrAny(color_name, _T(" \t"))) // Find space or tab, if any. *dp = '\0'; // Fix for v1.0.44.10: Treat trans_color as containing an RGB value (not BGR) so that it matches // the documented behavior. In older versions, a specified color like "TransYellow" was wrong in // every way (inverted) and a specified numeric color like "Trans0xFFFFAA" was treated as BGR vs. RGB. trans_color = ColorNameToBGR(color_name); if (trans_color == CLR_NONE) // A matching color name was not found, so assume it's in hex format. { wchar_t *endptr; // It seems _tcstol() automatically handles the optional leading "0x" if present: trans_color = _tcstol(color_name, &endptr, 16); if (*endptr) // Not (entirely) a valid hex number. return FR_E_ARG(6); } else trans_color = bgr_to_rgb(trans_color); // v1.0.44.10: See fix/comment above. } else // Assume it's a number since that's the only other asterisk-option. { aVariation = ATOI(cp); // Seems okay to support hex via ATOI because the space after the number is documented as being mandatory. if (aVariation < 0) aVariation = 0; if (aVariation > 255) aVariation = 255; // Note: because it's possible for filenames to start with a space (even though Explorer itself // won't let you create them that way), allow exactly one space between end of option and the // filename itself: } } // switch() if ( !(cp = StrChrAny(cp, _T(" \t"))) ) // Find the first space or tab after the option. return FR_E_ARG(6); // Bad option/format. // Now it's the space or tab (if there is one) after the option letter. Advance by exactly one character // because only one space or tab is considered the delimiter. Any others are considered to be part of the // filename (though some or all OSes might simply ignore them or tolerate them as first-try match criteria). aImageFile = ++cp; // This should now point to another asterisk or the filename itself. // Above also serves to reset the filename to omit the option string whenever at least one asterisk-option is present. cp = omit_leading_whitespace(cp); // This is done to make it more tolerant of having more than one space/tab between options. } // Update: Transparency is now supported in icons by using the icon's mask. In addition, an attempt // is made to support transparency in GIF, PNG, and possibly TIF files via the *Trans option, which // assumes that one color in the image is transparent. In GIFs not loaded via GDIPlus, the transparent // color might always been seen as pure white, but when GDIPlus is used, it's probably always black // like it is in PNG -- however, this will not relied upon, at least not until confirmed. // OLDER/OBSOLETE comment kept for background: // For now, images that can't be loaded as bitmaps (icons and cursors) are not supported because most // icons have a transparent background or color present, which the image search routine here is // probably not equipped to handle (since the transparent color, when shown, typically reveals the // color of whatever is behind it; thus screen pixel color won't match image's pixel color). // So currently, only BMP and GIF seem to work reliably, though some of the other GDIPlus-supported // formats might work too. int image_type; bool no_delete_bitmap; HBITMAP hbitmap_image = LoadPicture(aImageFile, width, height, image_type, icon_number, false, &no_delete_bitmap); // The comment marked OBSOLETE below is no longer true because the elimination of the high-byte via // 0x00FFFFFF seems to have fixed it. But "true" is still not passed because that should increase // consistency when GIF/BMP/ICO files are used by a script on both Win9x and other OSs (since the // same loading method would be used via "false" for these formats across all OSes). // OBSOLETE: Must not pass "true" with the above because that causes bitmaps and gifs to be not found // by the search. In other words, nothing works. Obsolete comment: Pass "true" so that an attempt // will be made to load icons as bitmaps if GDIPlus is available. if (!hbitmap_image) return FR_E_ARG(6); HDC hdc = GetDC(NULL); if (!hdc) { DWORD error = GetLastError(); if (!no_delete_bitmap) { if (image_type == IMAGE_ICON) DestroyIcon((HICON)hbitmap_image); else DeleteObject(hbitmap_image); } return FR_E_WIN32(error); } // From this point on, "goto end" will assume hdc and hbitmap_image are non-NULL, but that the below // might still be NULL. Therefore, all of the following must be initialized so that the "end" // label can detect them: HDC sdc = NULL; HBITMAP hbitmap_screen = NULL; LPCOLORREF image_pixel = NULL, screen_pixel = NULL, image_mask = NULL; HGDIOBJ sdc_orig_select = NULL; bool found = false; // Must init here for use by "goto end". bool image_is_16bit; LONG image_width, image_height; if (image_type == IMAGE_ICON) { // Must be done prior to IconToBitmap() since it deletes (HICON)hbitmap_image: ICONINFO ii; if (GetIconInfo((HICON)hbitmap_image, &ii)) { // If the icon is monochrome (black and white), ii.hbmMask will contain twice as many pixels as // are actually in the icon. But since the top half of the pixels are the AND-mask, it seems // okay to get all the pixels given the rarity of monochrome icons. This scenario should be // handled properly because: 1) the variables image_height and image_width will be overridden // further below with the correct icon dimensions; 2) Only the first half of the pixels within // the image_mask array will actually be referenced by the transparency checker in the loops, // and that first half is the AND-mask, which is the transparency part that is needed. The // second half, the XOR part, is not needed and thus ignored. Also note that if width/height // required the icon to be scaled, LoadPicture() has already done that directly to the icon, // so ii.hbmMask should already be scaled to match the size of the bitmap created later below. image_mask = getbits(ii.hbmMask, hdc, image_width, image_height, image_is_16bit, 1); DeleteObject(ii.hbmColor); // DeleteObject() probably handles NULL okay since few MSDN/other examples ever check for NULL. DeleteObject(ii.hbmMask); } if ( !(hbitmap_image = IconToBitmap((HICON)hbitmap_image, true)) ) goto end; } if ( !(image_pixel = getbits(hbitmap_image, hdc, image_width, image_height, image_is_16bit)) ) goto end; // Create an empty bitmap to hold all the pixels currently visible on the screen that lie within the search area: int search_width = aRight - aLeft + 1; int search_height = aBottom - aTop + 1; if ( !(sdc = CreateCompatibleDC(hdc)) || !(hbitmap_screen = CreateCompatibleBitmap(hdc, search_width, search_height)) ) goto end; if ( !(sdc_orig_select = SelectObject(sdc, hbitmap_screen)) ) goto end; // Copy the pixels in the search-area of the screen into the DC to be searched: if ( !(BitBlt(sdc, 0, 0, search_width, search_height, hdc, aLeft, aTop, SRCCOPY)) ) goto end; LONG screen_width, screen_height; bool screen_is_16bit; if ( !(screen_pixel = getbits(hbitmap_screen, sdc, screen_width, screen_height, screen_is_16bit)) ) goto end; LONG image_pixel_count = image_width * image_height; LONG screen_pixel_count = screen_width * screen_height; int i, j, k, x, y; // Declaring as "register" makes no performance difference with current compiler, so let the compiler choose which should be registers. // If either is 16-bit, convert *both* to the 16-bit-compatible 32-bit format: if (image_is_16bit || screen_is_16bit) { if (trans_color != CLR_NONE) trans_color &= 0x00F8F8F8; // Convert indicated trans-color to be compatible with the conversion below. for (i = 0; i < screen_pixel_count; ++i) screen_pixel[i] &= 0x00F8F8F8; // Highest order byte must be masked to zero for consistency with use of 0x00FFFFFF below. for (i = 0; i < image_pixel_count; ++i) image_pixel[i] &= 0x00F8F8F8; // Same. } // v1.0.44.03: The below is now done even for variation>0 mode so its results are consistent with those of // non-variation mode. This is relied upon by variation=0 mode but now also by the following line in the // variation>0 section: // || image_pixel[j] == trans_color // Without this change, there are cases where variation=0 would find a match but a higher variation // (for the same search) wouldn't. for (i = 0; i < image_pixel_count; ++i) image_pixel[i] &= 0x00FFFFFF; // Search the specified region for the first occurrence of the image: if (aVariation < 1) // Caller wants an exact match. { // Concerning the following use of 0x00FFFFFF, the use of 0x00F8F8F8 above is related (both have high order byte 00). // The following needs to be done only when shades-of-variation mode isn't in effect because // shades-of-variation mode ignores the high-order byte due to its use of macros such as GetRValue(). // This transformation incurs about a 15% performance decrease (percentage is fairly constant since // it is proportional to the search-region size, which tends to be much larger than the search-image and // is therefore the primary determination of how long the loops take). But it definitely helps find images // more successfully in some cases. For example, if a PNG file is displayed in a GUI window, this // transformation allows certain bitmap search-images to be found via variation==0 when they otherwise // would require variation==1 (possibly the variation==1 success is just a side-effect of it // ignoring the high-order byte -- maybe a much higher variation would be needed if the high // order byte were also subject to the same shades-of-variation analysis as the other three bytes [RGB]). for (i = 0; i < screen_pixel_count; ++i) screen_pixel[i] &= 0x00FFFFFF; for (i = 0; i < screen_pixel_count; ++i) { // Unlike the variation-loop, the following one uses a first-pixel optimization to boost performance // by about 10% because it's only 3 extra comparisons and exact-match mode is probably used more often. // Before even checking whether the other adjacent pixels in the region match the image, ensure // the image does not extend past the right or bottom edges of the current part of the search region. // This is done for performance but more importantly to prevent partial matches at the edges of the // search region from being considered complete matches. // The following check is ordered for short-circuit performance. In addition, image_mask, if // non-NULL, is used to determine which pixels are transparent within the image and thus should // match any color on the screen. if ((screen_pixel[i] == image_pixel[0] // A screen pixel has been found that matches the image's first pixel. || image_mask && image_mask[0] // Or: It's an icon's transparent pixel, which matches any color. || image_pixel[0] == trans_color) // This should be okay even if trans_color==CLR_NONE, since CLR_NONE should never occur naturally in the image. && image_height <= screen_height - i/screen_width // Image is short enough to fit in the remaining rows of the search region. && image_width <= screen_width - i%screen_width) // Image is narrow enough not to exceed the right-side boundary of the search region. { // Check if this candidate region -- which is a subset of the search region whose height and width // matches that of the image -- is a pixel-for-pixel match of the image. for (found = true, x = 0, y = 0, j = 0, k = i; j < image_pixel_count; ++j) { if (!(found = (screen_pixel[k] == image_pixel[j] // At least one pixel doesn't match, so this candidate is discarded. || image_mask && image_mask[j] // Or: It's an icon's transparent pixel, which matches any color. || image_pixel[j] == trans_color))) // This should be okay even if trans_color==CLR_NONE, since CLR none should never occur naturally in the image. break; if (++x < image_width) // We're still within the same row of the image, so just move on to the next screen pixel. ++k; else // We're starting a new row of the image. { x = 0; // Return to the leftmost column of the image. ++y; // Move one row downward in the image. // Move to the next row within the current-candidate region (not the entire search region). // This is done by moving vertically downward from "i" (which is the upper-left pixel of the // current-candidate region) by "y" rows. k = i + y*screen_width; // Verified correct. } } if (found) // Complete match found. break; } } } else // Allow colors to vary by aVariation shades; i.e. approximate match is okay. { // The following section is part of the first-pixel-check optimization that improves performance by // 15% or more depending on where and whether a match is found. This section and one the follows // later is commented out to reduce code size. // Set high/low range for the first pixel of the image since it is the pixel most often checked // (i.e. for performance). //BYTE search_red1 = GetBValue(image_pixel[0]); // Because it's RGB vs. BGR, the B value is fetched, not R (though it doesn't matter as long as everything is internally consistent here). //BYTE search_green1 = GetGValue(image_pixel[0]); //BYTE search_blue1 = GetRValue(image_pixel[0]); // Same comment as above. //BYTE red_low1 = (aVariation > search_red1) ? 0 : search_red1 - aVariation; //BYTE green_low1 = (aVariation > search_green1) ? 0 : search_green1 - aVariation; //BYTE blue_low1 = (aVariation > search_blue1) ? 0 : search_blue1 - aVariation; //BYTE red_high1 = (aVariation > 0xFF - search_red1) ? 0xFF : search_red1 + aVariation; //BYTE green_high1 = (aVariation > 0xFF - search_green1) ? 0xFF : search_green1 + aVariation; //BYTE blue_high1 = (aVariation > 0xFF - search_blue1) ? 0xFF : search_blue1 + aVariation; // Above relies on the fact that the 16-bit conversion higher above was already done because like // in PixelSearch, it seems more appropriate to do the 16-bit conversion prior to setting the range // of high and low colors (vs. than applying 0xF8 to each of the high/low values individually). BYTE red, green, blue; BYTE search_red, search_green, search_blue; BYTE red_low, green_low, blue_low, red_high, green_high, blue_high; // The following loop is very similar to its counterpart above that finds an exact match, so maintain // them together and see above for more detailed comments about it. for (i = 0; i < screen_pixel_count; ++i) { // The following is commented out to trade code size reduction for performance (see comment above). //red = GetBValue(screen_pixel[i]); // Because it's RGB vs. BGR, the B value is fetched, not R (though it doesn't matter as long as everything is internally consistent here). //green = GetGValue(screen_pixel[i]); //blue = GetRValue(screen_pixel[i]); //if ((red >= red_low1 && red <= red_high1 // && green >= green_low1 && green <= green_high1 // && blue >= blue_low1 && blue <= blue_high1 // All three color components are a match, so this screen pixel matches the image's first pixel. // || image_mask && image_mask[0] // Or: It's an icon's transparent pixel, which matches any color. // || image_pixel[0] == trans_color) // This should be okay even if trans_color==CLR_NONE, since CLR none should never occur naturally in the image. // && image_height <= screen_height - i/screen_width // Image is short enough to fit in the remaining rows of the search region. // && image_width <= screen_width - i%screen_width) // Image is narrow enough not to exceed the right-side boundary of the search region. // Instead of the above, only this abbreviated check is done: if (image_height <= screen_height - i/screen_width // Image is short enough to fit in the remaining rows of the search region. && image_width <= screen_width - i%screen_width) // Image is narrow enough not to exceed the right-side boundary of the search region. { // Since the first pixel is a match, check the other pixels. for (found = true, x = 0, y = 0, j = 0, k = i; j < image_pixel_count; ++j) { search_red = GetBValue(image_pixel[j]); search_green = GetGValue(image_pixel[j]); search_blue = GetRValue(image_pixel[j]); SET_COLOR_RANGE red = GetBValue(screen_pixel[k]); green = GetGValue(screen_pixel[k]); blue = GetRValue(screen_pixel[k]); if (!(found = red >= red_low && red <= red_high && green >= green_low && green <= green_high && blue >= blue_low && blue <= blue_high || image_mask && image_mask[j] // Or: It's an icon's transparent pixel, which matches any color. || image_pixel[j] == trans_color)) // This should be okay even if trans_color==CLR_NONE, since CLR_NONE should never occur naturally in the image. break; // At least one pixel doesn't match, so this candidate is discarded. if (++x < image_width) // We're still within the same row of the image, so just move on to the next screen pixel. ++k; else // We're starting a new row of the image. { x = 0; // Return to the leftmost column of the image. ++y; // Move one row downward in the image. k = i + y*screen_width; // Verified correct. } } if (found) // Complete match found. break; } } } end: DWORD error = GetLastError(); ReleaseDC(NULL, hdc); if (!no_delete_bitmap && hbitmap_image) DeleteObject(hbitmap_image); if (sdc) { if (sdc_orig_select) // i.e. the original call to SelectObject() didn't fail. SelectObject(sdc, sdc_orig_select); // Probably necessary to prevent memory leak. DeleteDC(sdc); } if (hbitmap_screen) DeleteObject(hbitmap_screen); if (image_pixel) free(image_pixel); if (image_mask) free(image_mask); if (screen_pixel) free(screen_pixel); else // One of the GDI calls failed. return FR_E_WIN32(error); if (found) { // Calculate xpos and ypos of where the match was found and adjust coords to // make them relative to the origin point (which will contain zeroes if this // doesn't need to be done): if (aFoundX) aFoundX->SetValue((aLeft + i%screen_width) - origin.x); if (aFoundY) aFoundY->SetValue((aTop + i/screen_width) - origin.y); } aRetVal = found; return OK; }
35,050
C++
.cpp
671
49.022355
189
0.710915
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,098
Gui.StatusBar.cpp
AutoHotkey_AutoHotkey/source/lib/Gui.StatusBar.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "script_gui.h" FResult GuiControlType::SB_SetIcon(StrArg aFilename, optl<int> aIconNumber, optl<UINT> aPartNumber, UINT_PTR &aRetVal) { GuiType& gui = *this->gui; UINT part_index = aPartNumber.value_or(1) - 1; if (part_index > 255) // Also covers wrapped negative values. return FR_E_ARG(2); int unused, icon_number = aIconNumber.value_or(1); if (icon_number == 0) // Must be != 0 to tell LoadPicture that "icon must be loaded, never a bitmap". icon_number = 1; auto hicon = (HICON)LoadPicture(aFilename // Load-time validation has ensured there is at least one parameter. , GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON) // Apparently the bar won't scale them for us. , unused, icon_number, false); // Defaulting to "false" for "use GDIplus" provides more consistent appearance across multiple OSes. if (!hicon) return FError(ERR_LOAD_ICON, aFilename); HICON hicon_old = (HICON)SendMessage(hwnd, SB_GETICON, part_index, 0); // Get the old one before setting the new one. // There's no need to keep track of the icon handle since it will be destroyed automatically if the // window is destroyed or the program exits. if (!SendMessage(hwnd, SB_SETICON, part_index, (LPARAM)hicon)) { DestroyIcon(hicon); return FR_E_FAILED; } if (hicon_old) // Although the old icon is automatically destroyed here, the script can call SendMessage(SB_SETICON) // itself if it wants to work with HICONs directly (for performance reasons, etc.) DestroyIcon(hicon_old); // Return the icon handle mainly for historical reasons. Old comments indicated the return value was // to allow the script to destroy the HICON later when it doesn't need it, but that doesn't make sense // since destroying the Gui or setting a new icon would implicitly cause the old icon to be destroyed. aRetVal = (UINT_PTR)hicon; return OK; } FResult GuiControlType::SB_SetParts(VariantParams &aParam, UINT& aRetVal) { GuiType& gui = *this->gui; int old_part_count, new_part_count; int edge, part[256]; // Load-time validation has ensured aParamCount is under 255, so it shouldn't overflow. for (edge = 0, new_part_count = 0; new_part_count < aParam.count; ++new_part_count) { auto &value = *aParam.value[new_part_count]; if (!TokenIsNumeric(value)) return FParamError(new_part_count, &value, _T("Number")); int width = (int)TokenToInt64(value); if (width < 0) return FR_E_ARG(new_part_count); edge += gui.Scale(width); part[new_part_count] = edge; } // For code simplicity, there is currently no means to have the last part of the bar use less than // all of the bar's remaining width. The desire to do so seems rare, especially since the script can // add an extra/unused part at the end to achieve nearly (or perhaps exactly) the same effect. part[new_part_count++] = -1; // Make the last part use the remaining width of the bar. old_part_count = (int)SendMessage(hwnd, SB_GETPARTS, 0, NULL); // MSDN: "This message always returns the number of parts in the status bar [regardless of how it is called]". if (old_part_count > new_part_count) // Some parts are being deleted, so destroy their icons. See other notes in GuiType::Destroy() for explanation. for (int i = new_part_count; i < old_part_count; ++i) // Verified correct. if (auto hicon = (HICON)SendMessage(hwnd, SB_GETICON, i, 0)) DestroyIcon(hicon); if (!SendMessage(hwnd, SB_SETPARTS, new_part_count, (LPARAM)part)) return FR_E_FAILED; // hwnd is returned for historical reasons; there are more direct and ubiquitous ways to get it. aRetVal = (UINT)(size_t)hwnd; return OK; } FResult GuiControlType::SB_SetText(StrArg aNewText, optl<UINT> aPartNumber, optl<UINT> aStyle) { UINT part_index = aPartNumber.value_or(1) - 1; if (part_index > 255) // Also covers wrapped negative values. return FR_E_ARG(2); UINT style = aStyle.value_or(0); if (style > 0xFF) return FR_E_ARG(3); return SendMessage(hwnd, SB_SETTEXT, (part_index | (style << 8)), (LPARAM)aNewText) ? OK : FR_E_FAILED; }
4,912
C++
.cpp
88
50.25
177
0.702426
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,099
wait.cpp
AutoHotkey_AutoHotkey/source/lib/wait.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "window.h" #include "application.h" #include "script_func_impl.h" void MsgSleepWithListLines(int aSleepDuration, Line *waiting_line, DWORD start_time) { if (MsgSleep(aSleepDuration)) { // v1.0.30.02: Since MsgSleep() launched and returned from at least one new thread, put the // current waiting line into the line-log again to make it easy to see what the current // thread is doing. This is especially useful for figuring out which subroutine is holding // another thread interrupted beneath it. For example, if a timer gets interrupted by // a hotkey that has an indefinite WinWait, and that window never appears, this will allow // the user to find out the culprit thread by showing its line in the log (and usually // it will appear as the very last line, since usually the script is idle and thus the // currently active thread is the one that's still waiting for the window). if (g->ListLinesIsEnabled) { // ListLines is enabled in this thread, but if it was disabled in the interrupting thread, // the very last log entry will be ours. In that case, we don't want to duplicate it. int previous_log_index = (Line::sLogNext ? Line::sLogNext : LINE_LOG_SIZE) - 1; // Wrap around if needed (the entry can be NULL in that case). if (Line::sLog[previous_log_index] != waiting_line || Line::sLogTick[previous_log_index] != start_time) // The previously logged line was not this one, or it was added by the interrupting thread (different start_time). { Line::sLog[Line::sLogNext] = waiting_line; Line::sLogTick[Line::sLogNext++] = start_time; // Store a special value so that Line::LogToText() can report that its "still waiting" from earlier. if (Line::sLogNext >= LINE_LOG_SIZE) Line::sLogNext = 0; // The lines above are the similar to those used in ExecUntil(), so the two should be // maintained together. } } } } typedef bool (*WaitCompletedPredicate)(void *); static bool Wait(int aTimeout, void *aParam, WaitCompletedPredicate aWaitCompleted) { Line *waiting_line = g_script.mCurrLine; for (DWORD start_time = GetTickCount();;) // start_time is initialized unconditionally for use with ListLines. { if (aWaitCompleted(aParam)) return true; // Must cast to int or any negative result will be lost due to DWORD type: if (aTimeout < 0 || (aTimeout - (int)(GetTickCount() - start_time)) > SLEEP_INTERVAL_HALF) MsgSleepWithListLines(INTERVAL_UNSPECIFIED, waiting_line, start_time); else // Done waiting (timed out). return false; } } bif_impl FResult ClipWait(optl<double> aTimeout, optl<int> aWaitForAnyData, BOOL &aRetVal) { int timeout = -1; if (aTimeout.has_value()) { timeout = (int)(aTimeout.value() * 1000); if (timeout < 0) return FR_E_ARG(0); } WaitCompletedPredicate predicate; switch (aWaitForAnyData.value_or(0)) { case 0: // Wait for text predicate = [](void*) -> bool { // Seems best to consider CF_HDROP to be a non-empty clipboard, since we // support the implicit conversion of that format to text: return (IsClipboardFormatAvailable(CF_NATIVETEXT) || IsClipboardFormatAvailable(CF_HDROP)); }; break; case 1: // Wait for any clipboard data predicate = [](void*) -> bool { return CountClipboardFormats(); }; break; default: // Reserved return FR_E_ARG(1); } aRetVal = Wait(timeout, nullptr, predicate); return OK; } bif_impl FResult KeyWait(StrArg aKeyName, optl<StrArg> aOptions, BOOL &aRetVal) { // Set defaults: int timeout = -1; struct Params { vk_type vk; JoyControls joy; int joystick_id; bool wait_for_keydown = false; // The default is to wait for the key to be released. KeyStateTypes key_state_type = KEYSTATE_PHYSICAL; // Since physical is more often used. } params; if ( !(params.vk = TextToVK(aKeyName)) ) { params.joy = (JoyControls)ConvertJoy(aKeyName, &params.joystick_id); if (!IS_JOYSTICK_BUTTON(params.joy)) // Currently, only buttons are supported. // It's either an invalid key name or an unsupported Joy-something. return FR_E_ARG(0); } for (auto cp = aOptions.value_or_empty(); *cp; ++cp) { switch (ctoupper(*cp)) { case 'D': params.wait_for_keydown = true; break; case 'L': params.key_state_type = KEYSTATE_LOGICAL; break; case 'T': timeout = (int)(ATOF(cp + 1) * 1000); if (timeout < 0) return FR_E_ARG(1); break; } } WaitCompletedPredicate predicate; if (params.vk) predicate = [](void *pp) -> bool { // Waiting for key or mouse button auto &p = *((Params*)pp); return ScriptGetKeyState(p.vk, p.key_state_type) == p.wait_for_keydown; }; else predicate = [](void *pp) -> bool { // Waiting for joystick button auto &p = *((Params*)pp); TCHAR unused[32]; ExprTokenType token; return ScriptGetJoyState(p.joy, p.joystick_id, token, unused) == p.wait_for_keydown; }; aRetVal = Wait(timeout, &params, predicate); return OK; } static FResult WinWait(ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<double> aTimeout, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText , UINT &aRetVal, BuiltInFunctionID aCondition) { int timeout = -1; if (aTimeout.has_value()) { timeout = (int)(aTimeout.value() * 1000); if (timeout < 0) return FR_E_ARG(2); } TCHAR title_buf[MAX_NUMBER_SIZE]; WaitCompletedPredicate predicate; struct Params { BuiltInFunctionID condition; bool hwnd_specified; HWND hwnd; LPCTSTR title, text, exclude_title, exclude_text; } p; p.condition = aCondition; p.hwnd_specified = false; p.hwnd = NULL; p.title = _T(""); p.text = aWinText.value_or_empty(); p.exclude_title = aExcludeTitle.value_or_empty(); p.exclude_text = aExcludeText.value_or_empty(); if (aWinTitle) { auto fr = DetermineTargetHwnd(p.hwnd, p.hwnd_specified, *aWinTitle); if (fr != OK) return fr; if (p.hwnd_specified && !p.hwnd) { // Caller may have specified a NULL HWND or it may be NULL due to an IsWindow() check. // In either case, it isn't meaningful to wait (see !IsWindow(p.hwnd) comments below). aRetVal = (aCondition == FID_WinWaitClose || aCondition == FID_WinWaitNotActive); if (aRetVal) DoWinDelay; return OK; } if (!p.hwnd_specified) p.title = TokenToString(*aWinTitle, title_buf); } if (p.hwnd_specified) { predicate = [](void *pp) { auto &p = *(Params*)pp; if (!IsWindow(p.hwnd)) { // It's not meaningful to wait for another window to be created with this // same HWND, so return now regardless of whether the wait condition was met. // Let the return value be 1 for WinWaitClose/WinWaitNotActive to indicate the // condition was met, and 0 for WinWait/WinWaitActive to indicate that it wasn't. p.hwnd = NULL; return true; } bool is_match, want_match; if (p.condition == FID_WinWait || p.condition == FID_WinWaitClose) { // Wait for the window to become visible/hidden. Most functions ignore // DetectHiddenWindows when given a pure HWND/object (because it's more // useful that way), but in this case it seems more useful and intuitive // to respect DetectHiddenWindows. is_match = g->DetectWindow(p.hwnd); want_match = (p.condition == FID_WinWait); } else { is_match = (GetForegroundWindow() == p.hwnd); want_match = (p.condition == FID_WinWaitActive); } if (is_match) g->hWndLastUsed = p.hwnd; return is_match == want_match; }; } else // hwnd_specified == false switch (aCondition) { default: #ifdef _DEBUG ASSERT(!"Unhandled case"); break; #endif case FID_WinWait: case FID_WinWaitClose: predicate = [](void *pp) { auto &p = *(Params*)pp; HWND found = WinExist(*g, p.title, p.text, p.exclude_title, p.exclude_text, false, true); if ((found != NULL) == (p.condition == FID_WinWait)) { p.hwnd = found; return true; } return false; }; break; case FID_WinWaitActive: case FID_WinWaitNotActive: predicate = [](void *pp) { auto &p = *(Params*)pp; HWND found = WinActive(*g, p.title, p.text, p.exclude_title, p.exclude_text, true); if ((found != NULL) == (p.condition == FID_WinWaitActive)) { p.hwnd = found; return true; } return false; }; break; } if (Wait(timeout, &p, predicate)) { DoWinDelay; if (aCondition == FID_WinWaitClose || aCondition == FID_WinWaitNotActive) aRetVal = 1; else aRetVal = (UINT)(size_t)p.hwnd; } else aRetVal = 0; return OK; } bif_impl FResult WinWait(ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<double> aTimeout, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText, UINT &aRetVal) { return WinWait(aWinTitle, aWinText, aTimeout, aExcludeTitle, aExcludeText, aRetVal, FID_WinWait); } bif_impl FResult WinWaitClose(ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<double> aTimeout, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText, UINT &aRetVal) { return WinWait(aWinTitle, aWinText, aTimeout, aExcludeTitle, aExcludeText, aRetVal, FID_WinWaitClose); } bif_impl FResult WinWaitActive(ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<double> aTimeout, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText, UINT &aRetVal) { return WinWait(aWinTitle, aWinText, aTimeout, aExcludeTitle, aExcludeText, aRetVal, FID_WinWaitActive); } bif_impl FResult WinWaitNotActive(ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<double> aTimeout, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText, UINT &aRetVal) { return WinWait(aWinTitle, aWinText, aTimeout, aExcludeTitle, aExcludeText, aRetVal, FID_WinWaitNotActive); } // RunWait is still a "BIF" for now because the OutputVarPID parameter can only be used // by another thread, while the function is running, and there's currently no means for // a function implemented via MdFunc to assign to the output var directly. ResultType RunWait(StrArg aTarget, optl<StrArg> aWorkingDir, optl<StrArg> aOptions, optl<IObject*> aPID, int &aExitCode) { Line *waiting_line = g_script.mCurrLine; DWORD start_time = GetTickCount(); HANDLE running_process; if (!g_script.ActionExec(aTarget, NULL, aWorkingDir.value_or_null(), true, aOptions.value_or_null(), &running_process, true, true)) return FAIL; // For the output var to be useful, it must be assigned before we wait: if (aPID.has_value() && running_process) { Var output_var(aPID.value()); if (!output_var.Assign(GetProcessId(running_process))) return FAIL; } if (!running_process) // Nothing to wait for (rare?). { aExitCode = 0; return OK; } for (;;) { // The below call takes care of determining whether the process has exited, // and is more reliable than GetExitCodeProcess() == STILL_ACTIVE because // STILL_ACTIVE is also valid exit code. if (MsgWaitForMultipleObjects(1, &running_process, FALSE, INFINITE, QS_ALLINPUT) == WAIT_OBJECT_0) break; MsgSleepWithListLines(-1, waiting_line, start_time); } DWORD exit_code = 0; GetExitCodeProcess(running_process, &exit_code); CloseHandle(running_process); // Use signed vs. unsigned, since that is more typical? No, it seems better // to use unsigned now that script variables store 64-bit ints. This is because // GetExitCodeProcess() yields a DWORD, implying that the value should be unsigned. // Unsigned also is more useful in cases where an app returns a (potentially large) // count of something as its result. However, if this is done, it won't be easy // to check against a return value of -1, for example, which I suspect many apps // return. AutoIt3 (and probably 2) use a signed int as well, so that is another // reason to keep it this way: aExitCode = (int)exit_code; return OK; }
12,246
C++
.cpp
327
34.593272
221
0.723505
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,100
regex.cpp
AutoHotkey_AutoHotkey/source/lib/regex.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "globaldata.h" #define PCRE_STATIC // For RegEx. PCRE_STATIC tells PCRE to declare its functions for normal, static #include "lib_pcre/pcre/pcre.h" // linkage rather than as functions inside an external DLL. #include "script_func_impl.h" struct RegExSearch { pcret *re; LPTSTR re_text; pcret_extra *extra; LPTSTR haystack; LPTSTR mark; int haystack_length; int options_length; int pattern_count; int starting_offset; int number_of_ints_in_offset; FResult fresult; // Used by Prepare() and callouts. TCHAR haystack_buf[MAX_NUMBER_SIZE]; pcret_extra extra_buf; bool Prepare(ExprTokenType &aHaystack, StrArg aNeedle, optl<int> aStartingPos); FResult Match(IObject** aMatchObj, int &aFoundPos) const; FResult Replace(ExprTokenType *aReplacement, int *aOutCount, optl<int> aLimit, ResultToken &aRetVal) const; FResult CreateMatchArray(int *offset, int captured_pattern_count, IObject *&match_object) const; }; FResult PCREExecError(int n) { TCHAR err_info[MAX_INTEGER_SIZE]; ITOA(n, err_info); return FError(ERR_PCRE_EXEC, err_info); } FResult RegExSearch::CreateMatchArray(int *offset, int captured_pattern_count, IObject *&match_object) const { // For lookup performance, create a table of subpattern names indexed by subpattern number. LPCTSTR *subpat_name = NULL; // Set default as "no subpattern names present or available". bool allow_dupe_subpat_names = false; // Set default. LPCTSTR name_table; int name_count, name_entry_size; if ( !pcret_fullinfo(re, extra, PCRE_INFO_NAMECOUNT, &name_count) // Success. Fix for v1.0.45.01: Don't check captured_pattern_count>=0 because PCRE_ERROR_NOMATCH can still have named patterns! && name_count // There's at least one named subpattern. Relies on short-circuit boolean order. && !pcret_fullinfo(re, extra, PCRE_INFO_NAMETABLE, &name_table) // Success. && !pcret_fullinfo(re, extra, PCRE_INFO_NAMEENTRYSIZE, &name_entry_size) ) // Success. { int pcre_options; if (!pcret_fullinfo(re, extra, PCRE_INFO_OPTIONS, &pcre_options)) // Success. allow_dupe_subpat_names = pcre_options & PCRE_DUPNAMES; // For indexing simplicity, also include an entry for the main/entire pattern at index 0 even though // it's never used because the entire pattern can't have a name without enclosing it in parentheses // (in which case it's not the entire pattern anymore, but in fact subpattern #1). size_t subpat_array_size = pattern_count * sizeof(LPCSTR); subpat_name = (LPCTSTR *)_alloca(subpat_array_size); // See other use of _alloca() above for reasons why it's used. ZeroMemory(subpat_name, subpat_array_size); // Set default for each index to be "no name corresponds to this subpattern number". for (int i = 0; i < name_count; ++i, name_table += name_entry_size) { // Below converts first two bytes of each name-table entry into the pattern number (it might be // possible to simplify this, but I'm not sure if big vs. little-endian will ever be a concern). #ifdef UNICODE subpat_name[name_table[0]] = name_table + 1; #else subpat_name[(name_table[0] << 8) + name_table[1]] = name_table + 2; // For indexing simplicity, subpat_name[0] is for the main/entire pattern though it is never actually used for that because it can't be named without being enclosed in parentheses (in which case it becomes a subpattern). #endif // For simplicity and unlike PHP, IsNumeric() isn't called to forbid numeric subpattern names. // It seems the worst than could happen if it is numeric is that it would overlap/overwrite some of // the numerically-indexed elements in the output-array. Seems pretty harmless given the rarity. } } //else one of the pcre_fullinfo() calls may have failed. The PCRE docs indicate that this realistically never // happens unless bad inputs were given. So due to rarity, just leave subpat_name==NULL; i.e. "no named subpatterns". return RegExMatchObject::Create(haystack, offset, subpat_name, pattern_count, captured_pattern_count, mark, match_object) ? OK : FR_E_OUTOFMEM; } ResultType RegExMatchObject::Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark, IObject *&aNewObject) { aNewObject = NULL; // If there was no match, seems best to not return an object: if (aCapturedPatternCount < 1) return OK; RegExMatchObject *m = new RegExMatchObject(); if (!m) return FAIL; m->SetBase(sPrototype); if ( aMark && !(m->mMark = _tcsdup(aMark)) ) { m->Release(); return FAIL; } ASSERT(aCapturedPatternCount >= 1); ASSERT(aPatternCount >= aCapturedPatternCount); // Use aPatternCount vs aCapturedPatternCount since we want to be able to retrieve the // names of *all* subpatterns, even ones that weren't captured. For instance, a loop // converting the object to an old-style pseudo-array would need to initialize even the // array items that weren't captured. m->mPatternCount = aPatternCount; // Allocate memory for a copy of the offset array. if ( !(m->mOffset = (int *)malloc(aPatternCount * 2 * sizeof(int *))) ) { m->Release(); return FAIL; } // memcpy currently benchmarks slightly faster on x64 than copying offsets in the loop below: memcpy(m->mOffset, aOffset, aPatternCount * 2 * sizeof(int)); // Do some pre-processing: // - Locate the smallest portion of haystack that contains all matches. // - Convert end offsets to lengths. int p, min_offset = INT_MAX, max_offset = -1; for (p = 0; p < aCapturedPatternCount; ++p) { if (m->mOffset[p*2] > -1) { // Substring is non-empty, so ensure we copy this portion of haystack. if (min_offset > m->mOffset[p*2]) min_offset = m->mOffset[p*2]; if (max_offset < m->mOffset[p*2+1]) max_offset = m->mOffset[p*2+1]; } // Convert end offset to length. m->mOffset[p*2+1] -= m->mOffset[p*2]; } // Initialize the remainder of the offset vector (patterns which were not captured), // which have indeterminate values if we're called by a regex callout and therefore // can't be handled the same way as in the loop above. for ( ; p < aPatternCount; ++p) { m->mOffset[p*2] = -1; m->mOffset[p*2+1] = 0; } // Copy only the portion of aHaystack which contains matches. This can be much faster // than copying the whole string for larger haystacks. For instance, searching for "GNU" // in the GPL v2 (18120 chars) and producing a match object is about 5 times faster with // this optimization than without if caller passes us the haystack length, and about 50 // times faster than the old code which used _tcsdup(). However, the difference is much // smaller for small strings. if (min_offset < max_offset) // There are non-empty matches. { int our_haystack_size = (max_offset - min_offset) + 1; if ( !(m->mHaystack = tmalloc(our_haystack_size)) ) { m->Release(); return FAIL; } tmemcpy(m->mHaystack, aHaystack + min_offset, our_haystack_size); m->mHaystackStart = min_offset; } // Copy subpattern names. if (aPatternName) { // Allocate array of pointers. if ( !(m->mPatternName = (LPTSTR *)malloc(aPatternCount * sizeof(LPTSTR *))) ) { m->Release(); // Also frees other things allocated above. return FAIL; } // Copy names and initialize array. m->mPatternName[0] = NULL; for (int p = 1; p < aPatternCount; ++p) if (aPatternName[p]) // A failed allocation here seems rare and the consequences would be // negligible, so in that case just act as if the subpattern has no name. m->mPatternName[p] = _tcsdup(aPatternName[p]); else m->mPatternName[p] = NULL; } // Since above didn't return, the object has been set up successfully. aNewObject = m; return OK; } void RegExMatchObject::Invoke(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount) { switch (aID) { case M_Count: _o_return(mPatternCount - 1); case M_Mark: _o_return(mMark ? mMark : _T("")); case M___Enum: _o_return(new IndexEnumerator(this, ParamIndexToOptionalInt(0, 0) , static_cast<IndexEnumerator::Callback>(&RegExMatchObject::GetEnumItem))); } int p; if (ParamIndexIsOmitted(0)) p = 0; else if (ParamIndexIsNumeric(0)) p = ParamIndexToInt(0); else if (!mPatternName) // There are no named subpatterns, so param 0 is invalid. p = -1; else { auto name = ParamIndexToString(0); for (p = 0; p < mPatternCount; ++p) if (mPatternName[p] && !_tcsicmp(mPatternName[p], name)) { if (mOffset[2*p] < 0) // This pattern wasn't matched, so check for one with a duplicate name. for (int i = p + 1; i < mPatternCount; ++i) if (mPatternName[i] && !_tcsicmp(mPatternName[i], name) // It has the same name. && mOffset[2*i] >= 0) // It matched something. { // Prefer this pattern. p = i; break; } break; } } if (p < 0 || p >= mPatternCount) _o_throw_param(0); // p != 0 implies the parameter was not omitted. switch (aID) { case M___Get: if (auto arr = dynamic_cast<Array*>(ParamIndexToObject(1))) if (arr->Length()) _o_throw(ERR_INVALID_USAGE); // Otherwise, fall through: // Gives the correct result even if there was no match (because length is 0): case M_Value: _o_return(mHaystack - mHaystackStart + mOffset[p*2], mOffset[p*2+1]); case M_Pos: _o_return(mOffset[2*p] + 1); case M_Len: _o_return(mOffset[2*p + 1]); case M_Name: _o_return((mPatternName && mPatternName[p]) ? mPatternName[p] : _T("")); } } int RegExCallout(pcret_callout_block *cb) { // Continuing execution on the hook thread wouldn't be safe, but there's no need to check // the following since cb->callout_data is non-null only when the regex is being evaluated // by RegExMatch/RegExReplace: //if (GetCurrentThreadId() != g_MainThreadID) // return 0; if (!cb->callout_data) // Callout not coming from RegExMatch/RegExReplace. return 0; RegExSearch &cd = *(RegExSearch *)cb->callout_data; // Callout functions must be resolved each time, since patterns are cached, and the scope // may be different each time the pattern is executed. Aside from potentially having the // wrong nested function, AddRef/Release would be needed in places to support closures. auto callout_name = *cb->user_callout ? cb->user_callout : _T("pcre_callout"); auto callout_var = g_script.FindVar(callout_name, 0, FINDVAR_FOR_READ); auto callout_func = callout_var ? callout_var->ToObject() : nullptr; if (!callout_func) { cd.fresult = FValueError(_T("Invalid callout"), callout_name); return PCRE_ERROR_CALLOUT; } // Adjust offset to account for options, which are excluded from the regex passed to PCRE. cb->pattern_position += cd.options_length; // Save EventInfo to be restored when we return. EventInfoType EventInfo_saved = g->EventInfo; g->EventInfo = (EventInfoType) cb; /* callout_number: should be available since callout number can be specified within (?C...). subject: useful when behaviour might depend on text surrounding a capture. start_match: as above. equivalent to return value of RegExMatch, so should be available somehow. pattern_position: useful to debug regexes when combined with auto-callouts. otherwise not useful. next_item_length: as above. combined 'next_item' instead of these two would be less useful as it cannot distinguish between multiple identical items, and would sometimes be empty. capture_top: not sure if useful? helps to distinguish between empty capture and non-capture. could maybe use callout number to determine this instead. capture_last: as above. current_position: can be derived from start_match and strlen(param1), or param1 itself if P option is used. offset_vector: not very useful as same information available in local variables in more convenient form. callout_data: not relevant, maybe use "user data" field of (RegExSearch*)callout_data if implemented. subject_length: not useful, use strlen(subject). version: not important. */ // Since matching is still in progress, these *should* be -1. // For maintainability and peace of mind, save them anyway: int offset[] = { cb->offset_vector[0], cb->offset_vector[1] }; // Temporarily set these for use by the function below: cb->offset_vector[0] = cb->start_match; cb->offset_vector[1] = cb->current_position; if (cd.extra->flags & PCRE_EXTRA_MARK) *cd.extra->mark = UorA(wchar_t *, UCHAR *) cb->mark; IObject *match_object; cd.fresult = cd.CreateMatchArray(cb->offset_vector, cb->capture_top, match_object); if (FAILED(cd.fresult)) return PCRE_ERROR_CALLOUT; // Abort. // Restore to former offsets (probably -1): cb->offset_vector[0] = offset[0]; cb->offset_vector[1] = offset[1]; // Make all string positions one-based. UPDATE: offset_vector cannot be modified, so for consistency don't do this: //++cb->pattern_position; //++cb->start_match; //++cb->current_position; ExprTokenType param[] = { match_object, cb->callout_number, cb->start_match + 1, // FoundPos (distinct from Match.Pos, which hasn't been set yet) const_cast<LPTSTR>(cb->subject), // Haystack cd.re_text // NeedleRegEx }; __int64 number_to_return; auto result = CallMethod(callout_func, callout_func, nullptr, param, _countof(param), &number_to_return); if (result == FAIL || result == EARLY_EXIT) { number_to_return = PCRE_ERROR_CALLOUT; cd.fresult = FR_FAIL; } g->EventInfo = EventInfo_saved; match_object->Release(); // Behaviour of return values is defined by PCRE. return (int)number_to_return; } pcret *get_compiled_regex(LPCTSTR aRegEx, pcret_extra *&aExtra, int *aOptionsLength, FResult *aFError = nullptr) // Returns the compiled RegEx, or NULL on failure. // This function is called by things other than built-in functions so it should be kept general-purpose. // Upon failure, if aResultToken!=NULL: // - An exception is thrown with a descriptive message on failure. // - *aResultToken is set up to contain an empty string. // Upon success, the following output parameters are set based on the options that were specified: // aGetPositionsNotSubstrings // aExtra // L14: aOptionsLength is used by callouts to adjust cb->pattern_position to be relative to beginning of actual user-specified NeedleRegEx instead of string seen by PCRE. { if (!pcret_callout) { // Ensure this is initialized, even for ::RegExMatch() (to allow (?C) in window title regexes). pcret_callout = &RegExCallout; } // While reading from or writing to the cache, don't allow another thread entry. This is because // that thread (or this one) might write to the cache while the other one is reading/writing, which // could cause loss of data integrity (the hook thread can enter here via #HotIf WinActive/Exist & SetTitleMatchMode RegEx). // Together, Enter/LeaveCriticalSection reduce performance by only 1.4% in the tightest possible script // loop that hits the first cache entry every time. So that's the worst case except when there's an actual // collision, in which case performance suffers more because internally, EnterCriticalSection() does a // wait/semaphore operation, which is more costly. // Finally, the code size of all critical-section features together is less than 512 bytes (uncompressed), // so like performance, that's not a concern either. EnterCriticalSection(&g_CriticalRegExCache); // Request ownership of the critical section. If another thread already owns it, this thread will block until the other thread finishes. // SET UP THE CACHE. // This is a very crude cache for linear search. Of course, hashing would be better in the sense that it // would allow the cache to get much larger while still being fast (I believe PHP caches up to 4096 items). // Binary search might not be such a good idea in this case due to the time required to find the right spot // to insert a new cache item (however, items aren't inserted often, so it might perform quite well until // the cache contained thousands of RegEx's, which is unlikely to ever happen in most scripts). struct pcre_cache_entry { // For simplicity (and thus performance), the entire RegEx pattern including its options is cached // is stored in re_raw and that entire string becomes the RegEx's unique identifier for the purpose // of finding an entry in the cache. Technically, this isn't optimal because some options like Study // and aGetPositionsNotSubstrings don't alter the nature of the compiled RegEx. However, the CPU time // required to strip off some options prior to doing a cache search seems likely to offset much of the // cache's benefit. So for this reason, as well as rarity and code size issues, this policy seems best. LPTSTR re_raw; // The RegEx's literal string pattern such as "abc.*123". pcret *re_compiled; // The RegEx in compiled form. pcret_extra *extra; // NULL unless a study() was done (and NULL even then if study() didn't find anything). // int pcre_options; // Not currently needed in the cache since options are implicitly inside re_compiled. int options_length; // Lexikos: See aOptionsLength comment at beginning of this function. }; #define PCRE_CACHE_SIZE 100 // Going too high would be counterproductive due to the slowness of linear search (and also the memory utilization of so many compiled RegEx's). static pcre_cache_entry sCache[PCRE_CACHE_SIZE] = {{0}}; static int sLastInsert, sLastFound = -1; // -1 indicates "cache empty". int insert_pos; // v1.0.45.03: This is used to avoid updating sLastInsert until an insert actually occurs (it might not occur if a compile error occurs in the regex, or something else stops it early). // CHECK IF THIS REGEX IS ALREADY IN THE CACHE. if (sLastFound == -1) // Cache is empty, so insert this RegEx at the first position. insert_pos = 0; // A section further below will change sLastFound to be 0. else { // Search the cache to see if it contains the caller-specified RegEx in compiled form. // First check if the last-found item is a match, since often it will be (such as cases // where a script-loop executes only one RegEx, and also for SetTitleMatchMode RegEx). if (!_tcscmp(aRegEx, sCache[sLastFound].re_raw)) // Match found (case sensitive). goto match_found; // And no need to update sLastFound because it's already set right. // Since above didn't find a match, search outward in both directions from the last-found match. // A bidirectional search is done because consecutively-called regex's tend to be adjacent to each other // in the array, so performance is improved on average (since most of the time when repeating a previously // executed regex, that regex will already be in the cache -- so optimizing the finding behavior is // more important than optimizing the never-found-because-not-cached behavior). bool go_right; int i, item_to_check, left, right; int last_populated_item = (sCache[PCRE_CACHE_SIZE-1].re_compiled) // When the array is full... ? PCRE_CACHE_SIZE - 1 // ...all items must be checked except the one already done earlier. : sLastInsert; // ...else only the items actually populated need to be checked. for (go_right = true, left = sLastFound, right = sLastFound, i = 0 ; i < last_populated_item // This limits it to exactly the number of items remaining to be checked. ; ++i, go_right = !go_right) { if (go_right) // Proceed rightward in the array. { right = (right == last_populated_item) ? 0 : right + 1; // Increment or wrap around back to the left side. item_to_check = right; } else // Proceed leftward. { left = (left == 0) ? last_populated_item : left - 1; // Decrement or wrap around back to the right side. item_to_check = left; } if (!_tcscmp(aRegEx, sCache[item_to_check].re_raw)) // Match found (case sensitive). { sLastFound = item_to_check; goto match_found; } } // Since above didn't goto, no match was found nor is one possible. So just indicate the insert position // for where this RegEx will be put into the cache. // The following formula is for both cache-full and cache-partially-full. When the cache is full, // it might not be the best possible formula; but it seems pretty good because it takes a round-robin // approach to overwriting/discarding old cache entries. A discarded entry might have just been // used -- or even be sLastFound itself -- but on average, this approach seems pretty good because a // script loop that uses 50 unique RegEx's will quickly stabilize in the cache so that all 50 of them // stay compiled/cached until the loop ends. insert_pos = (sLastInsert == PCRE_CACHE_SIZE-1) ? 0 : sLastInsert + 1; // Formula works for both full and partially-full array. } // Since the above didn't goto: // - This RegEx isn't yet in the cache. So compile it and put it in the cache, then return it to caller. // - Above is responsible for having set insert_pos to the cache position where the new RegEx will be stored. // The following macro is for maintainability, to enforce the definition of "default" in multiple places. // PCRE_NEWLINE_CRLF is the default in AutoHotkey rather than PCRE_NEWLINE_LF because *multiline* haystacks // that scripts will use are expected to come from: // 50%: FileRead: Uses `r`n by default, for performance) // 10%: Clipboard: Normally uses `r`n (includes files copied from Explorer, text data, etc.) // 20%: Download: Testing shows that it varies: e.g. microsoft.com uses `r`n, but `n is probably // more common due to FTP programs automatically translating CRLF to LF when uploading to UNIX servers. // 20%: Other sources such as GUI edit controls: It's fairly unusual to want to use RegEx on multiline data // from GUI controls, but in such case `n is much more common than `r`n. #ifdef UNICODE #define AHK_PCRE_CHARSET_OPTIONS (PCRE_UTF8 | PCRE_NO_UTF8_CHECK) #else #define AHK_PCRE_CHARSET_OPTIONS 0 #endif #define SET_DEFAULT_PCRE_OPTIONS \ {\ pcre_options = AHK_PCRE_CHARSET_OPTIONS;\ do_study = false;\ } #define PCRE_NEWLINE_BITS (PCRE_NEWLINE_CRLF | PCRE_NEWLINE_ANY) // Covers all bits that are used for newline options. // SET DEFAULT OPTIONS: int pcre_options; long long do_study; SET_DEFAULT_PCRE_OPTIONS // PARSE THE OPTIONS (if any). LPCTSTR pat; // When options-parsing is done, pat will point to the start of the pattern itself. for (pat = aRegEx;; ++pat) { switch(*pat) { case 'i': pcre_options |= PCRE_CASELESS; break; // Perl-compatible options. case 'm': pcre_options |= PCRE_MULTILINE; break; // case 's': pcre_options |= PCRE_DOTALL; break; // case 'x': pcre_options |= PCRE_EXTENDED; break; // case 'A': pcre_options |= PCRE_ANCHORED; break; // PCRE-specific options (uppercase used by convention, even internally by PCRE itself). case 'D': pcre_options |= PCRE_DOLLAR_ENDONLY; break; // case 'J': pcre_options |= PCRE_DUPNAMES; break; // case 'U': pcre_options |= PCRE_UNGREEDY; break; // case 'X': pcre_options |= PCRE_EXTRA; break; // case 'C': pcre_options |= PCRE_AUTO_CALLOUT; break; // L14: PCRE_AUTO_CALLOUT causes callouts to be created with callout_number == 255 before each item in the pattern. case '\a': // Enable matching of any kind of newline, including Unicode newline characters. // v2: \R doesn't match Unicode newlines by default, so `a also enables that. pcre_options = (pcre_options & ~PCRE_NEWLINE_BITS) | PCRE_NEWLINE_ANY | PCRE_BSR_UNICODE; break; case '\n':pcre_options = (pcre_options & ~PCRE_NEWLINE_BITS) | PCRE_NEWLINE_LF; break; // See below. // Above option: Could alternatively have called it "LF" rather than or in addition to "`n", but that // seems slightly less desirable due to potential overlap/conflict with future option letters, // plus the fact that `n should be pretty well known to AutoHotkey users, especially advanced ones // using RegEx. Note: `n`r is NOT treated the same as `r`n because there's a slight chance PCRE // will someday support `n`r for some obscure usage (or just for symmetry/completeness). // The PCRE_NEWLINE_XXX options are valid for both compile() and exec(), but specifying it for exec() // would only serve to override the default stored inside the compiled pattern (seems rarely needed). case '\r': if (pat[1] == '\n') { ++pat; // Skip over the second character so that it's not recognized as a separate option by the next iteration. pcre_options = (pcre_options & ~PCRE_NEWLINE_BITS) | PCRE_NEWLINE_CRLF; // Set explicitly in case it was unset by an earlier option. Remember that PCRE_NEWLINE_CRLF is a bitwise combination of PCRE_NEWLINE_LF and CR. } else // For completeness, it's easy to support PCRE_NEWLINE_CR too, though nowadays I think it's quite rare (former Macintosh format). pcre_options = (pcre_options & ~PCRE_NEWLINE_BITS) | PCRE_NEWLINE_CR; // Do it this way because PCRE_NEWLINE_CRLF is a bitwise combination of PCRE_NEWLINE_CR and PCRE_NEWLINE_LF. break; // Other options (uppercase so that lowercase can be reserved for future/PERL options): case 'S': do_study = true; break; case ' ': // Allow only spaces and tabs as fillers so that everything else is protected/reserved for case '\t': // future use (such as future PERL options). break; case ')': // This character, when not escaped, marks the normal end of the options section. We know it's not escaped because if it had been, the loop would have stopped at the backslash before getting here. ++pat; // Set pat to be the start of the actual RegEx pattern, and leave options set to how they were by any prior iterations above. goto break_both; default: // Namely the following: //case '\0': No options are present, so ignore any letters that were accidentally recognized and treat entire string as the pattern. //case '(' : An open parenthesis must be considered an invalid option because otherwise it would be ambiguous with a subpattern. //case '\\': In addition to backslash being an invalid option, it also covers "\)" as being invalid (i.e. so that it's never necessary to check for an escaped close-parenthesis). //case all-other-chars: All others are invalid options; so like backslash above, ignore any letters that were accidentally recognized and treat entire string as the pattern. SET_DEFAULT_PCRE_OPTIONS // Revert to original options in case any early letters happened to match valid options. pat = aRegEx; // Indicate that the entire string is the pattern (no options). // To distinguish between a bad option and no options at all (for better error reporting), could check if // within the next few chars there's an unmatched close-parenthesis (non-escaped). If so, the user // intended some options but one of them was invalid. However, that would be somewhat difficult to do // because both \) and [)] are valid regex patterns that contain an unmatched close-parenthesis. // Since I don't know for sure if there are other cases (or whether future RegEx extensions might // introduce more such cases), it seems best not to attempt to distinguish. Using more than two options // is extremely rare anyway, so syntax errors of this type do not happen often (and the only harm done // is a misleading error message from PCRE rather than something like "Bad option"). In addition, // omitting it simplifies the code and slightly improves performance. goto break_both; } // switch(*pat) } // for() break_both: // Reaching here means that pat has been set to the beginning of the RegEx pattern itself and all options // are set properly. LPCSTR error_msg; TCHAR error_buf[128]; int error_code, error_offset; pcret *re_compiled; // COMPILE THE REGEX. if ( !(re_compiled = pcret_compile2(pat, pcre_options, &error_code, &error_msg, &error_offset, NULL)) ) { if (aFError) // A non-NULL value indicates our caller is RegExMatch() or RegExReplace() in a script. { sntprintf(error_buf, _countof(error_buf), _T("Compile error %d at offset %d: %hs"), error_code , error_offset, error_msg); // Seems best to bring the error to the user's attention rather than letting it potentially // escape their notice. This sort of error should be corrected immediately, not handled // within the script (such as by try-catch). *aFError = FError(error_buf, pat); } goto error; } if (do_study) { // Enabling JIT compilation adds about 68 KB to the final executable size, which seems to outweigh // the speed-up that a minority of scripts would get. Pass the option anyway, in case it is enabled: aExtra = pcret_study(re_compiled, PCRE_STUDY_JIT_COMPILE, &error_msg); // aExtra is an output parameter for caller. // Above returns NULL on failure or inability to find anything worthwhile in its study. NULL is exactly // the right value to pass to exec() to indicate "no study info". // The following isn't done because: // 1) It seems best not to abort the caller's RegEx operation just due to a study error, since the only // error likely to happen (from looking at PCRE's source code) is out-of-memory. // 2) Reduced code size. //if (error_msg) //{ //if (aResultToken) //{ // sntprintf(error_buf, sizeof(error_buf), "Study error: %s", error_msg); // aResultToken->Error(error_buf); //} //goto error; //} } else // No studying desired. aExtra = NULL; // aExtra is an output parameter for caller. // ADD THE NEWLY-COMPILED REGEX TO THE CACHE. // An earlier stage has set insert_pos to be the desired insert-position in the cache. pcre_cache_entry &this_entry = sCache[insert_pos]; // For performance and convenience. if (this_entry.re_compiled) // An existing cache item is being overwritten, so free it's attributes. { // Free the old cache entry's attributes in preparation for overwriting them with the new one's. free(this_entry.re_raw); // Free the uncompiled pattern. pcret_free(this_entry.re_compiled); // Free the compiled pattern. if (this_entry.extra) pcret_free_study(this_entry.extra); } //else the insert-position is an empty slot, which is usually the case because most scripts contain fewer than // PCRE_CACHE_SIZE unique regex's. Nothing extra needs to be done. this_entry.re_raw = _tcsdup(aRegEx); // _strdup() is very tiny and basically just calls _tcslen+malloc+_tcscpy. this_entry.re_compiled = re_compiled; this_entry.extra = aExtra; // "this_entry.pcre_options" doesn't exist because it isn't currently needed in the cache. This is // because the RE's options are implicitly stored inside re_compiled. // Lexikos: See aOptionsLength comment at beginning of this function. this_entry.options_length = (int)(pat - aRegEx); if (aOptionsLength) *aOptionsLength = this_entry.options_length; sLastInsert = insert_pos; // v1.0.45.03: Must be done only *after* the insert succeeded because some things rely on sLastInsert being synonymous with the last populated item in the cache (when the cache isn't yet full). sLastFound = sLastInsert; // Relied upon in the case where sLastFound==-1. But it also sets things up to start the search at this item next time, because it's a bit more likely to be found here such as tight loops containing only one RegEx. // Remember that although sLastFound==sLastInsert in this case, it isn't always so -- namely when a previous // call found an existing match in the cache without having to compile and insert the item. LeaveCriticalSection(&g_CriticalRegExCache); return re_compiled; // Indicate success. match_found: // RegEx was found in the cache at position sLastFound, so return the cached info back to the caller. aExtra = sCache[sLastFound].extra; if (aOptionsLength) // Lexikos: See aOptionsLength comment at beginning of this function. *aOptionsLength = sCache[sLastFound].options_length; LeaveCriticalSection(&g_CriticalRegExCache); return sCache[sLastFound].re_compiled; // Indicate success. error: // Since NULL is returned here, caller should ignore the contents of the output parameters. LeaveCriticalSection(&g_CriticalRegExCache); return NULL; // Indicate failure. } LPCTSTR RegExMatch(LPCTSTR aHaystack, LPCTSTR aNeedleRegEx) // Returns NULL if no match. Otherwise, returns the address where the pattern was found in aHaystack. { pcret_extra *extra; pcret *re; // Compile the regex or get it from cache. if ( !(re = get_compiled_regex(aNeedleRegEx, extra, NULL, NULL)) ) // Compiling problem. return NULL; // Our callers just want there to be "no match" in this case. // Set up the offset array, which consists of int-pairs containing the start/end offset of each match. // For simplicity, use a fixed size because even if it's too small (unlikely for our types of callers), // PCRE will still operate properly (though it returns 0 to indicate the too-small condition). #define RXM_INT_COUNT 30 // Should be a multiple of 3. int offset[RXM_INT_COUNT]; // Execute the regex. int captured_pattern_count = pcret_exec(re, extra, aHaystack, (int)_tcslen(aHaystack), 0, 0, offset, RXM_INT_COUNT); if (captured_pattern_count < 0) // PCRE_ERROR_NOMATCH or some kind of error. return NULL; // Otherwise, captured_pattern_count>=0 (it's 0 when offset[] was too small; but that's harmless in this case). return aHaystack + offset[0]; // Return the position of the entire-pattern match. } FResult RegExReplace(ExprTokenType &aHaystack, StrArg aNeedle, ExprTokenType *aReplacement, int *aOutCount, optl<int> aLimit, optl<int> aStartingPos, ResultToken &aRetVal) { RegExSearch ss; if (!ss.Prepare(aHaystack, aNeedle, aStartingPos)) return ss.fresult; return ss.Replace(aReplacement, aOutCount, aLimit, aRetVal); } FResult RegExSearch::Replace(ExprTokenType *aReplacement, int *aOutCount, optl<int> aLimit, ResultToken &aRetVal) const { int starting_offset = this->starting_offset; // Reduces code size and allows this function to be const. FResult fresult = OK; auto offset = (int *)_alloca(number_of_ints_in_offset * sizeof(int)); // _alloca() boosts performance and seems safe because subpattern_count would usually have to be ridiculously high to cause a stack overflow. int replacement_count = 0; // Get the replacement text (if any) from the incoming parameters. If it was omitted, treat it as "". TCHAR repl_buf[MAX_NUMBER_SIZE]; LPTSTR replacement = _T(""); size_t replacement_length = 0; ResultToken result_token; ExprTokenType matchobj_token, *params; IObject *callback_obj = nullptr; result_token.mem_to_free = nullptr; if (aReplacement) { if (callback_obj = TokenToObject(*aReplacement)) { fresult = ValidateFunctor(callback_obj, 1); if (FAILED(fresult)) return fresult; params = &matchobj_token; matchobj_token.symbol = SYM_OBJECT; result_token.InitResult(repl_buf); } else replacement = TokenToString(*aReplacement, repl_buf, &replacement_length); } // In PCRE, lengths and such are confined to ints, so there's little reason for using unsigned for anything. int captured_pattern_count, empty_string_is_not_a_match, match_length, ref_num , result_size, new_result_length, haystack_portion_length, second_iteration, substring_name_length , extra_offset, pcre_options; TCHAR *haystack_pos, *match_pos, *src, *src_end, *src_orig, *closing_brace, *substring_name_pos; TCHAR *dest, char_after_dollar , substring_name[33] // In PCRE, "Names consist of up to 32 alphanumeric characters and underscores." , transform; // Caller has provided mem_to_free (initially NULL) as a means of passing back memory we allocate here. // So if we change "result" to be non-NULL, the caller will take over responsibility for freeing that memory. LPTSTR &result = aRetVal.mem_to_free; // Make an alias for convenience. size_t &result_length = aRetVal.marker_length; // MANDATORY FOR USERS OF MEM_TO_FREE: set marker_length to the length of the string. result_size = 0; // And caller has already set "result" to be NULL. The buffer is allocated only upon result_length = 0; // first use to avoid a potentially massive allocation that might be wasted and cause swapping (not to mention that we'll have better ability to estimate the correct total size after the first replacement is discovered). // Below uses a temp variable because realloc() returns NULL on failure but leaves original block allocated. // Note that if it's given a NULL pointer, realloc() does a malloc() instead. LPTSTR realloc_temp; #define REGEX_REALLOC(size) \ {\ result_size = size;\ if ( !(realloc_temp = trealloc(result, result_size)) )\ goto out_of_mem;\ result = realloc_temp;\ } // See if a replacement limit was specified. If not, use the default (-1 means "replace all"). int limit = aLimit.value_or(-1); // aStartingOffset is altered further on in the loop; but for its initial value, the caller has ensured // that it lies within aHaystackLength. Also, if there are no replacements yet, haystack_pos ignores // aStartingOffset because otherwise, when the first replacement occurs, any part of haystack that lies // to the left of a caller-specified aStartingOffset wouldn't get copied into the result. for (empty_string_is_not_a_match = 0, haystack_pos = haystack ;; haystack_pos = haystack + starting_offset) // See comment above. { // Execute the expression to find the next match. captured_pattern_count = (limit == 0) ? PCRE_ERROR_NOMATCH // Only when limit is exactly 0 are we done replacing. All negative values are "replace all". : pcret_exec(re, extra, haystack, haystack_length, starting_offset , empty_string_is_not_a_match, offset, number_of_ints_in_offset); if (captured_pattern_count == PCRE_ERROR_NOMATCH) { if (empty_string_is_not_a_match && starting_offset < haystack_length && limit != 0) // replacement_count>0 whenever empty_string_is_not_a_match!=0. { // This situation happens when a previous iteration found a match but it was the empty string. // That iteration told the pcre_exec that just occurred above to try to match something other than "" // at the same position. But since we're here, it wasn't able to find such a match. So just copy // the current character over literally then advance to the next character to resume normal searching. empty_string_is_not_a_match = 0; // Reset so that the next iteration starts off with the normal matching method. #ifdef UNICODE // Need to avoid chopping a supplementary Unicode character in half. WCHAR c = haystack_pos[0]; if (IS_SURROGATE_PAIR(c, haystack_pos[1])) // i.e. one supplementary character. { result[result_length++] = c; result[result_length++] = haystack_pos[1]; starting_offset += 2; // Supplementary characters are in the range U+010000 to U+10FFFF, continue; } #endif result[result_length++] = *haystack_pos; // This can't overflow because the size calculations in a previous iteration reserved 3 bytes: 1 for this character, 1 for the possible LF that follows CR, and 1 for the terminator. ++starting_offset; // Advance to next candidate section of haystack. // v1.0.46.06: This following section was added to avoid finding a match between a CR and LF // when PCRE_NEWLINE_ANY mode is in effect. The fact that this is the only change for // PCRE_NEWLINE_ANY relies on the belief that any pattern that matches the empty string in between // a CR and LF must also match the empty string that occurs right before the CRLF (even if that // pattern also matched a non-empty string right before the empty one in front of the CRLF). If // this belief is correct, no logic similar to this is needed near the bottom of the main loop // because the empty string found immediately prior to this CRLF will put us into // empty_string_is_not_a_match mode, which will then execute this section of code (unless // empty_string_is_not_a_match mode actually found a match, in which case the logic here seems // superseded by that match?) Even if this reasoning is not a complete solution, it might be // adequate if patterns that match empty strings are rare, which I believe they are. In fact, // they might be so rare that arguably this could be documented as a known limitation rather than // having added the following section of code in the first place. // Examples that illustrate the effect: // MsgBox % "<" . RegExReplace("`r`n", "`a).*", "xxx") . ">" // MsgBox % "<" . RegExReplace("`r`n", "`am)^.*$", "xxx") . ">" if (*haystack_pos == '\r' && haystack_pos[1] == '\n') { // pcre_fullinfo() is a fast call, so it's called every time to simplify the code (I don't think // this whole "empty_string_is_not_a_match" section of code executes for most patterns anyway, // so performance seems less of a concern). if (!pcret_fullinfo(re, extra, PCRE_INFO_OPTIONS, &pcre_options) // Success. && (pcre_options & PCRE_NEWLINE_ANY)) { result[result_length++] = '\n'; // This can't overflow because the size calculations in a previous iteration reserved 3 bytes: 1 for this character, 1 for the possible LF that follows CR, and 1 for the terminator. ++starting_offset; // Skip over this LF because it "belongs to" the CR that preceded it. } } continue; // i.e. we're not done yet because the "no match" above was a special one and there's still more haystack to check. } // Otherwise, there aren't any more matches. So we're all done except for copying the last part of // haystack into the result (if applicable). if (replacement_count) // And by definition, result!=NULL due in this case to prior iterations. { if (haystack_portion_length = haystack_length - starting_offset) // This is the remaining part of haystack that needs to be copied over as-is. { new_result_length = (int)result_length + haystack_portion_length; if (new_result_length >= result_size) REGEX_REALLOC(new_result_length + 1); // This will end the loop if an alloc error occurs. tmemcpy(result + result_length, haystack_pos, haystack_portion_length); // memcpy() usually benches a little faster than _tcscpy(). result_length = new_result_length; // Remember that result_length is actually an output for our caller, so even if for no other reason, it must be kept accurate for that. } result[result_length] = '\0'; // result!=NULL when replacement_count!=0. Also, must terminate it unconditionally because other sections usually don't do it. // Set RegExMatch()'s return value to be "result": aRetVal.marker = result; // Caller will take care of freeing result's memory. } else // No replacements were actually done, so just return the original string to avoid malloc+memcpy // (in addition, returning the original might help the caller make other optimizations). { aRetVal.marker = haystack; aRetVal.marker_length = haystack_length; // There's no need to do the following because it should already be that way when replacement_count==0. //if (result) // free(result); //result = NULL; // This tells the caller that we already freed it (i.e. from its POV, we never allocated anything). } aRetVal.symbol = SYM_STRING; goto set_count_and_return; // All done. } // Otherwise: if (captured_pattern_count < 0) // An error other than "no match". These seem very rare, so it seems best to abort rather than yielding a partially-converted result. { fresult = this->fresult; if (fresult == OK) // Checked in case a callout already exited/raised an error. fresult = PCREExecError(captured_pattern_count); goto abort; // Goto vs. break to leave replacement_count set to 0. } // Otherwise (since above didn't return or break or continue), a match has been found (i.e. // captured_pattern_count > 0; it should never be 0 in this case because that only happens // when offset[] is too small, which it isn't). ++replacement_count; --limit; // It's okay if it goes below -1 because all negatives are treated as "replace all". match_pos = haystack + offset[0]; // This is the location in aHaystack of the entire-pattern match. int match_end_offset = offset[1]; haystack_portion_length = (int)(match_pos - haystack_pos); // The length of the haystack section between the end of the previous match and the start of the current one. // Handle this replacement by making two passes through the replacement-text: The first calculates the size // (which avoids having to constantly check for buffer overflow with potential realloc at multiple stages). // The second iteration copies the replacement (along with any literal text in haystack before it) into the // result buffer (which was expanded if necessary by the first iteration). for (second_iteration = 0; second_iteration < 2; ++second_iteration) // second_iteration is used as a boolean for readability. { if (second_iteration) { // Using the required length calculated by the first iteration, expand/realloc "result" if necessary. if (new_result_length + 3 > result_size) // Must use +3 not +1 in case of empty_string_is_not_a_match (which needs room for up to two extra characters). { // The first expression passed to REGEX_REALLOC is the average length of each replacement so far. // It's more typically more accurate to pass that than the following "length of current // replacement": // new_result_length - haystack_portion_length - (aOffset[1] - aOffset[0]) // Above is the length difference between the current replacement text and what it's // replacing (it's negative when replacement is smaller than what it replaces). REGEX_REALLOC((int)PredictReplacementSize((new_result_length - match_end_offset) / replacement_count // See above. , replacement_count, limit, haystack_length, new_result_length+2, match_end_offset)); // +2 in case of empty_string_is_not_a_match (which needs room for up to two extra characters). The function will also do another +1 to convert length to size (for terminator). // The above will return if an alloc error occurs. } //else result_size is not only large enough, but also non-zero. Other sections rely on it always // being non-zero when replacement_count>0. // Before doing the actual replacement and its backreferences, copy over the part of haystack that // appears before the match. if (haystack_portion_length) { tmemcpy(result + result_length, haystack_pos, haystack_portion_length); result_length += haystack_portion_length; } dest = result + result_length; // Init dest for use by the loops further below. } else // i.e. it's the first iteration, so begin calculating the size required. new_result_length = (int)result_length + haystack_portion_length; // Init length to the part of haystack before the match (it must be copied over as literal text). // Calculate the actual replacement string through the callback function if (callback_obj) { if (second_iteration) { tmemcpy(dest, replacement, result_token.marker_length); result_length += result_token.marker_length; free(result_token.mem_to_free); result_token.mem_to_free = nullptr; } else { fresult = CreateMatchArray(offset, captured_pattern_count, matchobj_token.object); if (FAILED(fresult)) goto abort; result_token.SetValue(_T("")); callback_obj->Invoke(result_token, IT_CALL, nullptr, ExprTokenType{ callback_obj }, &params, 1); matchobj_token.object->Release(); if (result_token.symbol == SYM_OBJECT) { auto obj = result_token.object; result_token.SetValue(_T("")); ObjectToString(result_token, ExprTokenType{ obj }, obj); obj->Release(); } if (result_token.Exited()) { fresult = FR_FAIL; goto abort; } replacement = TokenToString(result_token, repl_buf, &replacement_length); new_result_length += (int)replacement_length; } continue; } // DOLLAR SIGN ($) is the only method supported because it simplifies the code, improves performance, // and avoids the need to escape anything other than $ (which simplifies the syntax). for (src = replacement, src_end = src + replacement_length; ; ++src) // For each '$' (increment to skip over the symbol just found by the inner for()). { // Find the next '$', if any. src_orig = src; // Init once for both loops below. if (second_iteration) // Mode: copy src-to-dest. { while (src < src_end && *src != '$') // While looking for the next '$', copy over everything up until the '$'. *dest++ = *src++; result_length += (int)(src - src_orig); } else // This is the first iteration (mode: size-calculation). { for (; src < src_end && *src != '$'; ++src); // Find the next '$', if any. new_result_length += (int)(src - src_orig); // '$' or '\0' was found: same expansion either way. } if (src == src_end) // Reached the end of the replacement text. break; // Nothing left to do, so if this is the first major iteration, begin the second. // Otherwise, a '$' has been found. Check if it's a backreference and handle it. // But first process any special flags that are present. transform = '\0'; // Set default. Indicate "no transformation". extra_offset = 0; // Set default. Indicate that there's no need to hop over an extra character. if (char_after_dollar = src[1]) // This check avoids calling ctoupper on '\0', which directly or indirectly causes an assertion error in CRT. { switch(char_after_dollar = ctoupper(char_after_dollar)) { case 'U': case 'L': case 'T': transform = char_after_dollar; extra_offset = 1; char_after_dollar = src[2]; // Ignore the transform character for the purposes of backreference recognition further below. break; //else leave things at their defaults. } } //else leave things at their defaults. ref_num = INT_MIN; // Set default to "no valid backreference". Use INT_MIN to virtually guaranty that anything other than INT_MIN means that something like a backreference was found (even if it's invalid, such as ${-5}). switch (char_after_dollar) { case '{': // Found a backreference: ${... substring_name_pos = src + 2 + extra_offset; if (closing_brace = _tcschr(substring_name_pos, '}')) { if (substring_name_length = (int)(closing_brace - substring_name_pos)) { if (substring_name_length < _countof(substring_name)) { tcslcpy(substring_name, substring_name_pos, substring_name_length + 1); // +1 to convert length to size, which truncates the new string at the desired position. if (IsNumeric(substring_name, true, false, true)) // Seems best to allow floating point such as 1.0 because it will then get truncated to an integer. It seems to rare that anyone would want to use floats as names. ref_num = _ttoi(substring_name); // Uses _ttoi() vs. ATOI to avoid potential overlap with non-numeric names such as ${0x5}, which should probably be considered a name not a number? In other words, seems best not to make some names that start with numbers "special" just because they happen to be hex numbers. else // For simplicity, no checking is done to ensure it consists of the "32 alphanumeric characters and underscores". Let pcre_get_stringnumber() figure that out for us. ref_num = pcret_get_first_set(re, substring_name, offset); // Returns a negative on failure, which when stored in ref_num is relied upon as an indicator. } //else it's too long, so it seems best (debatable) to treat it as a unmatched/unfound name, i.e. "". src = closing_brace; // Set things up for the next iteration to resume at the char after "${..}" } //else it's ${}, so do nothing, which in effect will treat it all as literal text. } //else unclosed '{': for simplicity, do nothing, which in effect will treat it all as literal text. break; case '$': // i.e. Two consecutive $ amounts to one literal $. ++src; // Skip over the first '$', and the loop's increment will skip over the second. "extra_offset" is ignored due to rarity and silliness. Just transcribe things like $U$ as U$ to indicate the problem. break; // This also sets up things properly to copy a single literal '$' into the result. case '\0': // i.e. a single $ was found at the end of the string. break; // Seems best to treat it as literal (strictly speaking the script should have escaped it). default: if (char_after_dollar >= '0' && char_after_dollar <= '9') // Treat it as a single-digit backreference. CONSEQUENTLY, $15 is really $1 followed by a literal '5'. { ref_num = char_after_dollar - '0'; // $0 is the whole pattern rather than a subpattern. src += 1 + extra_offset; // Set things up for the next iteration to resume at the char after $d. Consequently, $19 is seen as $1 followed by a literal 9. } //else not a digit: do nothing, which treats a $x as literal text (seems ok since like $19, $name will never be supported due to ambiguity; only ${name}). } // switch (char_after_dollar) if (ref_num == INT_MIN) // Nothing that looks like backreference is present (or the very unlikely ${-2147483648}). { if (second_iteration) { *dest++ = *src; // src is incremented by the loop. Copy only one character because the enclosing loop will take care of copying the rest. ++result_length; // Update the actual length. } else ++new_result_length; // Update the calculated length. // And now the enclosing loop will take care of the characters beyond src. } else // Something that looks like a backreference was found, even if it's invalid (e.g. ${-5}). { // It seems to improve convenience and flexibility to transcribe a nonexistent backreference // as a "" rather than literally (e.g. putting a ${1} literally into the new string). Although // putting it in literally has the advantage of helping debugging, it doesn't seem to outweigh // the convenience of being able to specify nonexistent subpatterns. MORE IMPORANTLY a subpattern // might not exist per se if it hasn't been matched, such as an "or" like (abc)|(xyz), at least // when it's the last subpattern, in which case it should definitely be treated as "" and not // copied over literally. So that would have to be checked for if this is changed. if (ref_num >= 0 && ref_num < captured_pattern_count) // Treat ref_num==0 as reference to the entire-pattern's match. { int ref_num0 = offset[ref_num*2]; int ref_num1 = offset[ref_num*2 + 1]; match_length = ref_num1 - ref_num0; if (match_length) { if (second_iteration) { tmemcpy(dest, haystack + ref_num0, match_length); if (transform) { dest[match_length] = '\0'; // Terminate for use below (shouldn't cause overflow because REALLOC reserved space for terminator; nor should there be any need to undo the termination afterward). switch(transform) { case 'U': CharUpper(dest); break; case 'L': CharLower(dest); break; case 'T': StrToTitleCase(dest); break; } } dest += match_length; result_length += match_length; } else // First iteration. new_result_length += match_length; } } //else subpattern doesn't exist (or it's invalid such as ${-5}, so treat it as blank because: // 1) It's boosts script flexibility and convenience (at the cost of making it hard to detect // script bugs, which would be assisted by transcribing ${999} as literal text rather than ""). // 2) It simplifies the code. // 3) A subpattern might not exist per se if it hasn't been matched, such as "(abc)|(xyz)" // (in which case only one of them is matched). If such a thing occurs at the end // of the RegEx pattern, captured_pattern_count might not include it. But it seems // pretty clear that it should be treated as "" rather than some kind of error condition. } } // for() (for each '$') } // for() (a 2-iteration for-loop) // If we're here, a match was found. // Technique and comments from pcredemo.c: // If the previous match was NOT an empty string, we can just start the next match at the end // of the previous one. // If the previous match WAS an empty string, we can't do that, as it would lead to an // infinite loop. Instead, a special call of pcre_exec() is made with the PCRE_NOTEMPTY and // PCRE_ANCHORED flags set. The first of these tells PCRE that an empty string is not a valid match; // other possibilities must be tried. The second flag restricts PCRE to one match attempt at the // initial string position. If this match succeeds, that means there are two valid matches at the // SAME position: one for the empty string, and other for a non-empty string after it. BOTH of // these matches are considered valid, and BOTH are eligible for replacement by RegExReplace(). // // The following may be one example of this concept: // In the string "xy", replace the pattern "x?" by "z". The traditional/proper answer (achieved by // the logic here) is "zzyz" because: 1) The first x is replaced by z; 2) The empty string before y // is replaced by z; 3) the logic here applies PCRE_NOTEMPTY to search again at the same position, but // that search doesn't find a match; so the logic higher above advances to the next character (y) and // continues the search; it finds the empty string at the end of haystack, which is replaced by z. // On the other hand, maybe there's a better example than the above that explains what would happen // if PCRE_NOTEMPTY actually finds a match, or what would happen if this PCRE_NOTEMPTY method weren't // used at all (i.e. infinite loop as mentioned in the previous paragraph). // // If this match is "" (length 0), then by definition we just found a match in normal mode, not // PCRE_NOTEMPTY mode (since that mode isn't capable of finding ""). Thus, empty_string_is_not_a_match // is currently 0. If "" was just found (and replaced), now try to find a second match at the same // position, but one that isn't "". This is done by switching to an alternate mode and doing another // iteration. Otherwise (the match found above wasn't "") advance to next candidate section of haystack // and resume searching. // v1.0.48.04: Fixed line below to reset to 0 (if appropriate) so that it doesn't get stuck in // PCRE_NOTEMPTY-mode for one extra iteration. Otherwise there are too few replacements (4 vs. 5) // in examples like: // RegExReplace("ABC", "Z*|A", "x") empty_string_is_not_a_match = (offset[0] == offset[1]) ? PCRE_NOTEMPTY|PCRE_ANCHORED : 0; starting_offset = match_end_offset; // In either case, set starting offset to the candidate for the next search. } // for() // All paths above should return (or goto some other label), so execution should never reach here except // through goto: out_of_mem: fresult = FR_E_OUTOFMEM; abort: if (result) { free(result); // Since result is probably an non-terminated string (not to mention an incompletely created result), it seems best to free it here to remove it from any further consideration by the caller. result = NULL; // Tell caller that it was freed. } // Now fall through to below so that count is set even for out-of-memory error. set_count_and_return: free(result_token.mem_to_free); if (aOutCount) *aOutCount = replacement_count; return fresult; } bool RegExSearch::Prepare(ExprTokenType &aHaystack, StrArg aNeedle, optl<int> aStartingPos) { if (TokenToObject(aHaystack)) { fresult = FParamError(0, &aHaystack, _T("String")); return false; } // COMPILE THE REGEX OR GET IT FROM CACHE. if ( !(re = get_compiled_regex(aNeedle, extra, &options_length, &fresult)) ) // Compiling problem. return false; // It already reported the error. // Since compiling succeeded, get info about other parameters. size_t temp_length; haystack = TokenToString(aHaystack, haystack_buf, &temp_length); haystack_length = (int)temp_length; if (!aStartingPos.has_value()) starting_offset = 0; // The one-based starting position in haystack (if any). Convert it to zero-based. else { starting_offset = aStartingPos.value(); if (starting_offset <= 0) // Same convention as SubStr(): Treat negative StartingPos as a position relative to the end of the string. { starting_offset += haystack_length; if (starting_offset < 0) starting_offset = 0; } else if (starting_offset > haystack_length) // Although pcre_exec() seems to work properly even without this check, its absence would allow // the empty string to be found beyond the length of haystack, which could lead to problems and is // probably more trouble than its worth (assuming it has any worth -- perhaps for a pattern that // looks backward from itself; but that seems too rare to support and might create code that's // harder to maintain, especially in RegExReplace()). starting_offset = haystack_length; // Due to rarity of this condition, opt for simplicity: just point it to the terminator, which is in essence an empty string (which will cause result in "no match" except when searcing for ""). else --starting_offset; // Convert to zero-based. } // SET UP THE OFFSET ARRAY, which consists of int-pairs containing the start/end offset of each match. pcret_fullinfo(re, extra, PCRE_INFO_CAPTURECOUNT, &pattern_count); // The number of capturing subpatterns (i.e. all except (?:xxx) I think). Failure is not checked because it seems too unlikely in this case. ++pattern_count; // Increment to include room for the entire-pattern match. number_of_ints_in_offset = pattern_count * 3; // PCRE uses 3 ints for each (sub)pattern: 2 for offsets and 1 for its internal use. // The remaining setup is for callouts (?C) and (*MARK:NAME): re_text = const_cast<LPTSTR>(aNeedle); if (extra) { // S (study) option was specified, use existing pcre_extra struct. extra->flags |= PCRE_EXTRA_CALLOUT_DATA | PCRE_EXTRA_MARK; } else { // Use caller-allocated pcre_extra struct to pass callout_data. extra = &extra_buf; extra->flags = PCRE_EXTRA_CALLOUT_DATA | PCRE_EXTRA_MARK; } // extra->callout_data is used to pass callout_data to PCRE. extra->callout_data = this; // extra->mark is used by PCRE to return the NAME of a (*MARK:NAME), if encountered. extra->mark = UorA(wchar_t **, UCHAR **) &mark; fresult = OK; return true; } FResult RegExMatch(ExprTokenType &aHaystack, StrArg aNeedle, IObject** aMatchObj, optl<int> aStartingPos, int &aFoundPos) { RegExSearch ss; if (!ss.Prepare(aHaystack, aNeedle, aStartingPos)) return ss.fresult; return ss.Match(aMatchObj, aFoundPos); } FResult RegExSearch::Match(IObject** aMatchObj, int &aFoundPos) const { auto offset = (int *)_alloca(number_of_ints_in_offset * sizeof(int)); // _alloca() boosts performance and seems safe because subpattern_count would usually have to be ridiculously high to cause a stack overflow. // EXECUTE THE REGEX. int captured_pattern_count = pcret_exec(re, extra, haystack, haystack_length , starting_offset, 0, offset, number_of_ints_in_offset); // SET THE RETURN VALUE BASED ON THE RESULTS OF EXECUTING THE EXPRESSION. if (captured_pattern_count == PCRE_ERROR_NOMATCH) { aFoundPos = 0; } else if (captured_pattern_count < 0) // An error other than "no match". { if (fresult != OK) // A callout exited/raised an error. return fresult; return PCREExecError(captured_pattern_count); } else // Match found, and captured_pattern_count >= 0 (but should never be 0 in this case because that only happens when offset[] is too small, which it isn't). { aFoundPos = offset[0] + 1; // i.e. the position of the entire-pattern match is the function's return value. } if (aMatchObj) return CreateMatchArray(offset, captured_pattern_count, *aMatchObj); return OK; } BIF_DECL(Op_RegEx) { if (ParamIndexToObject(1)) _f_throw_param(1, _T("String")); auto needle = TokenToString(*aParam[1], aResultToken.buf); int found_pos; auto fresult = RegExMatch(*aParam[0], needle, nullptr, nullptr, found_pos); if (FAILED(fresult)) FResultToError(aResultToken, aParam, aParamCount, fresult, 0); else aResultToken.SetValue(found_pos); }
65,357
C++
.cpp
1,128
54.431738
318
0.72205
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,101
Gui.ListView.cpp
AutoHotkey_AutoHotkey/source/lib/Gui.ListView.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "script_gui.h" #define CTRL_THROW_IF_DESTROYED if (!hwnd) return ControlDestroyedError() FResult ControlDestroyedError(); FResult GuiControlType::LV_GetCount(optl<StrArg> aMode, int &aRetVal) { CTRL_THROW_IF_DESTROYED; if (aMode.is_blank_or_omitted()) { aRetVal = (int)SendMessage(hwnd, LVM_GETITEMCOUNT, 0, 0); return OK; } auto options = aMode.value(); if (ctoupper(*options) == 'S') aRetVal = (int)SendMessage(hwnd, LVM_GETSELECTEDCOUNT, 0, 0); else if (!_tcsnicmp(options, _T("Col"), 3)) // "Col" or "Column". Don't allow "C" by itself, so that "Checked" can be added in the future. aRetVal = union_lv_attrib->col_count; else return FR_E_ARG(0); return OK; } // LV.GetNext: // Returns: The index of the found item, or 0 on failure. // Parameters: // 1: Starting index (one-based when it comes in). If absent, search starts at the top. // 2: Options string. FResult GuiControlType::LV_GetNext(optl<int> aStartIndex, optl<StrArg> aRowType, int &aRetVal) { CTRL_THROW_IF_DESTROYED; HWND control_hwnd = hwnd; int index = -1; if (aStartIndex.has_value()) { index = aStartIndex.value() - 1; // -1 to convert to zero-based. // For flexibility, allow index to be less than -1 to avoid first-iteration complications in script loops // (such as when deleting rows, which shifts the row index upward, require the search to resume at // the previously found index rather than the row after it). However, reset it to -1 to ensure // proper return values from the API in the "find checked item" mode used below. if (index < -1) index = -1; // Signal it to start at the top. } // For performance, decided to always find next selected item when the "C" option hasn't been specified, // even when the checkboxes style is in effect. Otherwise, would have to fetch and check checkbox style // bit for each call, which would slow down this heavily-called function. auto options = aRowType.value_or_empty(); TCHAR first_char = ctoupper(*omit_leading_whitespace(options)); // To retain compatibility in the future, also allow "Check(ed)" and "Focus(ed)" since any word that // starts with C or F is already supported. switch(first_char) { case '\0': // Listed first for performance. case 'F': aRetVal = ListView_GetNextItem(control_hwnd, index , first_char ? LVNI_FOCUSED : LVNI_SELECTED) + 1; // +1 to convert to 1-based. return OK; case 'C': // Checkbox: Find checked items. For performance assume that the control really has checkboxes. { int item_count = ListView_GetItemCount(control_hwnd); for (int i = index + 1; i < item_count; ++i) // Start at index+1 to omit the first item from the search (for consistency with the other mode above). if (ListView_GetCheckState(control_hwnd, i)) // Item's box is checked. { aRetVal = i + 1; // +1 to convert from zero-based to one-based. return OK; } // Since above didn't return, no match found. aRetVal = 0; return OK; } default: return FR_E_ARG(1); } } FResult GuiControlType::LV_GetText(int aRow, optl<int> aColumn, StrRet &aRetVal) // Returns: Text on success. // Throws on failure. // Parameters: // 1: Row index (one-based when it comes in). // 2: Column index (one-based when it comes in). { CTRL_THROW_IF_DESTROYED; int row_index = aRow - 1; // -1 to convert to zero-based. if (row_index < -1) // row_index==-1 is reserved to mean "get column heading's text". return FR_E_ARG(0); // If parameter 2 is omitted, default to the first column (index 0): int col_index = aColumn.has_value() ? aColumn.value() - 1 : 0; // -1 to convert to zero-based. if (col_index < 0) return FR_E_ARG(1); TCHAR buf[LV_TEXT_BUF_SIZE]; if (row_index == -1) // Special mode to get column's text. { LVCOLUMN lvc; lvc.cchTextMax = LV_TEXT_BUF_SIZE - 1; // See notes below about -1. lvc.pszText = buf; lvc.mask = LVCF_TEXT; if (SendMessage(hwnd, LVM_GETCOLUMN, col_index, (LPARAM)&lvc)) // Assign. return aRetVal.Copy(lvc.pszText) ? OK : FR_E_OUTOFMEM; // See notes below about why pszText is used instead of buf (might apply to this too). else // On failure, it seems best to throw. return FR_E_FAILED; } else // Get row's indicated item or subitem text. { LVITEM lvi; // Subtract 1 because of that nagging doubt about size vs. length. Some MSDN examples subtract one, such as // TabCtrl_GetItem()'s cchTextMax: lvi.iItem = row_index; lvi.iSubItem = col_index; // Which field to fetch. If it's zero, the item vs. subitem will be fetched. lvi.mask = LVIF_TEXT; lvi.pszText = buf; lvi.cchTextMax = LV_TEXT_BUF_SIZE - 1; // Note that LVM_GETITEM doesn't update this member to reflect the new length. // Unlike LVM_GETITEMTEXT, LVM_GETITEM indicates success or failure, which seems more useful/preferable // as a return value since a text length of zero would be ambiguous: could be an empty field or a failure. if (SendMessage(hwnd, LVM_GETITEM, 0, (LPARAM)&lvi)) // Assign // Must use lvi.pszText vs. buf because MSDN says: "Applications should not assume that the text will // necessarily be placed in the specified buffer. The control may instead change the pszText member // of the structure to point to the new text rather than place it in the buffer." return aRetVal.Copy(lvi.pszText) ? OK : FR_E_OUTOFMEM; // See notes below about why pszText is used instead of buf (might apply to this too). else // On failure, it seems best to throw. return FR_E_FAILED; } } FResult GuiControlType::LV_AddInsertModify(optl<int> aRow, optl<StrArg> aOptions, VariantParams &aCol , int *aRetVal, bool aModify) // Returns: 1 on success and 0 on failure. // Parameters: // 1: For Add(), this is the options. For Insert/Modify, it's the row index (one-based when it comes in). // 2: For Add(), this is the first field's text. For Insert/Modify, it's the options. // 3 and beyond: Additional field text. // In Add/Insert mode, if there are no text fields present, a blank for is appended/inserted. { CTRL_THROW_IF_DESTROYED; TCHAR buf[MAX_NUMBER_SIZE]; GuiControlType &control = *this; int index; if (!aRow.has_value()) // Add { index = INT_MAX; // Use INT_MAX as a signal to append the item rather than inserting it. } else // Insert or Modify { index = aRow.value() - 1; // -1 to convert to zero-based. if (index < (aModify ? -1 : 0)) // Allow -1 to mean "all rows" when in modify mode. return FR_E_ARG(0); } bool ensure_visible = false, is_checked = false; // Checkmark. int col_start_index = 0; LVITEM lvi; lvi.mask = LVIF_STATE; // LVIF_STATE: state member is valid, but only to the extent that corresponding bits are set in stateMask (the rest will be ignored). lvi.stateMask = 0; lvi.state = 0; // Parse list of space-delimited options: LPCTSTR next_option, option_end; bool adding; // Whether this option is being added (+) or removed (-). for (next_option = aOptions.value_or_empty(); *next_option; next_option = omit_leading_whitespace(option_end)) { if (*next_option == '-') { adding = false; // omit_leading_whitespace() is not called, which enforces the fact that the option word must // immediately follow the +/- sign. This is done to allow the flexibility to have options // omit the plus/minus sign, and also to reserve more flexibility for future option formats. ++next_option; // Point it to the option word itself. } else { // Assume option is being added in the absence of either sign. However, when we were // called by GuiControl(), the first option in the list must begin with +/- otherwise the cmd // would never have been properly detected as GUICONTROL_CMD_OPTIONS in the first place. adding = true; if (*next_option == '+') ++next_option; // Point it to the option word itself. //else do not increment, under the assumption that the plus has been omitted from a valid // option word and is thus an implicit plus. } if (!*next_option) // In case the entire option string ends in a naked + or -. break; // Find the end of this option item: if ( !(option_end = StrChrAny(next_option, _T(" \t"))) ) // Space or tab. option_end = next_option + _tcslen(next_option); // Set to position of zero terminator instead. if (option_end == next_option) continue; // i.e. the string contains a + or - with a space or tab after it, which is intentionally ignored. if (!_tcsnicmp(next_option, _T("Select"), 6)) // Could further allow "ed" suffix by checking for that inside, but "Selected" is getting long so it doesn't seem something many would want to use. { next_option += 6; // If it's Select0, invert the mode to become "no select". This allows a boolean variable // to be more easily applied, such as this expression: "Select" . VarContainingState if (next_option < option_end && !ATOI(next_option)) adding = !adding; // Another reason for not having "Select" imply "Focus" by default is that it would probably // reduce performance when selecting all or a large number of rows. // Because a row might or might not have focus, the script may wish to retain its current // focused state. For this reason, "select" does not imply "focus", which allows the // LVIS_FOCUSED bit to be omitted from the stateMask, which in turn retains the current // focus-state of the row rather than disrupting it. lvi.stateMask |= LVIS_SELECTED; if (adding) lvi.state |= LVIS_SELECTED; //else removing, so the presence of LVIS_SELECTED in the stateMask above will cause it to be de-selected. } else if (!_tcsnicmp(next_option, _T("Focus"), 5)) { next_option += 5; if (next_option < option_end && !ATOI(next_option)) // If it's Focus0, invert the mode to become "no focus". adding = !adding; lvi.stateMask |= LVIS_FOCUSED; if (adding) lvi.state |= LVIS_FOCUSED; //else removing, so the presence of LVIS_FOCUSED in the stateMask above will cause it to be de-focused. } else if (!_tcsnicmp(next_option, _T("Check"), 5)) { // The rationale for not checking for an optional "ed" suffix here and incrementing next_option by 2 // is that: 1) It would be inconsistent with the lack of support for "selected" (see reason above); // 2) Checkboxes in a ListView are fairly rarely used, so code size reduction might be more important. next_option += 5; if (next_option < option_end && !ATOI(next_option)) // If it's Check0, invert the mode to become "unchecked". adding = !adding; if (aModify) // v1.0.46.10: Do this section only for Modify, not Add/Insert, to avoid generating an extra "unchecked" notification when a row is added/inserted with an initial state of "checked". In other words, the script now receives only a "checked" notification, not an "unchecked+checked". Search on is_checked for more comments. { lvi.stateMask |= LVIS_STATEIMAGEMASK; lvi.state |= adding ? 0x2000 : 0x1000; // The #1 image is "unchecked" and the #2 is "checked". } is_checked = adding; } else if (!_tcsnicmp(next_option, _T("Col"), 3)) { if (adding) { col_start_index = ATOI(next_option + 3) - 1; // The ability to start at a column other than 1 (i.e. subitem vs. item). if (col_start_index < 0) col_start_index = 0; } } else if (!_tcsnicmp(next_option, _T("Icon"), 4)) { // Testing shows that there is no way to avoid having an item icon in report view if the // ListView has an associated small-icon ImageList (well, perhaps you could have it show // a blank square by specifying an invalid icon index, but that doesn't seem useful). // If LVIF_IMAGE is entirely omitted when adding and item/row, the item will take on the // first icon in the list. This is probably by design because the control wants to make // each item look consistent by indenting its first field by a certain amount for the icon. if (adding) { lvi.mask |= LVIF_IMAGE; lvi.iImage = ATOI(next_option + 4) - 1; // -1 to convert to zero-based. } //else removal of icon currently not supported (see comment above), so do nothing in order // to reserve "-Icon" in case a future way can be found to do it. } else if ((option_end - next_option) == 3 && !_tcsnicmp(next_option, _T("Vis"), 3)) // v1.0.44 { // Since this option much more typically used with LV.Modify than LV.Add/Insert, the technique of // Vis%VarContainingOneOrZero% isn't supported, to reduce code size. ensure_visible = adding; // Ignored by modes other than LV.Modify(), since it's not really appropriate when adding a row (plus would add code complexity). } else { return FValueError(ERR_INVALID_OPTION, next_option); } } // Suppress any events raised by the changes made below: control.attrib |= GUI_CONTROL_ATTRIB_SUPPRESS_EVENTS; // More maintainable and performs better to have a separate struct for subitems vs. items. LVITEM lvi_sub; // Ensure mask is pure to avoid giving it any excuse to fail due to the fact that // "You cannot set the state or lParam members for subitems." lvi_sub.mask = LVIF_TEXT; int i, j, rows_to_change; if (index == -1) // Modify all rows (above has ensured that this is only happens in modify-mode). { rows_to_change = ListView_GetItemCount(control.hwnd); lvi.iItem = 0; ensure_visible = false; // Not applicable when operating on all rows. } else // Modify or insert a single row. Set it up for the loop to perform exactly one iteration. { rows_to_change = 1; lvi.iItem = index; // Which row to operate upon. This can be a huge number such as 999999 if the caller wanted to append vs. insert. } lvi.iSubItem = 0; // Always zero to operate upon the item vs. sub-item (subitems have their own LVITEM struct). for (j = 0; j < rows_to_change; ++j, ++lvi.iItem) // ++lvi.iItem because if the loop has more than one iteration, by definition it is modifying all rows starting at 0. { if (aCol.count && col_start_index == 0 && aCol.value[0]->symbol != SYM_MISSING) // The first field/column is present, so include that when setting the item. { lvi.pszText = TokenToString(*aCol.value[0], buf); // Fairly low-overhead, so called every iteration for simplicity (so that buf can be used for both items and subitems). lvi.mask |= LVIF_TEXT; } if (!aModify) // Insert or Add. { // Note that ListView_InsertItem() will append vs. insert if the index is too large, in which case // it returns the items new index (which will be the last item in the list unless the control has // auto-sort style). if ( -1 == (lvi_sub.iItem = ListView_InsertItem(control.hwnd, &lvi)) ) { control.attrib &= ~GUI_CONTROL_ATTRIB_SUPPRESS_EVENTS; // Re-enable events. return OK; // Since item can't be inserted, no reason to try attaching any subitems to it. } // Update iItem with the actual index assigned to the item, which might be different than the // specified index if the control has an auto-sort style in effect. This new iItem value // is used for ListView_SetCheckState() and for the attaching of any subitems to this item. if (aRetVal) *aRetVal = lvi_sub.iItem + 1; // Convert from zero-based to 1-based. // For add/insert (but not modify), testing shows that checkmark must be added only after // the item has been inserted rather than provided in the lvi.state/stateMask fields. // MSDN confirms this by saying "When an item is added with [LVS_EX_CHECKBOXES], // it will always be set to the unchecked state [ignoring any value placed in bits // 12 through 15 of the state member]." if (is_checked) ListView_SetCheckState(control.hwnd, lvi_sub.iItem, TRUE); // TRUE = Check the row's checkbox. // Note that 95/NT4 systems that lack comctl32.dll 4.70+ distributed with MSIE 3.x // do not support LVS_EX_CHECKBOXES, so the above will have no effect for them. } else // Modify. { // Rather than trying to detect if anything was actually changed, this is called // unconditionally to simplify the code (ListView_SetItem() is probably very fast if it // discovers that lvi.mask==LVIF_STATE and lvi.stateMask==0). // By design (to help catch script bugs), a failure here does not revert to append mode. ListView_SetItem(control.hwnd, &lvi); lvi_sub.iItem = lvi.iItem; // In preparation for modifying any subitems that need it. if (ensure_visible) // Seems best to do this one prior to "select" below. SendMessage(control.hwnd, LVM_ENSUREVISIBLE, lvi.iItem, FALSE); // PartialOK==FALSE is somewhat arbitrary. } // For each remaining parameter, assign its text to a subitem. // Testing shows that if the control has too few columns for all of the fields/parameters // present, the ones at the end are automatically ignored: they do not consume memory nor // do they significantly impact performance (at least on Windows XP). For this reason, there // is no code above the for-loop above to reduce aParamCount if it's "too large" because // it might reduce flexibility (in case future/past OSes allow non-existent columns to be // populated, or in case current OSes allow the contents of recently removed columns to be modified). for (lvi_sub.iSubItem = (col_start_index > 1) ? col_start_index : 1 // Start at the first subitem unless we were told to start at or after the third column. // "i" starts at 1 (the third parameter) unless col_start_index is greater than 0, in which case // it starts at 0 (the second parameter) because that parameter has not yet been assigned to anything: , i = (col_start_index == 0) ; i < aCol.count ; ++i, ++lvi_sub.iSubItem) { if (aCol.value[i]->symbol == SYM_MISSING) // Omitted, such as LV.Modify(1,Opt,"One",,"Three"). continue; lvi_sub.pszText = TokenToString(*aCol.value[i], buf); // Done every time through the outer loop since it's not high-overhead, and for code simplicity. ListView_SetItem(control.hwnd, &lvi_sub); } } // outer for() // When the control has no rows, work around the fact that LVM_SETITEMCOUNT delivers less than 20% // of its full benefit unless done after the first row is added (at least on XP SP1). A non-zero // row_count_hint tells us that this message should be sent after the row has been inserted/appended: if (control.union_lv_attrib->row_count_hint > 0 && !aModify) { SendMessage(control.hwnd, LVM_SETITEMCOUNT, control.union_lv_attrib->row_count_hint, 0); // Last parameter should be 0 for LVS_OWNERDATA (verified if you look at the definition of ListView_SetItemCount macro). control.union_lv_attrib->row_count_hint = 0; // Reset so that it only gets set once per request. } control.attrib &= ~GUI_CONTROL_ATTRIB_SUPPRESS_EVENTS; // Re-enable events. return OK; } FResult GuiControlType::LV_Delete(optl<int> aRow) // Returns: 1 on success and 0 on failure. // Parameters: // 1: Row index (one-based when it comes in). { CTRL_THROW_IF_DESTROYED; if (!aRow.has_value()) { SendMessage(hwnd, LVM_DELETEALLITEMS, 0, 0); return OK; } // Since above didn't return, there is a first parameter present. int index = aRow.value() - 1; // -1 to convert to zero-based. if (index < 0) // Even if aRow.value()==0, for safety, it seems best not to do a delete-all. return FR_E_ARG(0); SendMessage(hwnd, LVM_DELETEITEM, index, 0); return OK; } FResult GuiControlType::LV_DeleteCol(int aColumn) { CTRL_THROW_IF_DESTROYED; int index = aColumn - 1; // -1 to convert to zero-based. if (!ListView_DeleteColumn(hwnd, index)) return FR_E_FAILED; // It's important to note that when the user slides columns around via drag and drop, the // column index as seen by the script is not changed. This is fortunate because otherwise, // the lv_attrib.col array would get out of sync with the column indices. Testing shows that // all of the following operations respect the original column index, regardless of where the // user may have moved the column physically: InsertCol, DeleteCol, ModifyCol. Insert and Delete // shifts the indices of those columns that *originally* lay to the right of the affected column. lv_attrib_type &lv_attrib = *union_lv_attrib; if (lv_attrib.col_count > 0) // Avoid going negative, which would otherwise happen if script previously added columns by calling the API directly. --lv_attrib.col_count; // Must be done prior to the below. if (index < lv_attrib.col_count) // When a column other than the last was removed, adjust the array so that it stays in sync with actual columns. MoveMemory(lv_attrib.col+index, lv_attrib.col+index+1, sizeof(lv_col_type)*(lv_attrib.col_count-index)); return OK; } FResult GuiControlType::LV_InsertModifyCol(optl<int> aColumn, optl<StrArg> aOptions, optl<StrArg> aTitle, int *aRetVal, bool aModify) // Returns: 1 on success and 0 on failure. // Parameters: // 1: Column index (one-based when it comes in). // 2: String of options // 3: New text of column // There are also some special modes when only zero or one parameter is present, see below. { CTRL_THROW_IF_DESTROYED; GuiControlType &control = *this; GuiType &gui = *control.gui; lv_attrib_type &lv_attrib = *control.union_lv_attrib; DWORD view_mode = ListView_GetView(control.hwnd); int index; if (aColumn.has_value()) index = aColumn.value() - 1; // -1 to convert to zero-based. else if (!aModify) // InsertCol(,...) index = lv_attrib.col_count; // When no insertion index was specified, append to the end of the list. else // ModifyCol() { // v1.0.36.03: Don't attempt to auto-size the columns while the view is not report-view because // that causes any subsequent switch to the "list" view to be corrupted (invisible icons and items): if (view_mode != LV_VIEW_DETAILS || aOptions.has_value() || aTitle.has_value()) return FR_E_ARGS; for (int i = 0; ; ++i) // Don't limit it to lv_attrib.col_count in case script added extra columns via direct API calls. if (!ListView_SetColumnWidth(control.hwnd, i, LVSCW_AUTOSIZE)) // Failure means last column has already been processed. break; return OK; } // Do this prior to checking if index is in bounds so that it can support columns beyond LV_MAX_COLUMNS: if (aModify && !aOptions.has_value() && !aTitle.has_value()) // A single parameter is a special modify-mode to auto-size that column. { // v1.0.36.03: Don't attempt to auto-size the columns while the view is not report-view because // that causes any subsequent switch to the "list" view to be corrupted (invisible icons and items): if (view_mode != LV_VIEW_DETAILS) return FR_E_ARGS; ListView_SetColumnWidth(control.hwnd, index, LVSCW_AUTOSIZE); return OK; } if (!aModify) { if (lv_attrib.col_count >= LV_MAX_COLUMNS) // No room to insert or append. return FR_E_FAILED; if (index >= lv_attrib.col_count) // For convenience, fall back to "append" when index too large. index = lv_attrib.col_count; } //else do nothing so that modification and deletion of columns that were added via script's // direct calls to the API can sort-of work (it's documented in the help file that it's not supported, // since col-attrib array can get out of sync with actual columns that way). if (index < 0 || index >= LV_MAX_COLUMNS) return FR_E_ARG(0); // Avoid array under/overflow below. // It's done the following way so that when in insert-mode, if the column fails to be inserted, don't // have to remove the inserted array element from the lv_attrib.col array: lv_col_type temp_col = {0}; // Init unconditionally even though only needed for InsertCol. lv_col_type &col = aModify ? lv_attrib.col[index] : temp_col; // Done only after index has been confirmed in-bounds. LVCOLUMN lvc; lvc.mask = LVCF_FMT; if (aModify) // Fetch the current format so that it's possible to leave parts of it unaltered. ListView_GetColumn(control.hwnd, index, &lvc); else // Mode is "insert". lvc.fmt = 0; // Init defaults prior to parsing options: bool sort_now = false; int do_auto_size = aModify ? 0 : LVSCW_AUTOSIZE_USEHEADER; // Default to auto-size for new columns. TCHAR sort_now_direction = 'A'; // Ascending. int new_justify = lvc.fmt & LVCFMT_JUSTIFYMASK; // Simplifies the handling of the justification bitfield. //lvc.iSubItem = 0; // Not necessary if the LVCF_SUBITEM mask-bit is absent. // Parse list of space-delimited options: auto options = aOptions.value_or_empty(); TCHAR option_word[16]; // Enough for any single option word or number, with room to avoid false positives due to truncation. LPCTSTR next_option, option_end; bool adding; // Whether this option is being added (+) or removed (-). for (next_option = options; *next_option; next_option = omit_leading_whitespace(option_end)) { if (*next_option == '-') { adding = false; // omit_leading_whitespace() is not called, which enforces the fact that the option word must // immediately follow the +/- sign. This is done to allow the flexibility to have options // omit the plus/minus sign, and also to reserve more flexibility for future option formats. ++next_option; // Point it to the option word itself. } else { // Assume option is being added in the absence of either sign. However, when we were // called by GuiControl(), the first option in the list must begin with +/- otherwise the cmd // would never have been properly detected as GUICONTROL_CMD_OPTIONS in the first place. adding = true; if (*next_option == '+') ++next_option; // Point it to the option word itself. //else do not increment, under the assumption that the plus has been omitted from a valid // option word and is thus an implicit plus. } if (!*next_option) // In case the entire option string ends in a naked + or -. break; // Find the end of this option item: for (option_end = next_option; *option_end && !IS_SPACE_OR_TAB(*option_end); ++option_end); if (option_end == next_option) continue; // i.e. the string contains a + or - with a space or tab after it, which is intentionally ignored. // Make a copy to simplify comparisons below. tcslcpy(option_word, next_option, min((option_end - next_option) + 1, _countof(option_word))); // For simplicity, the value of "adding" is ignored for this and the other number/alignment options. if (!_tcsicmp(option_word, _T("Integer"))) { // For simplicity, changing the col.type dynamically (since it's so rarely needed) // does not try to set up col.is_now_sorted_ascending so that the next click on the column // puts it into default starting order (which is ascending unless the Desc flag was originally // present). col.type = LV_COL_INTEGER; new_justify = LVCFMT_RIGHT; } else if (!_tcsicmp(option_word, _T("Float"))) { col.type = LV_COL_FLOAT; new_justify = LVCFMT_RIGHT; } else if (!_tcsicmp(option_word, _T("Text"))) // Seems more approp. name than "Str" or "String" // Since "Text" is so general, it seems to leave existing alignment (Center/Right) as it is. col.type = LV_COL_TEXT; // The following can exist by themselves or in conjunction with the above. They can also occur // *after* one of the above words so that alignment can be used to override the default for the type; // e.g. "Integer Left" to have left-aligned integers. else if (!_tcsicmp(option_word, _T("Right"))) new_justify = adding ? LVCFMT_RIGHT : LVCFMT_LEFT; else if (!_tcsicmp(option_word, _T("Center"))) new_justify = adding ? LVCFMT_CENTER : LVCFMT_LEFT; else if (!_tcsicmp(option_word, _T("Left"))) // Supported so that existing right/center column can be changed back to left. new_justify = LVCFMT_LEFT; // The value of "adding" seems inconsequential so is ignored. else if (!_tcsicmp(option_word, _T("Uni"))) // Unidirectional sort (clicking the column will not invert to the opposite direction). col.unidirectional = adding; else if (!_tcsicmp(option_word, _T("Desc"))) // Make descending order the default order (applies to uni and first click of col for non-uni). col.prefer_descending = adding; // So that the next click will toggle to the opposite direction. else if (!_tcsnicmp(option_word, _T("Case"), 4)) { if (adding) col.case_sensitive = !_tcsicmp(option_word + 4, _T("Locale")) ? SCS_INSENSITIVE_LOCALE : SCS_SENSITIVE; else col.case_sensitive = SCS_INSENSITIVE; } else if (!_tcsicmp(option_word, _T("Logical"))) // v1.0.44.12: Supports StrCmpLogicalW() method of sorting. col.case_sensitive = SCS_INSENSITIVE_LOGICAL; else if (!_tcsnicmp(option_word, _T("Sort"), 4)) // This is done as an option vs. LV.SortCol/LV.Sort so that the column's options can be changed simultaneously with a "sort now" to refresh. { // Defer the sort until after all options have been parsed and applied. sort_now = true; if (!_tcsicmp(option_word + 4, _T("Desc"))) sort_now_direction = 'D'; // Descending. } else if (!_tcsicmp(option_word, _T("NoSort"))) // Called "NoSort" so that there's a way to enable and disable the setting via +/-. col.sort_disabled = adding; else if (!_tcsnicmp(option_word, _T("Auto"), 4)) // No separate failure result is reported for this item. // In case the mode is "insert", defer auto-width of column until col exists. do_auto_size = _tcsicmp(option_word + 4, _T("Hdr")) ? LVSCW_AUTOSIZE : LVSCW_AUTOSIZE_USEHEADER; else if (!_tcsnicmp(option_word, _T("Icon"), 4)) { if (!_tcsicmp(option_word + 4, _T("Right"))) { if (adding) lvc.fmt |= LVCFMT_BITMAP_ON_RIGHT; else lvc.fmt &= ~LVCFMT_BITMAP_ON_RIGHT; } else // Assume its an icon number or the removal of the icon via -Icon. { if (adding) { lvc.mask |= LVCF_IMAGE; lvc.fmt |= LVCFMT_IMAGE; // Flag this column as displaying an image. lvc.iImage = ATOI(next_option + 4) - 1; // -1 to convert to zero based. Use next_option since option_word might be truncated. } else lvc.fmt &= ~LVCFMT_IMAGE; // Flag this column as NOT displaying an image. } } else // Handle things that are more general than the above, such as single letter options and pure numbers. { // Width does not have a W prefix to permit a naked expression to be used as the entirely of // options. For example: LV.SetCol(1, old_width + 10) // v1.0.37: Fixed to allow floating point (although ATOI below will convert it to integer). if (IsNumeric(option_word, true, false, true)) // Above has already verified that *next_option can't be whitespace. { lvc.mask |= LVCF_WIDTH; int width = gui.Scale(ATOI(next_option)); // Specifying a width when the column is initially added prevents the scrollbar from // updating on Windows 7 and 10 (but not XP). As a workaround, initialise the width // to 0 and then resize it afterward. do_auto_size is overloaded for this purpose // since it's already passed to ListView_SetColumnWidth(). if (!aModify && view_mode == LV_VIEW_DETAILS) { lvc.cx = 0; // Must be zero; if width is zero, ListView_SetColumnWidth() won't be called. do_auto_size = width; // If non-zero, this is passed to ListView_SetColumnWidth(). } else { lvc.cx = width; do_auto_size = 0; // Turn off any auto-sizing that may have been put into effect (explicitly or by default). } } else { return FValueError(ERR_INVALID_OPTION, option_word); } } } // Apply any changed justification/alignment to the fmt bit field: lvc.fmt = (lvc.fmt & ~LVCFMT_JUSTIFYMASK) | new_justify; if (aTitle.has_value()) // Parameter #3 (text) is present. { lvc.pszText = const_cast<LPTSTR>(aTitle.value()); lvc.mask |= LVCF_TEXT; } if (aModify) // ModifyCol // For code simplicity, this is called unconditionally even if nothing needs updating. ListView_SetColumn(control.hwnd, index, &lvc); else // InsertCol { // It's important to note that when the user slides columns around via drag and drop, the // column index as seen by the script is not changed. This is fortunate because otherwise, // the lv_attrib.col array would get out of sync with the column indices. Testing shows that // all of the following operations respect the original column index, regardless of where the // user may have moved the column physically: InsertCol, DeleteCol, ModifyCol. Insert and Delete // shifts the indices of those columns that *originally* lay to the right of the affected column. // Doesn't seem to do anything -- not even with respect to inserting a new first column with it's // unusual behavior of inheriting the previously column's contents -- so it's disabled for now. // Testing shows that it also does not seem to cause a new column to inherit the indicated subitem's // text, even when iSubItem is set to index + 1 vs. index: //lvc.mask |= LVCF_SUBITEM; //lvc.iSubItem = index; // Testing shows that the following serve to set the column's physical/display position in the // heading to iOrder without affecting the specified index. This concept is very similar to // when the user drags and drops a column heading to a new position: it's index doesn't change, // only it's displayed position: //lvc.mask |= LVCF_ORDER; //lvc.iOrder = index + 1; if ( -1 == (index = ListView_InsertColumn(control.hwnd, index, &lvc)) ) return OK; // Since column could not be inserted, return so that below, sort-now, etc. are not done. if (aRetVal) *aRetVal = index + 1; // +1 to convert the new index to 1-based. if (index < lv_attrib.col_count) // Since col is not being appended to the end, make room in the array to insert this column. MoveMemory(lv_attrib.col+index+1, lv_attrib.col+index, sizeof(lv_col_type)*(lv_attrib.col_count-index)); // Above: Shift columns to the right by one. lv_attrib.col[index] = col; // Copy temp struct's members to the correct element in the array. // The above is done even when index==0 because "col" may contain attributes set via the Options // parameter. Therefore, for code simplicity and rarity of real-world need, no attempt is made // to make the following idea work: // When index==0, retain the existing attributes due to the unique behavior of inserting a new first // column: The new first column inherit's the old column's values (fields), so it seems best to also have it // inherit the old column's attributes. ++lv_attrib.col_count; // New column successfully added. Must be done only after the MoveMemory() above. } // Auto-size is done only at this late a stage, in case column was just created above. // Note that ListView_SetColumn() apparently does not support LVSCW_AUTOSIZE_USEHEADER for it's "cx" member. // do_auto_size contains the actual column width if mode == 'I' and a width was passed by the caller. if (do_auto_size && view_mode == LV_VIEW_DETAILS) ListView_SetColumnWidth(control.hwnd, index, do_auto_size); // retval was previously set to the more important result above. //else v1.0.36.03: Don't attempt to auto-size the columns while the view is not report-view because // that causes any subsequent switch to the "list" view to be corrupted (invisible icons and items). if (sort_now) GuiType::LV_Sort(control, index, false, sort_now_direction); return OK; } FResult GuiControlType::LV_SetImageList(UINT_PTR aImageListID, optl<int> aIconType, UINT_PTR &aRetVal) // Returns (MSDN): "handle to the image list previously associated with the control if successful; NULL otherwise." // Parameters: // 1: HIMAGELIST obtained from somewhere such as IL_Create(). // 2: Optional: Type of list. { CTRL_THROW_IF_DESTROYED; HIMAGELIST himl = (HIMAGELIST)aImageListID; int list_type; if (aIconType.has_value()) list_type = aIconType.value(); else // Auto-detect large vs. small icons based on the actual icon size in the image list. { int cx, cy; ImageList_GetIconSize(himl, &cx, &cy); list_type = (cx > GetSystemMetrics(SM_CXSMICON)) ? LVSIL_NORMAL : LVSIL_SMALL; } aRetVal = (UINT_PTR)ListView_SetImageList(hwnd, himl, list_type); return OK; }
36,607
C++
.cpp
685
50.366423
338
0.715824
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,102
math.cpp
AutoHotkey_AutoHotkey/source/lib/math.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "qmath.h" #include "script.h" #include <stdint.h> #include "script_func_impl.h" BIF_DECL(BIF_Round) // For simplicity, this always yields something numeric (or a string that's numeric). // Even Round(empty_or_unintialized_var) is zero rather than "" or "NaN". { // In the future, a string conversion algorithm might be better to avoid the loss // of 64-bit integer precision that is currently caused by the use of doubles in // the calculation: int param2; double multiplier; if (aParamCount > 1) { Throw_if_Param_NaN(1); param2 = ParamIndexToInt(1); multiplier = qmathPow(10, param2); } else // Omitting the parameter is the same as explicitly specifying 0 for it. { param2 = 0; multiplier = 1; } Throw_if_Param_NaN(0); double value = ParamIndexToDouble(0); value = (value >= 0.0 ? qmathFloor(value * multiplier + 0.5) : qmathCeil(value * multiplier - 0.5)) / multiplier; // If incoming value is an integer, it seems best for flexibility to convert it to a // floating point number whenever the second param is >0. That way, it can be used // to "cast" integers into floats. Conversely, it seems best to yield an integer // whenever the second param is <=0 or omitted. if (param2 > 0) { // v1.0.44.01: Since Round (in its param2>0 mode) is almost always used to facilitate some kind of // display or output of the number (hardly ever for intentional reducing the precision of a floating // point math operation), it seems best by default to omit only those trailing zeroes that are beyond // the specified number of decimal places. This is done by converting the result into a string here, // which will cause the expression evaluation to write out the final result as this very string as long // as no further floating point math is done on it (such as Round(3.3333, 2)+0). Also note that not // all trailing zeros are removed because it is often the intent that exactly the number of decimal // places specified should be *shown* (for column alignment, etc.). For example, Round(3.5, 2) should // be 3.50 not 3.5. Similarly, Round(1, 2) should be 1.00 not 1 (see above comment about "casting" for // why. // Performance: This method is about twice as slow as the old method (which did merely the line // "aResultToken.symbol = SYM_FLOAT" in place of the below). However, that might be something // that can be further optimized in the caller (its calls to _tcslen, memcpy, etc. might be optimized // someday to omit certain calls when very simply situations allow it). In addition, twice as slow is // not going to impact the vast majority of scripts since as mentioned above, Round (in its param2>0 // mode) is almost always used for displaying data, not for intensive operations within a expressions. // AS DOCUMENTED: Round(..., positive_number) displays exactly positive_number decimal places, which // might be inconsistent with normal float->string conversion. If it wants, the script can force the // result to be formatted the normal way (omitting trailing 0s) by adding 0 to the result. // Also, a new parameter an be added someday to trim excess trailing zeros from param2>0's result // (e.g. Round(3.50, 2, true) can be 3.5 rather than 3.50), but this seems less often desired due to // column alignment and other goals where consistency is important. LPTSTR buf = _f_retval_buf; int len = _stprintf(buf, _T("%0.*f"), param2, value); // %f can handle doubles in MSVC++. _f_return_p(buf, len); } else // Fix for v1.0.47.04: See BIF_FloorCeil() for explanation of this fix. Currently, the only known example // of when the fix is necessary is the following script in release mode (not debug mode): // myNumber := 1043.22 ; Bug also happens with -1043.22 (negative). // myRounded1 := Round( myNumber, -1 ) ; Stores 1040 (correct). // ChartModule := DllCall("LoadLibrary", "str", "rmchart.dll") // myRounded2 := Round( myNumber, -1 ) ; Stores 1039 (wrong). _f_return_i((__int64)(value + (value > 0 ? 0.2 : -0.2))); // Formerly above simply returned (__int64)value. } BIF_DECL(BIF_FloorCeil) // Probably saves little code size to merge extremely short/fast functions, hence FloorCeil. // Floor() rounds down to the nearest integer; that is, to the integer that lies to the left on the // number line (this is not the same as truncation because Floor(-1.2) is -2, not -1). // Ceil() rounds up to the nearest integer; that is, to the integer that lies to the right on the number line. // // For simplicity and backward compatibility, a numeric result is always returned (even if the input // is non-numeric or an empty string). { Throw_if_Param_NaN(0); // The qmath routines are used because Floor() and Ceil() are deceptively difficult to implement in a way // that gives the correct result in all permutations of the following: // 1) Negative vs. positive input. // 2) Whether or not the input is already an integer. // Therefore, do not change this without conducting a thorough test. double x = ParamIndexToDouble(0); x = (_f_callee_id == FID_Floor) ? qmathFloor(x) : qmathCeil(x); // Fix for v1.0.40.05: For some inputs, qmathCeil/Floor yield a number slightly to the left of the target // integer, while for others they yield one slightly to the right. For example, Ceil(62/61) and Floor(-4/3) // yield a double that would give an incorrect answer if it were simply truncated to an integer via // type casting. The below seems to fix this without breaking the answers for other inputs (which is // surprisingly harder than it seemed). There is a similar fix in BIF_Round(). _f_return_i((__int64)(x + (x > 0 ? 0.2 : -0.2))); } BIF_DECL(BIF_Mod) { // Load-time validation has already ensured there are exactly two parameters. // "Cast" each operand to Int64/Double depending on whether it has a decimal point. ExprTokenType param0, param1; if (ParamIndexToNumber(0, param0) && ParamIndexToNumber(1, param1)) // Both are numeric. { if (param0.symbol == SYM_INTEGER && param1.symbol == SYM_INTEGER) // Both are integers. { if (param1.value_int64 == 0) _f_throw(ERR_DIVIDEBYZERO, ErrorPrototype::ZeroDivision); // For performance, % is used vs. qmath for integers. _f_return_i(param0.value_int64 % param1.value_int64); } else // At least one is a floating point number. { double dividend = TokenToDouble(param0); double divisor = TokenToDouble(param1); if (divisor == 0.0) _f_throw(ERR_DIVIDEBYZERO, ErrorPrototype::ZeroDivision); _f_return(qmathFmod(dividend, divisor)); } } // Since above didn't return, one or both parameters were invalid. _f_throw(ERR_PARAM_INVALID, ErrorPrototype::Type); } BIF_DECL(BIF_MinMax) { // Supports one or more parameters. // Load-time validation has already ensured there is at least one parameter. ExprTokenType param; int index, ib_index = 0, db_index = 0; bool isMin = _f_callee_id == FID_Min; __int64 ia, ib = 0; double da, db = 0; bool ib_empty = TRUE, db_empty = TRUE; for (int i = 0; i < aParamCount; ++i) { ParamIndexToNumber(i, param); switch (param.symbol) { case SYM_INTEGER: // Compare only integers. ia = param.value_int64; if ((ib_empty) || (isMin ? ia < ib : ia > ib)) { ib_empty = FALSE; ib = ia; ib_index = i; } break; case SYM_FLOAT: // Compare only floats. da = param.value_double; if ((db_empty) || (isMin ? da < db : da > db)) { db_empty = FALSE; db = da; db_index = i; } break; default: // Non-operand or non-numeric string. _f_throw_param(i, _T("Number")); } } // Compare found integer with found float: index = (db_empty || !ib_empty && (isMin ? ib < db : ib > db)) ? ib_index : db_index; ParamIndexToNumber(index, param); aResultToken.symbol = param.symbol; aResultToken.value_int64 = param.value_int64; } BIF_DECL(BIF_Abs) { if (!TokenToDoubleOrInt64(*aParam[0], aResultToken)) // "Cast" token to Int64/Double depending on whether it has a decimal point. _f_throw_param(0, _T("Number")); // Non-operand or non-numeric string. if (aResultToken.symbol == SYM_INTEGER) { // The following method is used instead of __abs64() to allow linking against the multi-threaded // DLLs (vs. libs) if that option is ever used (such as for a minimum size AutoHotkeySC.bin file). // It might be somewhat faster than __abs64() anyway, unless __abs64() is a macro or inline or something. if (aResultToken.value_int64 < 0) aResultToken.value_int64 = -aResultToken.value_int64; } else // Must be SYM_FLOAT due to the conversion above. aResultToken.value_double = qmathFabs(aResultToken.value_double); } BIF_DECL(BIF_Sin) // For simplicity and backward compatibility, a numeric result is always returned (even if the input // is non-numeric or an empty string). { Throw_if_Param_NaN(0); _f_return(qmathSin(ParamIndexToDouble(0))); } BIF_DECL(BIF_Cos) // For simplicity and backward compatibility, a numeric result is always returned (even if the input // is non-numeric or an empty string). { Throw_if_Param_NaN(0); _f_return(qmathCos(ParamIndexToDouble(0))); } BIF_DECL(BIF_Tan) // For simplicity and backward compatibility, a numeric result is always returned (even if the input // is non-numeric or an empty string). { Throw_if_Param_NaN(0); _f_return(qmathTan(ParamIndexToDouble(0))); } BIF_DECL(BIF_ASinACos) { Throw_if_Param_NaN(0); double value = ParamIndexToDouble(0); if (value > 1 || value < -1) // ASin and ACos aren't defined for such values. { _f_throw_param(0); } else { // For simplicity and backward compatibility, a numeric result is always returned in this case (even if // the input is non-numeric or an empty string). _f_return((_f_callee_id == FID_ASin) ? qmathAsin(value) : qmathAcos(value)); } } BIF_DECL(BIF_ATan) // For simplicity and backward compatibility, a numeric result is always returned (even if the input // is non-numeric or an empty string). { Throw_if_Param_NaN(0); _f_return(qmathAtan(ParamIndexToDouble(0))); } BIF_DECL(BIF_ATan2) // For simplicity and backward compatibility, a numeric result is always returned (even if the input // is non-numeric or an empty string). { Throw_if_Param_NaN(0); Throw_if_Param_NaN(1); _f_return(qmathAtan2(ParamIndexToDouble(0), ParamIndexToDouble(1))); } BIF_DECL(BIF_Exp) { Throw_if_Param_NaN(0); _f_return(qmathExp(ParamIndexToDouble(0))); } BIF_DECL(BIF_SqrtLogLn) { Throw_if_Param_NaN(0); double value = ParamIndexToDouble(0); if (value < 0) // Result is undefined in these cases. { _f_throw_param(0); } else { // For simplicity and backward compatibility, a numeric result is always returned in this case (even if // the input is non-numeric or an empty string). switch (_f_callee_id) { case FID_Sqrt: _f_return(qmathSqrt(value)); case FID_Log: _f_return(qmathLog10(value)); //case FID_Ln: default: _f_return(qmathLog(value)); } } } BIF_DECL(BIF_Random) { UINT64 rand = 0; if (!GenRandom(&rand, sizeof(rand))) _f_throw(ERR_INTERNAL_CALL); SymbolType arg1type = ParamIndexIsOmitted(0) ? SYM_MISSING : ParamIndexIsNumeric(0); SymbolType arg2type = ParamIndexIsOmitted(1) ? SYM_MISSING : ParamIndexIsNumeric(1); if (arg1type == PURE_NOT_NUMERIC) _f_throw_param(0, _T("Number")); if (arg2type == PURE_NOT_NUMERIC) _f_throw_param(1, _T("Number")); bool use_float = arg1type == PURE_FLOAT || arg2type == PURE_FLOAT || !aParamCount; // Let Random() be Random(0.0, 1.0). if (use_float) { double target_min = arg1type != SYM_MISSING ? ParamIndexToDouble(0) : 0.0; double target_max = arg2type != SYM_MISSING ? ParamIndexToDouble(1) : arg1type == SYM_MISSING ? 1.0 : 0.0; // Be permissive about the order of parameters, and convert Random(n) to Random(0, n). if (target_min > target_max) swap(target_min, target_max); // The first part below produces a 53-bit integer, and from that a value between // 0.0 (inclusive) and 1.0 (exclusive) with the maximum precision for a double. _f_return((((rand >> 11) / 9007199254740992.0) * (target_max - target_min)) + target_min); } else { INT64 target_min = arg1type != SYM_MISSING ? ParamIndexToInt64(0) : 0; INT64 target_max = arg2type != SYM_MISSING ? ParamIndexToInt64(1) : 0; // Be permissive about the order of parameters, and convert Random(n) to Random(0, n). if (target_min > target_max) swap(target_min, target_max); // Do NOT use floating-point to generate random integers because of cases like // min=0 and max=1: we want an even distribution of 1's and 0's in that case, not // something skewed that might result due to rounding/truncation issues caused by // the float method used above. // Furthermore, the simple modulo approach is biased when the target range does not // divide cleanly into rand. Suppose that rand ranges from 0..7, and the target range // is 0..2. By using modulo, rand is effectively divided into sets {0..2, 3..5, 6..7} // and each value in the set is mapped to the target range 0..2. Because the last set // maps to 0..1, 0 and 1 have greater chance of appearing than 2. However, since rand // is 64-bit, this isn't actually a problem for small ranges such as 1..100 due to the // vanishingly small chance of rand falling within the defective set. UINT64 u_max = (UINT64)(target_max - target_min); if (u_max < UINT64_MAX) { // What we actually want is (UINT64_MAX + 1) % (u_max + 1), but without overflow. UINT64 error_margin = UINT64_MAX % (u_max + 1); if (error_margin != u_max) // i.e. ((error_margin + 1) % (u_max + 1)) != 0. { ++error_margin; // error_margin is now the remainder after dividing (UINT64_MAX+1) by (u_max+1). // This is also the size of the incomplete number set which must be excluded to // ensure even distribution of random numbers. For simplicity we just take the // number set starting at 0, since use of modulo below will auto-correct. // For example, with a target range of 1..100, the error_margin should be 16, // which gives a mere 16 in 2**64 chance that a second iteration will be needed. while (rand < error_margin) // To ensure even distribution, keep trying until outside the error margin. GenRandom(&rand, sizeof(rand)); } rand %= (u_max + 1); } _f_return((INT64)(rand + (UINT64)target_min)); } } bif_impl FResult DateAdd(StrArg aDateTime, double aTime, StrArg aTimeUnits, StrRet &aRetVal) { FILETIME ft; if (!YYYYMMDDToFileTime(aDateTime, ft)) return FR_E_ARG(0); // Use double to support a floating point value for days, hours, minutes, etc: double nUnits = aTime; // Convert to seconds: switch (ctoupper(*aTimeUnits)) { case 'S': // Seconds break; case 'M': // Minutes nUnits *= ((double)60); break; case 'H': // Hours nUnits *= ((double)60 * 60); break; case 'D': // Days nUnits *= ((double)60 * 60 * 24); break; default: // Invalid return FR_E_ARG(2); } // Convert ft struct to a 64-bit variable (maybe there's some way to avoid these conversions): ULARGE_INTEGER ul; ul.LowPart = ft.dwLowDateTime; ul.HighPart = ft.dwHighDateTime; // Prior to adding nUnits to the result value, convert it from seconds to 10ths of a // microsecond (the units of the FILETIME struct). Use int64 multiplication to avoid // floating-point rounding errors, such as with values of seconds > 115292150460. // Testing shows this keeps precision beyond year 9999. Truncating any fractional part // is fine at this point because the resulting string only includes whole seconds. ul.QuadPart += (__int64)nUnits * 10000000; // Convert back into ft struct: ft.dwLowDateTime = ul.LowPart; ft.dwHighDateTime = ul.HighPart; aRetVal.SetTemp(FileTimeToYYYYMMDD(aRetVal.CallerBuf(), ft, false)); return OK; } bif_impl FResult DateDiff(StrArg aTime1, StrArg aTime2, StrArg aTimeUnits, __int64 &aRetVal) { FResult fr; // If either parameter is blank, it will default to the current time: __int64 time_until = YYYYMMDDSecondsUntil(aTime2, aTime1, fr); if (fr != OK) // Usually caused by an invalid component in the date-time string. return fr; switch (ctoupper(*aTimeUnits)) { case 'S': break; case 'M': time_until /= 60; break; // Minutes case 'H': time_until /= 60 * 60; break; // Hours case 'D': time_until /= 60 * 60 * 24; break; // Days default: // Invalid return FR_E_ARG(2); } aRetVal = time_until; return OK; }
17,035
C++
.cpp
390
41.125641
130
0.717205
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,103
process.cpp
AutoHotkey_AutoHotkey/source/lib/process.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "defines.h" #include "globaldata.h" #include "application.h" #include <Psapi.h> #include "script_func_impl.h" bif_impl UINT ProcessExist(optl<StrArg> aProcess) { // Return the discovered PID or zero if none. return aProcess.has_value() ? ProcessExist(aProcess.value()) : GetCurrentProcessId(); } bif_impl UINT ProcessGetParent(optl<StrArg> aProcess) { TCHAR buf[MAX_INTEGER_SIZE]; return ProcessExist(aProcess.has_value() ? aProcess.value() : ITOA(GetCurrentProcessId(), buf), true); } bif_impl FResult ProcessClose(StrArg aProcess, UINT &aRetVal) { aRetVal = 0; // Set default in case of failure. if (auto pid = ProcessExist(aProcess, false, false)) { if (auto hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid)) { if (TerminateProcess(hProcess, 0)) aRetVal = pid; // Indicate success. CloseHandle(hProcess); } } return OK; } static FResult ProcessGetPathName(optl<StrArg> aProcess, StrRet &aRetVal, bool aGetNameOnly) { auto pid = aProcess.has_value() ? ProcessExist(aProcess.value(), false, false) : GetCurrentProcessId(); if (!pid) return FError(ERR_NO_PROCESS, nullptr, ErrorPrototype::Target); TCHAR process_name[MAX_PATH]; if (!GetProcessName(pid, process_name, _countof(process_name), aGetNameOnly)) return FR_E_WIN32; return aRetVal.Copy(process_name) ? OK : FR_E_OUTOFMEM; } bif_impl FResult ProcessGetName(optl<StrArg> aProcess, StrRet &aRetVal) { return ProcessGetPathName(aProcess, aRetVal, true); } bif_impl FResult ProcessGetPath(optl<StrArg> aProcess, StrRet &aRetVal) { return ProcessGetPathName(aProcess, aRetVal, false); } void MsgSleepWithListLines(int aSleepDuration, Line *waiting_line, DWORD start_time); static FResult ProcessWait(StrArg aProcess, optl<double> aTimeout, UINT &aRetVal, bool aWaitClose) { DWORD pid; HANDLE proc = NULL; // This section is similar to that used for WINWAIT and RUNWAIT: bool wait_indefinitely; int sleep_duration, remainder; DWORD start_time = GetTickCount(); Line *waiting_line = g_script.mCurrLine; if (aTimeout.has_value()) // The param containing the timeout value was specified. { wait_indefinitely = false; sleep_duration = (int)(aTimeout.value_or(0) * 1000); // Can be zero. } else { wait_indefinitely = true; sleep_duration = 0; // Just to catch any bugs. } for (;;) { // Always do the first iteration so that at least one check is done. if (proc && WaitForSingleObject(proc, 0) != WAIT_TIMEOUT) { // Reset proc so that if a timeout occurs in this iteration, the PID won't be returned. // Don't reset pid directly because there might be other matching processes. CloseHandle(proc); proc = NULL; } if (!proc) pid = ProcessExist(aProcess); if ((!aWaitClose) == (pid != 0)) // i.e. condition of this cmd is satisfied. { // For WaitClose: Since PID cannot always be determined (i.e. if process never existed, // there was no need to wait for it to close), for consistency, return 0 on success. aRetVal = pid; return OK; } // Must use int or any negative result (due to exceeding sleep_duration) will be lost due to DWORD type: if (wait_indefinitely || (remainder = sleep_duration - (GetTickCount() - start_time)) > SLEEP_INTERVAL_HALF) { if (aWaitClose && (proc || (proc = OpenProcess(SYNCHRONIZE, FALSE, pid)))) { switch (MsgWaitForMultipleObjects(1, &proc, FALSE, wait_indefinitely ? INFINITE : remainder, QS_ALLINPUT)) { case WAIT_OBJECT_0: CloseHandle(proc); proc = NULL; // This process has closed, but we may need another iteration to verify that no other // matching processes are running. case WAIT_OBJECT_0 + 1: MsgSleepWithListLines(-1, waiting_line, start_time); continue; case WAIT_TIMEOUT: CloseHandle(proc); aRetVal = pid; return OK; // Avoid the 100ms sleep below. } // In case of failure, fall through: } MsgSleepWithListLines(100, waiting_line, start_time); // For performance reasons, don't check as often as the WinWait family does. } else // Done waiting. { if (proc) CloseHandle(proc); // Return 0 if ProcessWait times out; or the PID of the process that still exists // if ProcessWaitClose times out. aRetVal = pid; return OK; } } // for() } bif_impl FResult ProcessWait(StrArg aProcess, optl<double> aTimeout, UINT &aRetVal) { return ProcessWait(aProcess, aTimeout, aRetVal, false); } bif_impl FResult ProcessWaitClose(StrArg aProcess, optl<double> aTimeout, UINT &aRetVal) { return ProcessWait(aProcess, aTimeout, aRetVal, true); } bif_impl FResult ProcessSetPriority(StrArg aPriority, optl<StrArg> aProcess, UINT &aRetVal) { DWORD priority; switch (_totupper(*aPriority)) { case 'L': priority = IDLE_PRIORITY_CLASS; break; case 'B': priority = BELOW_NORMAL_PRIORITY_CLASS; break; case 'N': priority = NORMAL_PRIORITY_CLASS; break; case 'A': priority = ABOVE_NORMAL_PRIORITY_CLASS; break; case 'H': priority = HIGH_PRIORITY_CLASS; break; case 'R': priority = REALTIME_PRIORITY_CLASS; break; default: // Since above didn't break, aPriority was invalid. return FR_E_ARG(0); } DWORD pid = aProcess.has_nonempty_value() ? ProcessExist(aProcess.value(), false, false) : GetCurrentProcessId(); if (!pid) return FError(ERR_NO_PROCESS, nullptr, ErrorPrototype::Target); HANDLE hProcess = OpenProcess(PROCESS_SET_INFORMATION, FALSE, pid); if (!hProcess) return FR_E_WIN32; DWORD error = SetPriorityClass(hProcess, priority) ? NOERROR : GetLastError(); CloseHandle(hProcess); if (error) return FR_E_WIN32(error); aRetVal = pid; return OK; } bif_impl FResult Run(StrArg aTarget, optl<StrArg> aWorkingDir, optl<StrArg> aOptions, ResultToken *aOutPID) { HANDLE hprocess; auto result = g_script.ActionExec(aTarget, nullptr, aWorkingDir.value_or_null(), true , aOptions.value_or_null(), &hprocess, true, true); if (aOutPID && hprocess) aOutPID->SetValue((UINT)GetProcessId(hprocess)); return result ? OK : FR_FAIL; } DWORD GetProcessName(DWORD aProcessID, LPTSTR aBuf, DWORD aBufSize, bool aGetNameOnly) { *aBuf = '\0'; // Set default. HANDLE hproc; // Windows XP/2003 would require PROCESS_QUERY_INFORMATION, but those OSes are not supported. if ( !(hproc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, aProcessID)) ) return 0; // Benchmarks showed that attempting GetModuleBaseName/GetModuleFileNameEx // first did not help performance. Also, QueryFullProcessImageName appeared // to be slower than the following. DWORD buf_length = GetProcessImageFileName(hproc, aBuf, aBufSize); if (buf_length) { LPTSTR cp; if (aGetNameOnly) { // Convert full path to just name. cp = _tcsrchr(aBuf, '\\'); if (cp) tmemmove(aBuf, cp + 1, _tcslen(cp)); // Includes the null terminator. } else { // Convert device path to logical path. TCHAR device_path[MAX_PATH]; TCHAR letter[3]; letter[1] = ':'; letter[2] = '\0'; // For simplicity and because GetLogicalDriveStrings does not exist on Win2k, it is not used. for (*letter = 'A'; *letter <= 'Z'; ++(*letter)) { DWORD device_path_length = QueryDosDevice(letter, device_path, _countof(device_path)); if (device_path_length > 2) // Includes two null terminators. { device_path_length -= 2; if (!_tcsncmp(device_path, aBuf, device_path_length) && aBuf[device_path_length] == '\\') // Relies on short-circuit evaluation. { // Copy drive letter: aBuf[0] = letter[0]; aBuf[1] = letter[1]; // Contract path to remove remainder of device name. tmemmove(aBuf + 2, aBuf + device_path_length, buf_length - device_path_length + 1); buf_length -= device_path_length - 2; break; } } } } } CloseHandle(hproc); return buf_length; }
8,387
C++
.cpp
232
33.198276
134
0.726399
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,104
CCallback.cpp
AutoHotkey_AutoHotkey/source/lib/CCallback.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "globaldata.h" #include "application.h" #include "script_func_impl.h" #ifdef ENABLE_REGISTERCALLBACK struct RCCallbackFunc // Used by BIF_CallbackCreate() and related. { #ifdef WIN32_PLATFORM ULONG data1; //E8 00 00 00 ULONG data2; //00 8D 44 24 ULONG data3; //08 50 FF 15 UINT_PTR (CALLBACK **callfuncptr)(UINT_PTR*, char*); ULONG data4; //59 84 C4 nn USHORT data5; //FF E1 #endif #ifdef _WIN64 UINT64 data1; // 0xfffffffff9058d48 UINT64 data2; // 0x9090900000000325 void (*stub)(); UINT_PTR (CALLBACK *callfuncptr)(UINT_PTR*, char*); #endif //code ends UCHAR actual_param_count; // This is the actual (not formal) number of parameters passed from the caller to the callback. Kept adjacent to the USHORT above to conserve memory due to 4-byte struct alignment. #define CBF_CREATE_NEW_THREAD 1 #define CBF_PASS_PARAMS_POINTER 2 UCHAR flags; // Kept adjacent to above to conserve memory due to 4-byte struct alignment in 32-bit builds. IObject *func; // The function object to be called whenever the callback's caller calls callfuncptr. }; #ifdef _WIN64 extern "C" void RegisterCallbackAsmStub(); #endif UINT_PTR CALLBACK RegisterCallbackCStub(UINT_PTR *params, char *address) // Used by BIF_RegisterCallback(). // JGR: On Win32 parameters are always 4 bytes wide. The exceptions are functions which work on the FPU stack // (not many of those). Win32 is quite picky about the stack always being 4 byte-aligned, (I have seen only one // application which defied that and it was a patched ported DOS mixed mode application). The Win32 calling // convention assumes that the parameter size equals the pointer size. 64 integers on Win32 are passed on // pointers, or as two 32 bit halves for some functions... { #ifdef WIN32_PLATFORM RCCallbackFunc &cb = *((RCCallbackFunc*)(address-5)); //second instruction is 5 bytes after start (return address pushed by call) #else RCCallbackFunc &cb = *((RCCallbackFunc*) address); #endif BOOL pause_after_execute; // NOTES ABOUT INTERRUPTIONS / CRITICAL: // An incoming call to a callback is considered an "emergency" for the purpose of determining whether // critical/high-priority threads should be interrupted because there's no way easy way to buffer or // postpone the call. Therefore, NO check of the following is done here: // - Current thread's priority (that's something of a deprecated feature anyway). // - Current thread's status of Critical (however, Critical would prevent us from ever being called in // cases where the callback is triggered indirectly via message/dispatch due to message filtering // and/or Critical's ability to pump messes less often). // - INTERRUPTIBLE_IN_EMERGENCY (which includes g_MenuIsVisible and g_AllowInterruption), which primarily // affects SLEEP_WITHOUT_INTERRUPTION): It's debatable, but to maximize flexibility it seems best to allow // callbacks during the display of a menu and during SLEEP_WITHOUT_INTERRUPTION. For most callers of // SLEEP_WITHOUT_INTERRUPTION, interruptions seem harmless. For some it could be a problem, but when you // consider how rare such callbacks are (mostly just subclassing of windows/controls) and what those // callbacks tend to do, conflicts seem very rare. // Of course, a callback can also be triggered through explicit script action such as a DllCall of // EnumWindows, in which case the script would want to be interrupted unconditionally to make the call. // However, in those cases it's hard to imagine that INTERRUPTIBLE_IN_EMERGENCY wouldn't be true anyway. if (cb.flags & CBF_CREATE_NEW_THREAD) { if (g_nThreads >= g_MaxThreadsTotal) // To avoid array overflow, g_MaxThreadsTotal must not be exceeded except where otherwise documented. return 0; // See MsgSleep() for comments about the following section. InitNewThread(0, false, true); DEBUGGER_STACK_PUSH(_T("Callback")) } else { if (pause_after_execute = g->IsPaused) // Assign. { // v1.0.48: If the current thread is paused, this threadless callback would get stuck in // ExecUntil()'s pause loop (keep in mind that this situation happens only when a fast-mode // callback has been created without a script thread to control it, which goes against the // advice in the documentation). To avoid that, it seems best to temporarily unpause the // thread until the callback finishes. But for performance, tray icon color isn't updated. g->IsPaused = false; --g_nPausedThreads; // See below. // If g_nPausedThreads isn't adjusted here, g_nPausedThreads could become corrupted if the // callback (or some thread that interrupts it) uses the Pause command/menu-item because // those aren't designed to deal with g->IsPaused being out-of-sync with g_nPausedThreads. // However, if --g_nPausedThreads reduces g_nPausedThreads to 0, timers would allowed to // run during the callback. But that seems like the lesser evil, especially given that // this whole situation is very rare, and the documentation advises against doing it. } //else the current thread wasn't paused, which is usually the case. // TRAY ICON: g_script.UpdateTrayIcon() is not called because it's already in the right state // except when pause_after_execute==true, in which case it seems best not to change the icon // because it's likely to hurt any callback that's performance-sensitive. } g_script.mLastPeekTime = GetTickCount(); // Somewhat debatable, but might help minimize interruptions when the callback is called via message (e.g. subclassing a control; overriding a WindowProc). __int64 number_to_return; FuncResult result_token; ExprTokenType *param, one_param; int param_count; if (cb.flags & CBF_PASS_PARAMS_POINTER) { param_count = 1; param = &one_param; one_param.SetValue((UINT_PTR)params); } else { param_count = cb.actual_param_count; param = (ExprTokenType *)_alloca(param_count * sizeof(ExprTokenType)); for (int i = 0; i < param_count; ++i) param[i].SetValue((UINT_PTR)params[i]); } CallMethod(cb.func, cb.func, nullptr, param, param_count, &number_to_return); // CallMethod()'s own return value is ignored because it wouldn't affect the handling below. if (cb.flags & CBF_CREATE_NEW_THREAD) { DEBUGGER_STACK_POP() ResumeUnderlyingThread(); } else { if (g == g_array && !g_script.mAutoExecSectionIsRunning) // If the function just called used thread #0 and the AutoExec section isn't running, that means // the AutoExec section definitely didn't launch or control the callback (even if it is running, // it's not 100% certain it launched the callback). This can happen when a fast-mode callback has // been invoked via message, though the documentation advises against the fast mode when there is // no script thread controlling the callback. global_maximize_interruptibility(*g); // In case the script function called above used commands like Critical or "Thread Interrupt", ensure the idle thread is interruptible. This avoids having to treat the idle thread as special in other places. //else never alter the interruptibility of AutoExec while it's running because it has its own method to do that. if (pause_after_execute) // See comments where it's defined. { g->IsPaused = true; ++g_nPausedThreads; } } return (INT_PTR)number_to_return; } bif_impl FResult CallbackCreate(IObject *func, optl<StrArg> aOptions, optl<int> aParamCount, UINT_PTR &aRetVal) // Returns: Address of callback procedure. // Parameters: // 1: Name of the function to be called when the callback routine is executed. // 2: Options. // 3: Number of parameters of callback. // // Author: Original x86 RegisterCallback() was created by Jonathan Rennison (JGR). // x64 support by fincs. Various changes by Lexikos. { auto options = aOptions.value_or_empty(); bool pass_params_pointer = _tcschr(options, '&'); // Callback wants the address of the parameter list instead of their values. #ifdef WIN32_PLATFORM bool use_cdecl = StrChrAny(options, _T("Cc")); // Recognize "C" as the "CDecl" option. bool require_param_count = !use_cdecl; // Param count must be specified for x86 stdcall. #else bool require_param_count = false; #endif bool params_specified = aParamCount.has_value(); if (pass_params_pointer && require_param_count && !params_specified) return FR_E_ARG(2); int actual_param_count = aParamCount.value_or(0); ResultToken result_token; // Just used for .result. auto fr = ValidateFunctor(func , pass_params_pointer ? 1 : actual_param_count // Count of script parameters being passed. // Use MinParams as actual_param_count if unspecified and no & option. , params_specified || pass_params_pointer ? nullptr : &actual_param_count); if (fr != OK) return fr; #ifdef WIN32_PLATFORM if (!use_cdecl && actual_param_count > 31) // The ASM instruction currently used limits parameters to 31 (which should be plenty for any realistic use). { func->Release(); return FR_E_ARG(2); } #endif // GlobalAlloc() and dynamically-built code is the means by which a script can have an unlimited number of // distinct callbacks. On Win32, GlobalAlloc is the same function as LocalAlloc: they both point to // RtlAllocateHeap on the process heap. For large chunks of code you would reserve a 64K section with // VirtualAlloc and fill that, but for the 32 bytes we use here that would be overkill; GlobalAlloc is // much more efficient. MSDN says about GlobalAlloc: "All memory is created with execute access; no // special function is required to execute dynamically generated code. Memory allocated with this function // is guaranteed to be aligned on an 8-byte boundary." // ABOVE IS OBSOLETE/INACCURATE: Systems with DEP enabled (and some without) require a VirtualProtect call // to allow the callback to execute. MSDN currently says only this about the topic in the documentation // for GlobalAlloc: "To execute dynamically generated code, use the VirtualAlloc function to allocate // memory and the VirtualProtect function to grant PAGE_EXECUTE access." RCCallbackFunc *callbackfunc=(RCCallbackFunc*) GlobalAlloc(GMEM_FIXED,sizeof(RCCallbackFunc)); //allocate structure off process heap, automatically RWE and fixed. if (!callbackfunc) return FR_E_OUTOFMEM; RCCallbackFunc &cb = *callbackfunc; // For convenience and possible code-size reduction. #ifdef WIN32_PLATFORM cb.data1=0xE8; // call +0 -- E8 00 00 00 00 ;get eip, stays on stack as parameter 2 for C function (char *address). cb.data2=0x24448D00; // lea eax, [esp+8] -- 8D 44 24 08 ;eax points to params cb.data3=0x15FF5008; // push eax -- 50 ;eax pushed on stack as parameter 1 for C stub (UINT *params) // call [xxxx] (in the lines below) -- FF 15 xx xx xx xx ;call C stub __stdcall, so stack cleaned up for us. // Comments about the static variable below: The reason for using the address of a pointer to a function, // is that the address is passed as a fixed address, whereas a direct call is passed as a 32-bit offset // relative to the beginning of the next instruction, which is more fiddly than it's worth to calculate // for dynamic code, as a relative call is designed to allow position independent calls to within the // same memory block without requiring dynamic fixups, or other such inconveniences. In essence: // call xxx ; is relative // call [ptr_xxx] ; is position independent // Typically the latter is used when calling imported functions, etc., as only the pointers (import table), // need to be adjusted, not the calls themselves... static UINT_PTR (CALLBACK *funcaddrptr)(UINT_PTR*, char*) = RegisterCallbackCStub; // Use fixed absolute address of pointer to function, instead of varying relative offset to function. cb.callfuncptr = &funcaddrptr; // xxxx: Address of C stub. cb.data4=0xC48359 // pop ecx -- 59 ;return address... add esp, xx -- 83 C4 xx ;stack correct (add argument to add esp, nn for stack correction). + (use_cdecl ? 0 : actual_param_count<<26); cb.data5=0xE1FF; // jmp ecx -- FF E1 ;return #endif #ifdef _WIN64 /* Adapted from http://www.dyncall.org/ lea rax, (rip) # copy RIP (=p?) to RAX and use address in jmp [rax+16] # 'entry' (stored at RIP+16) for jump nop nop nop */ cb.data1 = 0xfffffffff9058d48ULL; cb.data2 = 0x9090900000000325ULL; cb.stub = RegisterCallbackAsmStub; cb.callfuncptr = RegisterCallbackCStub; #endif func->AddRef(); cb.func = func; cb.actual_param_count = actual_param_count; cb.flags = 0; if (!StrChrAny(options, _T("Ff"))) // Recognize "F" as the "fast" mode that avoids creating a new thread. cb.flags |= CBF_CREATE_NEW_THREAD; if (pass_params_pointer) cb.flags |= CBF_PASS_PARAMS_POINTER; // If DEP is enabled (and sometimes when DEP is apparently "disabled"), we must change the // protection of the page of memory in which the callback resides to allow it to execute: DWORD dwOldProtect; VirtualProtect(callbackfunc, sizeof(RCCallbackFunc), PAGE_EXECUTE_READWRITE, &dwOldProtect); aRetVal = (UINT_PTR)callbackfunc; // Yield the callable address as the result. return OK; } bif_impl FResult CallbackFree(UINT_PTR aCallback) { if (aCallback < 65536) // Basic sanity check to catch incoming raw addresses that are zero or blank. On Win32, the first 64KB of address space is always invalid. return FR_E_ARG(0); RCCallbackFunc *callbackfunc = (RCCallbackFunc *)aCallback; callbackfunc->func->Release(); callbackfunc->func = NULL; // To help detect bugs. GlobalFree(callbackfunc); return OK; } #endif
14,156
C++
.cpp
258
52.523256
249
0.756135
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,105
win.cpp
AutoHotkey_AutoHotkey/source/lib/win.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "window.h" #include "application.h" #include "script_func_impl.h" #include "abi.h" static FResult WinAct(WINTITLE_PARAMETERS_DECL, BuiltInFunctionID action, optl<double> aWaitTime = nullptr) { TCHAR title_buf[MAX_NUMBER_SIZE]; auto aTitle = aWinTitle ? TokenToString(*aWinTitle, title_buf) : _T(""); auto aText = aWinText.value_or_empty(); // Set initial guess for is_ahk_group (further refined later). For ahk_group, WinText, // ExcludeTitle, and ExcludeText must be blank so that they are reserved for future use // (i.e. they're currently not supported since the group's own criteria take precedence): bool is_ahk_group = !_tcsnicmp(aTitle, _T("ahk_group"), 9) && !*aText && aExcludeTitle.is_blank_or_omitted() && aExcludeText.is_blank_or_omitted(); // The following is not quite accurate since is_ahk_group is only a guess at this stage, but // given the extreme rarity of the guess being wrong, this shortcut seems justified to reduce // the code size/complexity. A wait_time of zero seems best for group closing because it's // currently implemented to do the wait after every window in the group. In addition, // this makes "WinClose ahk_group GroupName" behave identically to "GroupClose GroupName", // which seems best, for consistency: int wait_time = is_ahk_group ? 0 : DEFAULT_WINCLOSE_WAIT; if (aWaitTime.has_value()) // Implies (action == FID_WinClose || action == FID_WinKill) wait_time = (int)(1000 * aWaitTime.value()); if (is_ahk_group) if (WinGroup *group = g_script.FindGroup(omit_leading_whitespace(aTitle + 9))) { group->ActUponAll(action, wait_time); // It will do DoWinDelay if appropriate. return OK; } // Since above didn't return, either the group doesn't exist or it's paired with other // criteria, such as "ahk_group G ahk_class C", so do the normal single-window behavior. HWND target_window = NULL; if (aWinTitle) { bool hwnd_specified; auto fr = DetermineTargetHwnd(target_window, hwnd_specified, *aWinTitle); if (fr != OK) return fr; if (hwnd_specified && !target_window) // Specified a HWND of 0, or IsWindow() returned false. return FError(ERR_NO_WINDOW, nullptr, ErrorPrototype::Target); } if (action == FID_WinClose || action == FID_WinKill) { if (target_window) { WinClose(target_window, wait_time, action == FID_WinKill); DoWinDelay; return OK; } if (!WinClose(*g, aTitle, aText, wait_time, aExcludeTitle.value_or_empty(), aExcludeText.value_or_empty(), action == FID_WinKill)) // Currently WinClose returns NULL only for this case; it doesn't confirm the window closed. return FError(ERR_NO_WINDOW, nullptr, ErrorPrototype::Target); DoWinDelay; return OK; } if (!target_window) { // By design, the WinShow command must always unhide a hidden window, even if the user has // specified that hidden windows should not be detected. So set this now so that // DetermineTargetWindow() will make its calls in the right mode: bool need_restore = (action == FID_WinShow && !g->DetectHiddenWindows); if (need_restore) g->DetectHiddenWindows = true; target_window = Line::DetermineTargetWindow(aTitle, aText, aExcludeTitle.value_or_empty(), aExcludeText.value_or_empty()); if (need_restore) g->DetectHiddenWindows = false; if (!target_window) return FError(ERR_NO_WINDOW, nullptr, ErrorPrototype::Target); } // WinGroup's EnumParentActUponAll() is quite similar to the following, so the two should be // maintained together. int nCmdShow = SW_NONE; // Set default. switch (action) { // SW_FORCEMINIMIZE: supported only in Windows 2000/XP and beyond: "Minimizes a window, // even if the thread that owns the window is hung. This flag should only be used when // minimizing windows from a different thread." // My: It seems best to use SW_FORCEMINIMIZE on OS's that support it because I have // observed ShowWindow() to hang (thus locking up our app's main thread) if the target // window is hung. // UPDATE: For now, not using "force" every time because it has undesirable side-effects such // as the window not being restored to its maximized state after it was minimized // this way. case FID_WinMinimize: if (IsWindowHung(target_window)) { nCmdShow = SW_FORCEMINIMIZE; // SW_MINIMIZE can lock up our thread on WinXP, which is why we revert to SW_FORCEMINIMIZE above. // Older/obsolete comment for background: don't attempt to minimize hung windows because that // might hang our thread because the call to ShowWindow() would never return. } else nCmdShow = SW_MINIMIZE; break; case FID_WinMaximize: if (!IsWindowHung(target_window)) nCmdShow = SW_MAXIMIZE; break; case FID_WinRestore: if (!IsWindowHung(target_window)) nCmdShow = SW_RESTORE; break; // Seems safe to assume it's not hung in these cases, since I'm inclined to believe // (untested) that hiding and showing a hung window won't lock up our thread, and // there's a chance they may be effective even against hung windows, unlike the // others above (except ACT_WINMINIMIZE, which has a special FORCE method): case FID_WinHide: nCmdShow = SW_HIDE; break; case FID_WinShow: nCmdShow = SW_SHOW; break; } // UPDATE: Trying ShowWindowAsync() // now, which should avoid the problems with hanging. UPDATE #2: Went back to // not using Async() because sometimes the script lines that come after the one // that is doing this action here rely on this action having been completed // (e.g. a window being maximized prior to clicking somewhere inside it). if (nCmdShow != SW_NONE) { // I'm not certain that SW_FORCEMINIMIZE works with ShowWindowAsync(), but // it probably does since there's absolutely no mention to the contrary // anywhere on MS's site or on the web. But clearly, if it does work, it // does so only because Async() doesn't really post the message to the thread's // queue, instead opting for more aggressive measures. Thus, it seems best // to do it this way to have maximum confidence in it: //if (nCmdShow == SW_FORCEMINIMIZE) // Safer not to use ShowWindowAsync() in this case. ShowWindow(target_window, nCmdShow); //else // ShowWindowAsync(target_window, nCmdShow); DoWinDelay; } return OK; } bif_impl FResult WinClose(ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<double> aWaitTime, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText) { return WinAct(WINTITLE_PARAMETERS, FID_WinClose, aWaitTime); } bif_impl FResult WinKill(ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<double> aWaitTime, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText) { return WinAct(WINTITLE_PARAMETERS, FID_WinKill, aWaitTime); } bif_impl FResult WinShow(WINTITLE_PARAMETERS_DECL) { return WinAct(WINTITLE_PARAMETERS, FID_WinShow); } bif_impl FResult WinHide(WINTITLE_PARAMETERS_DECL) { return WinAct(WINTITLE_PARAMETERS, FID_WinHide); } bif_impl FResult WinMaximize(WINTITLE_PARAMETERS_DECL) { return WinAct(WINTITLE_PARAMETERS, FID_WinMaximize); } bif_impl FResult WinMinimize(WINTITLE_PARAMETERS_DECL) { return WinAct(WINTITLE_PARAMETERS, FID_WinMinimize); } bif_impl FResult WinRestore(WINTITLE_PARAMETERS_DECL) { return WinAct(WINTITLE_PARAMETERS, FID_WinRestore); } static FResult WinActivate(WINTITLE_PARAMETERS_DECL, bool aBottom) { HWND target_window; auto fr = DetermineTargetWindow(target_window, aWinTitle, aWinText.value_or_null(), aExcludeTitle.value_or_null(), aExcludeText.value_or_null() , aBottom); // The last parameter determines whether the first or last match is used. if (fr != OK) return fr; SetForegroundWindowEx(target_window); // It seems best to do these sleeps here rather than in the windowing // functions themselves because that way, the program can use the // windowing functions without being subject to the script's delay // setting (i.e. there are probably cases when we don't need to wait, // such as bringing a message box to the foreground, since no other // actions will be dependent on it actually having happened): DoWinDelay; return OK; } bif_impl FResult WinActivate(WINTITLE_PARAMETERS_DECL) { return WinActivate(WINTITLE_PARAMETERS, false); } bif_impl FResult WinActivateBottom(WINTITLE_PARAMETERS_DECL) { return WinActivate(WINTITLE_PARAMETERS, true); } bif_impl FResult GroupAdd(StrArg aGroup, optl<StrArg> aTitle, optl<StrArg> aText, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText) { auto group = g_script.FindGroup(aGroup, true); if (!group) return FR_FAIL; // It already displayed the error for us. return group->AddWindow(aTitle.value_or_null(), aText.value_or_null(), aExcludeTitle.value_or_null(), aExcludeText.value_or_null()) ? OK : FR_FAIL; } bif_impl FResult GroupActivate(StrArg aGroup, optl<StrArg> aMode, UINT &aRetVal) { WinGroup *group; if ( !(group = g_script.FindGroup(aGroup, true)) ) // Last parameter -> create-if-not-found. return FR_FAIL; // It already displayed the error for us. TCHAR mode = 0; if (aMode.has_nonempty_value()) { mode = *aMode.value(); if (mode == 'r') mode = 'R'; if (mode != 'R' || aMode.value()[1]) return FR_E_ARG(1); } aRetVal = (UINT)(UINT_PTR)group->Activate(mode == 'R'); return OK; } bif_impl FResult GroupDeactivate(StrArg aGroup, optl<StrArg> aMode) { auto group = g_script.FindGroup(aGroup); if (!group) return FR_E_ARG(0); TCHAR mode = 0; if (aMode.has_nonempty_value()) { mode = *aMode.value(); if (mode == 'r') mode = 'R'; if (mode != 'R' || aMode.value()[1]) return FR_E_ARG(1); } group->Deactivate(mode == 'R'); return OK; } bif_impl FResult GroupClose(StrArg aGroup, optl<StrArg> aMode) { auto group = g_script.FindGroup(aGroup); if (!group) return FR_E_ARG(0); TCHAR mode = 0; if (aMode.has_nonempty_value()) { mode = ctoupper(*aMode.value()); if ((mode != 'R' && mode != 'A') || aMode.value()[1]) return FR_E_ARG(1); } if (mode == 'A') group->ActUponAll(FID_WinClose, 0); else group->CloseAndGoToNext(mode == 'R'); return OK; } bif_impl FResult WinMove(optl<int> aX, optl<int> aY, optl<int> aWidth, optl<int> aHeight, WINTITLE_PARAMETERS_DECL) { HWND target_window; DETERMINE_TARGET_WINDOW; RECT rect; if (!GetWindowRect(target_window, &rect) || !MoveWindow(target_window , aX.value_or(rect.left) // X-position , aY.value_or(rect.top) // Y-position , aWidth.value_or(rect.right - rect.left) , aHeight.value_or(rect.bottom - rect.top) , TRUE)) // Do repaint. return FR_E_WIN32; DoWinDelay; return OK; } static FResult ControlSend(StrArg aKeys, CONTROL_PARAMETERS_DECL_OPT, SendRawModes aMode) { DETERMINE_TARGET_CONTROL2; SendKeys(aKeys, aMode, SM_EVENT, control_window); // But don't do WinDelay because KeyDelay should have been in effect for the above. return OK; } bif_impl FResult ControlSend(StrArg aKeys, CONTROL_PARAMETERS_DECL_OPT) { return ControlSend(aKeys, CONTROL_PARAMETERS, SCM_NOT_RAW); } bif_impl FResult ControlSendText(StrArg aKeys, CONTROL_PARAMETERS_DECL_OPT) { return ControlSend(aKeys, CONTROL_PARAMETERS, SCM_RAW_TEXT); } bif_impl FResult ControlClick(ExprTokenType *aControlSpec, ExprTokenType *aWinTitle, optl<StrArg> aWinText , optl<StrArg> aWhichButton, optl<int> aClickCount, optl<StrArg> aOptions, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText) { int aVK = Line::ConvertMouseButton(aWhichButton.value_or_null()); if (!aVK) return FR_E_ARG(3); int click_count = aClickCount.value_or(1); // Set the defaults that will be in effect unless overridden by options: KeyEventTypes event_type = KEYDOWNANDUP; bool position_mode = false; bool do_activate = true; // These default coords can be overridden either by aOptions or aControl's X/Y mode: POINT click = {COORD_UNSPECIFIED, COORD_UNSPECIFIED}; for (auto cp = aOptions.value_or_empty(); *cp; ++cp) { switch(ctoupper(*cp)) { case 'D': event_type = KEYDOWN; break; case 'U': event_type = KEYUP; break; case 'N': // v1.0.45: // It was reported (and confirmed through testing) that this new NA mode (which avoids // AttachThreadInput() and SetActiveWindow()) improves the reliability of ControlClick when // the user is moving the mouse fairly quickly at the time the command tries to click a button. // In addition, the new mode avoids activating the window, which tends to happen otherwise. // HOWEVER, the new mode seems no more reliable than the old mode when the target window is // the active window. In addition, there may be side-effects of the new mode (I caught it // causing Notepad's Save-As dialog to hang once, during the display of its "Overwrite?" dialog). // ALSO, SetControlDelay -1 seems to fix the unreliability issue as well (independently of NA), // though it might not work with some types of windows/controls (thus, for backward // compatibility, ControlClick still obeys SetControlDelay). if (ctoupper(cp[1]) == 'A') { cp += 1; // Add 1 vs. 2 to skip over the rest of the letters in this option word. do_activate = false; } break; case 'P': if (!_tcsnicmp(cp, _T("Pos"), 3)) { cp += 2; // Add 2 vs. 3 to skip over the rest of the letters in this option word. position_mode = true; } break; // For the below: // Use atoi() vs. ATOI() to avoid interpreting something like 0x01D as hex // when in fact the D was meant to be an option letter: case 'X': click.x = _ttoi(cp + 1); // Will be overridden later below if it turns out that position_mode is in effect. break; case 'Y': click.y = _ttoi(cp + 1); // Will be overridden later below if it turns out that position_mode is in effect. break; } } HWND target_window, control_window; if (position_mode) { // Determine target window only. Control will be found by position below. auto fr = DetermineTargetWindow(target_window, WINTITLE_PARAMETERS); if (fr != OK) return fr; control_window = NULL; } else { // Determine target window and control. auto fr = DetermineTargetControl(control_window, target_window, CONTROL_PARAMETERS, false); if (fr != OK) return fr; } ASSERT(target_window != NULL); // It's debatable, but might be best for flexibility (and backward compatibility) to allow target_window to itself // be a control (at least for the position_mode handler below). For example, the script may have called SetParent // to make a top-level window the child of some other window, in which case this policy allows it to be seen like // a non-child. TCHAR control_buf[MAX_NUMBER_SIZE]; LPCTSTR aControl = nullptr; if (!control_window && aControlSpec) // Even if position_mode is false, the below is still attempted, as documented. { // New section for v1.0.24. But only after the above fails to find a control do we consider // whether aControl contains X and Y coordinates. That way, if a control class happens to be // named something like "X1 Y1", it will still be found by giving precedence to class names. point_and_hwnd_type pah = {0}; pah.ignore_disabled_controls = true; // v1.1.20: Ignore disabled controls. // Parse the X an Y coordinates in a strict way to reduce ambiguity with control names and also // to keep the code simple. auto cp = aControl = omit_leading_whitespace(TokenToString(*aControlSpec, control_buf)); if (ctoupper(*cp) != 'X') goto control_error; ++cp; if (!*cp) goto control_error; pah.pt.x = ATOI(cp); if ( !(cp = StrChrAny(cp, _T(" \t"))) ) // Find next space or tab (there must be one for it to be considered valid). goto control_error; cp = omit_leading_whitespace(cp + 1); if (!*cp || _totupper(*cp) != 'Y') goto control_error; ++cp; if (!*cp) goto control_error; pah.pt.y = ATOI(cp); // The passed-in coordinates are always relative to target_window's client area because offering // an option for absolute/screen coordinates doesn't seem useful. ClientToScreen(target_window, &pah.pt); // Convert to screen coordinates. EnumChildWindows(target_window, EnumChildFindPoint, (LPARAM)&pah); // Find topmost control containing point. // If no control is at this point, try posting the mouse event message(s) directly to the // parent window to increase the flexibility of this feature: control_window = pah.hwnd_found ? pah.hwnd_found : target_window; // Convert click's target coordinates to be relative to the client area of the control or // parent window because that is the format required by messages such as WM_LBUTTONDOWN // used later below: click = pah.pt; ScreenToClient(control_window, &click); } // This is done this late because it seems better to throw an exception whenever the // target window or control isn't found, or any other error condition occurs above: if (click_count < 1) { if (click_count < 0) return FR_E_ARG(4); // Allow this to simply "do nothing", because it increases flexibility // in the case where the number of clicks is a dereferenced script variable // that may sometimes (by intent) resolve to zero or negative: return OK; } RECT rect; if (click.x == COORD_UNSPECIFIED || click.y == COORD_UNSPECIFIED) { // The following idea is from AutoIt3. It states: "Get the dimensions of the control so we can click // the centre of it" (maybe safer and more natural than 0,0). // My: In addition, this is probably better for some large controls (e.g. SysListView32) because // clicking at 0,0 might activate a part of the control that is not even visible: if (!GetWindowRect(control_window, &rect)) return FR_E_WIN32; if (click.x == COORD_UNSPECIFIED) click.x = (rect.right - rect.left) / 2; if (click.y == COORD_UNSPECIFIED) click.y = (rect.bottom - rect.top) / 2; } UINT msg_down, msg_up; WPARAM wparam, wparam_up = 0; bool vk_is_wheel = aVK == VK_WHEEL_UP || aVK == VK_WHEEL_DOWN; bool vk_is_hwheel = aVK == VK_WHEEL_LEFT || aVK == VK_WHEEL_RIGHT; // v1.0.48: Lexikos: Support horizontal scrolling in Windows Vista and later. if (vk_is_wheel) { ClientToScreen(control_window, &click); // Wheel messages use screen coordinates. wparam = MAKEWPARAM(0, click_count * ((aVK == VK_WHEEL_UP) ? WHEEL_DELTA : -WHEEL_DELTA)); msg_down = WM_MOUSEWHEEL; // Make the event more accurate by having the state of the keys reflected in the event. // The logical state (not physical state) of the modifier keys is used so that something // like this is supported: // Send, {ShiftDown} // MouseClick, WheelUp // Send, {ShiftUp} // In addition, if the mouse hook is installed, use its logical mouse button state so that // something like this is supported: // MouseClick, left, , , , , D ; Hold down the left mouse button // MouseClick, WheelUp // MouseClick, left, , , , , U ; Release the left mouse button. // UPDATE: Since the other ControlClick types (such as leftclick) do not reflect these // modifiers -- and we want to keep it that way, at least by default, for compatibility // reasons -- it seems best for consistency not to do them for WheelUp/Down either. // A script option can be added in the future to obey the state of the modifiers: //mod_type mod = GetModifierState(); //if (mod & MOD_SHIFT) // wparam |= MK_SHIFT; //if (mod & MOD_CONTROL) // wparam |= MK_CONTROL; //if (g_MouseHook) // wparam |= g_mouse_buttons_logical; } else if (vk_is_hwheel) // Lexikos: Support horizontal scrolling in Windows Vista and later. { wparam = MAKEWPARAM(0, click_count * ((aVK == VK_WHEEL_LEFT) ? -WHEEL_DELTA : WHEEL_DELTA)); msg_down = WM_MOUSEHWHEEL; } else { switch (aVK) { case VK_LBUTTON: msg_down = WM_LBUTTONDOWN; msg_up = WM_LBUTTONUP; wparam = MK_LBUTTON; break; case VK_RBUTTON: msg_down = WM_RBUTTONDOWN; msg_up = WM_RBUTTONUP; wparam = MK_RBUTTON; break; case VK_MBUTTON: msg_down = WM_MBUTTONDOWN; msg_up = WM_MBUTTONUP; wparam = MK_MBUTTON; break; case VK_XBUTTON1: msg_down = WM_XBUTTONDOWN; msg_up = WM_XBUTTONUP; wparam_up = XBUTTON1<<16; wparam = MK_XBUTTON1|wparam_up; break; case VK_XBUTTON2: msg_down = WM_XBUTTONDOWN; msg_up = WM_XBUTTONUP; wparam_up = XBUTTON2<<16; wparam = MK_XBUTTON2|wparam_up; break; default: // Just do nothing since this should realistically never happen. ASSERT(!"aVK value not handled"); } } LPARAM lparam = MAKELPARAM(click.x, click.y); // SetActiveWindow() requires ATTACH_THREAD_INPUT to succeed. Even though the MSDN docs state // that SetActiveWindow() has no effect unless the parent window is foreground, Jon insists // that SetActiveWindow() resolved some problems for some users. In any case, it seems best // to do this in case the window really is foreground, in which case MSDN indicates that // it will help for certain types of dialogs. ATTACH_THREAD_INPUT_AND_SETACTIVEWINDOW_IF_DO_ACTIVATE // It's kept with a similar macro for maintainability. // v1.0.44.13: Notes for the above: Unlike some other Control commands, GetNonChildParent() is not // called here when target_window==control_window. This is because the script may have called // SetParent to make target_window the child of some other window, in which case target_window // should still be used above (unclear). Perhaps more importantly, it's allowed for control_window // to be the same as target_window, at least in position_mode, whose docs state, "If there is no // control, the target window itself will be sent the event (which might have no effect depending // on the nature of the window)." In other words, it seems too complicated and rare to add explicit // handling for "ahk_id %ControlHWND%" (though the below rules should work). // The line "ControlClick,, ahk_id %HWND%" can have multiple meanings depending on the nature of HWND: // 1) If HWND is a top-level window, its topmost child will be clicked. // 2) If HWND is a top-level window that has become a child of another window via SetParent: same. // 3) If HWND is a control, its topmost child will be clicked (or itself if it has no children). // For example, the following works (as documented in the first parameter): // ControlGet, HWND, HWND,, OK, A ; Get the HWND of the OK button. // ControlClick,, ahk_id %HWND% FResult result = OK; if (vk_is_wheel || vk_is_hwheel) // v1.0.48: Lexikos: Support horizontal scrolling in Windows Vista and later. { if (!PostMessage(control_window, msg_down, wparam, lparam)) result = FR_E_WIN32; else DoControlDelay; } else { for (int i = 0; i < click_count; ++i) { if (event_type != KEYUP) // It's either down-only or up-and-down so always to the down-event. { if (!PostMessage(control_window, msg_down, wparam, lparam)) { result = FR_E_WIN32; break; } // Seems best to do this one too, which is what AutoIt3 does also. User can always reduce // ControlDelay to 0 or -1. Update: Jon says this delay might be causing it to fail in // some cases. Upon reflection, it seems best not to do this anyway because PostMessage() // should queue up the message for the app correctly even if it's busy. Update: But I // think the timestamp is available on every posted message, so if some apps check for // inhumanly fast clicks (to weed out transients with partial clicks of the mouse, or // to detect artificial input), the click might not work. So it might be better after // all to do the delay until it's proven to be problematic (Jon implies that he has // no proof yet). IF THIS IS EVER DISABLED, be sure to do the ControlDelay anyway // if event_type == KEYDOWN: DoControlDelay; } if (event_type != KEYDOWN) // It's either up-only or up-and-down so always to the up-event. { if (!PostMessage(control_window, msg_up, wparam_up, lparam)) { result = FR_E_WIN32; break; } DoControlDelay; } } } DETACH_THREAD_INPUT // Also takes into account do_activate, indirectly. return result; control_error: return FError(ERR_NO_CONTROL, aControl, ErrorPrototype::Target); } static FResult ControlShow(CONTROL_PARAMETERS_DECL, int aShow) { DETERMINE_TARGET_CONTROL2; ShowWindow(control_window, aShow); DoControlDelay; return OK; } bif_impl FResult ControlShow(CONTROL_PARAMETERS_DECL) { return ControlShow(CONTROL_PARAMETERS, SW_SHOWNOACTIVATE); } bif_impl FResult ControlHide(CONTROL_PARAMETERS_DECL) { return ControlShow(CONTROL_PARAMETERS, SW_HIDE); } bif_impl FResult ControlGetVisible(CONTROL_PARAMETERS_DECL, BOOL &aRetVal) { DETERMINE_TARGET_CONTROL2; aRetVal = IsWindowVisible(control_window); return OK; } bif_impl FResult ControlMove(optl<int> aX, optl<int> aY, optl<int> aWidth, optl<int> aHeight, CONTROL_PARAMETERS_DECL) { DETERMINE_TARGET_CONTROL2; // The following macro is used to keep ControlMove and ControlGetPos in sync: #define CONTROL_COORD_PARENT(target, control) \ (target == control ? GetNonChildParent(target) : target) // Determine which window the supplied coordinates are relative to: HWND coord_parent = CONTROL_COORD_PARENT(target_window, control_window); // Determine the controls current coordinates relative to coord_parent in case one // or more parameters were omitted. RECT control_rect; if (!GetWindowRect(control_window, &control_rect)) return FR_E_WIN32; // For simplicity, failure isn't checked for the below since a return value of 0 can // indicate that the coord_parent is at 0,0 (i.e. the translation made no change). MapWindowPoints(NULL, coord_parent, (LPPOINT)&control_rect, 2); POINT point { aX.value_or(control_rect.left), aY.value_or(control_rect.top) }; // MoveWindow accepts coordinates relative to the control's immediate parent, which might // be different to coord_parent since controls can themselves have child controls. So if // necessary, map the caller-supplied coordinates to the control's immediate parent: HWND immediate_parent = GetParent(control_window); if (immediate_parent != coord_parent) MapWindowPoints(coord_parent, immediate_parent, &point, 1); MoveWindow(control_window , point.x , point.y , aWidth.value_or(control_rect.right - control_rect.left) , aHeight.value_or(control_rect.bottom - control_rect.top) , TRUE); // Do repaint. DoControlDelay return OK; } bif_impl FResult ControlGetPos(int *aX, int *aY, int *aWidth, int *aHeight, CONTROL_PARAMETERS_DECL) { DETERMINE_TARGET_CONTROL2; // Determine which window the returned coordinates should be relative to: HWND coord_parent = CONTROL_COORD_PARENT(target_window, control_window); RECT child_rect; // Realistically never fails since DetermineTargetWindow() and ControlExist() should always yield // valid window handles: GetWindowRect(control_window, &child_rect); // Map the screen coordinates returned by GetWindowRect to the client area of coord_parent. MapWindowPoints(NULL, coord_parent, (LPPOINT)&child_rect, 2); if (aX) *aX = child_rect.left; if (aY) *aY = child_rect.top; if (aWidth) *aWidth = child_rect.right - child_rect.left; if (aHeight) *aHeight = child_rect.bottom - child_rect.top; return OK; } bif_impl FResult ControlGetFocus(WINTITLE_PARAMETERS_DECL, UINT &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; GUITHREADINFO guithreadInfo; guithreadInfo.cbSize = sizeof(GUITHREADINFO); if (!GetGUIThreadInfo(GetWindowThreadProcessId(target_window, NULL), &guithreadInfo)) { // Failure is most likely because the target thread has no input queue; i.e. target_window // is a console window and the process which owns it has no input queue. Controls cannot // exist without an input queue, so a return value of 0 is appropriate in that case. // A value of 0 is already ambiguous (window is not focused, or window itself is focused), // and is most likely preferable to a thrown exception, so returning 0 in the unlikely event // of some other failure seems acceptable. There might be a possibility of a race condition // between determining target_window and the window being destroyed, but checking for that // doesn't seem useful since the window could be destroyed or deactivated after we return. aRetVal = 0; return OK; } // Use IsChild() to ensure the focused control actually belongs to this window. // Otherwise, a HWND will be returned if any window in the same thread has focus, // including the target window itself (typically when it has no controls). if (!IsChild(target_window, guithreadInfo.hwndFocus)) aRetVal = 0; // As documented, if "none of the target window's controls has focus, the return value is 0". else aRetVal = (UINT)(size_t)guithreadInfo.hwndFocus; return OK; } bif_impl FResult ControlGetClassNN(CONTROL_PARAMETERS_DECL, StrRet &aRetVal) { DETERMINE_TARGET_CONTROL2; if (target_window == control_window) target_window = GetNonChildParent(control_window); TCHAR class_nn[WINDOW_CLASS_NN_SIZE]; auto fr = ControlGetClassNN(target_window, control_window, class_nn, _countof(class_nn)); return fr != OK ? fr : aRetVal.Copy(class_nn) ? OK : FR_E_OUTOFMEM; } // Retrieves the ClassNN of a control. // aBuf is ideally sized by WINDOW_CLASS_NN_SIZE to avoid any possibility of // the buffer being insufficient. Must be large enough to fit the class name // plus CONTROL_NN_SIZE. FResult ControlGetClassNN(HWND aWindow, HWND aControl, LPTSTR aBuf, int aBufSize) { ASSERT(aBufSize > CONTROL_NN_SIZE); class_and_hwnd_type cah; cah.hwnd = aControl; cah.class_name = aBuf; int length = GetClassName(cah.hwnd, aBuf, aBufSize - CONTROL_NN_SIZE); // Allow room for sequence number. if (!length) return FR_E_WIN32; cah.class_count = 0; // Init for the below. cah.is_found = false; // Same. EnumChildWindows(aWindow, EnumChildFindSeqNum, (LPARAM)&cah); if (!cah.is_found) return FR_E_FAILED; // Append the class sequence number onto the class name: sntprintf(aBuf + length, aBufSize - length, _T("%u"), cah.class_count); return OK; } BOOL CALLBACK EnumChildFindSeqNum(HWND aWnd, LPARAM lParam) { class_and_hwnd_type &cah = *(class_and_hwnd_type *)lParam; // For performance and convenience. TCHAR class_name[WINDOW_CLASS_SIZE]; if (!GetClassName(aWnd, class_name, _countof(class_name))) return TRUE; // Continue the enumeration. if (!_tcscmp(class_name, cah.class_name)) // Class names match. { ++cah.class_count; if (aWnd == cah.hwnd) // The caller-specified window has been found. { cah.is_found = true; return FALSE; } } return TRUE; // Continue enumeration until a match is found or there aren't any windows remaining. } bif_impl FResult ControlFocus(CONTROL_PARAMETERS_DECL) { DETERMINE_TARGET_CONTROL2; // Unlike many of the other Control commands, this one requires AttachThreadInput() // to have any realistic chance of success (though sometimes it may work by pure // chance even without it): ATTACH_THREAD_INPUT SetFocus(control_window); DoControlDelay; // Done unconditionally for simplicity, and in case SetFocus() had some effect despite indicating failure. // GetFocus() isn't called and failure to focus isn't treated as an error because // a successful change in focus doesn't guarantee that the focus will still be as // expected when the next line of code runs. // Very important to detach any threads whose inputs were attached above, // prior to returning, otherwise the next attempt to attach thread inputs // for these particular windows may result in a hung thread or other // undesirable effect: DETACH_THREAD_INPUT return OK; } bif_impl FResult ControlSetText(StrArg aNewText, CONTROL_PARAMETERS_DECL) { DETERMINE_TARGET_CONTROL2; // SendMessage must be used, not PostMessage(), at least for some (probably most) apps. // Also: No need to call IsWindowHung() because SendMessageTimeout() should return // immediately if the OS already "knows" the window is hung: DWORD_PTR result; SendMessageTimeout(control_window, WM_SETTEXT, (WPARAM)0, (LPARAM)aNewText , SMTO_ABORTIFHUNG, 5000, &result); DoControlDelay; return OK; } bif_impl FResult ControlGetText(CONTROL_PARAMETERS_DECL, StrRet &aRetVal) { DETERMINE_TARGET_CONTROL2; // Handle the output parameter. Note: Using GetWindowTextTimeout() vs. GetWindowText() // because it is able to get text from more types of controls (e.g. large edit controls): size_t estimated_length = GetWindowTextTimeout(control_window); // Allocate memory for the return value. LPTSTR buf = aRetVal.Alloc(estimated_length); if (!buf) return FR_E_OUTOFMEM; // Fetch the text directly into the buffer. Also set the length explicitly // in case actual size written was off from the estimated size (since // GetWindowTextLength() can return more space that will actually be required // in certain circumstances, see MS docs): auto actual_length = GetWindowTextTimeout(control_window, buf, estimated_length + 1); aRetVal.SetLength(actual_length); if (!actual_length) // There was no text to get or GetWindowTextTimeout() failed. *buf = '\0'; return OK; } static FResult WinSetEnabled(int aValue, CONTROL_PARAMETERS_DECL_OPT) { if (aValue < -1 || aValue > 1) return FR_E_ARG(0); DETERMINE_TARGET_CONTROL2; // If this is WinSetEnabled rather than ControlSetEnabled, control_window == target_window. if (aValue == -1) aValue = IsWindowEnabled(control_window) ? 0 : 1; EnableWindow(control_window, aValue); bool success = !IsWindowEnabled(control_window) == !aValue; if (aControlSpec) DoControlDelay; return success ? OK : FR_E_FAILED; } bif_impl FResult WinSetEnabled(int aValue, WINTITLE_PARAMETERS_DECL) { return WinSetEnabled(aValue, nullptr, WINTITLE_PARAMETERS); } bif_impl FResult WinGetEnabled(WINTITLE_PARAMETERS_DECL, BOOL &aRetVal) { // Merging this with ControlGetEnabled increased code size slightly. HWND target_window; DETERMINE_TARGET_WINDOW; aRetVal = IsWindowEnabled(target_window); return OK; } bif_impl FResult ControlSetEnabled(int aValue, CONTROL_PARAMETERS_DECL) { return WinSetEnabled(aValue, &CONTROL_PARAMETERS); } bif_impl FResult ControlGetEnabled(CONTROL_PARAMETERS_DECL, BOOL &aRetVal) { DETERMINE_TARGET_CONTROL2; aRetVal = IsWindowEnabled(control_window); return OK; } bif_impl FResult ListViewGetContent(optl<StrArg> aOpt, CONTROL_PARAMETERS_DECL, ResultToken &aResultToken) { DETERMINE_TARGET_CONTROL2; auto aHwnd = control_window; auto aOptions = aOpt.value_or_empty(); // GET ROW COUNT LRESULT row_count; if (!SendMessageTimeout(aHwnd, LVM_GETITEMCOUNT, 0, 0, SMTO_ABORTIFHUNG, 2000, (PDWORD_PTR)&row_count)) // Timed out or failed. return FR_E_WIN32; // GET COLUMN COUNT // Through testing, could probably get to a level of 90% certainty that a ListView for which // InsertColumn() was never called (or was called only once) might lack a header control if the LV is // created in List/Icon view-mode and/or with LVS_NOCOLUMNHEADER. The problem is that 90% doesn't // seem to be enough to justify elimination of the code for "undetermined column count" mode. If it // ever does become a certainty, the following could be changed: // 1) The extra code for "undetermined" mode rather than simply forcing col_count to be 1. // 2) Probably should be kept for compatibility: -1 being returned when undetermined "col count". // // The following approach might be the only simple yet reliable way to get the column count (sending // LVM_GETITEM until it returns false doesn't work because it apparently returns true even for // nonexistent subitems -- the same is reported to happen with LVM_GETCOLUMN and such, though I seem // to remember that LVM_SETCOLUMN fails on non-existent columns -- but calling that on a ListView // that isn't in Report view has been known to traumatize the control). // Fix for v1.0.37.01: It appears that the header doesn't always exist. For example, when an // Explorer window opens and is *initially* in icon or list mode vs. details/tiles mode, testing // shows that there is no header control. Testing also shows that there is exactly one column // in such cases but only for Explorer and other things that avoid creating the invisible columns. // For example, a script can create a ListView in Icon-mode and give it retrievable column data for // columns beyond the first. Thus, having the undetermined-col-count mode preserves flexibility // by allowing individual columns beyond the first to be retrieved. On a related note, testing shows // that attempts to explicitly retrieve columns (i.e. fields/subitems) other than the first in the // case of Explorer's Icon/List view modes behave the same as fetching the first column (i.e. Col3 // would retrieve the same text as specifying Col1 or not having the Col option at all). // Obsolete because not always true: Testing shows that a ListView always has a header control // (at least on XP), even if you can't see it (such as when the view is Icon/Tile or when -Hdr has // been specified in the options). HWND header_control; LRESULT col_count = -1; // Fix for v1.0.37.01: Use -1 to indicate "undetermined col count". if (SendMessageTimeout(aHwnd, LVM_GETHEADER, 0, 0, SMTO_ABORTIFHUNG, 2000, (PDWORD_PTR)&header_control) && header_control) // Relies on short-circuit boolean order. SendMessageTimeout(header_control, HDM_GETITEMCOUNT, 0, 0, SMTO_ABORTIFHUNG, 2000, (PDWORD_PTR)&col_count); // Return value is not checked because if it fails, col_count is left at its default of -1 set above. // In fact, if any of the above conditions made it impossible to determine col_count, col_count stays // at -1 to indicate "undetermined". // PARSE OPTIONS (a simple vs. strict method is used to reduce code size) bool get_count = tcscasestr(aOptions, _T("Count")); bool include_selected_only = tcscasestr(aOptions, _T("Selected")); // Explicit "ed" to reserve "Select" for possible future use. bool include_focused_only = tcscasestr(aOptions, _T("Focused")); // Same. LPTSTR col_option = tcscasestr(aOptions, _T("Col")); // Also used for mode "Count Col" int requested_col = col_option ? ATOI(col_option + 3) - 1 : -1; if (col_option && (get_count ? col_option[3] && !IS_SPACE_OR_TAB(col_option[3]) // "Col" has a suffix. : (requested_col < 0 || col_count > -1 && requested_col >= col_count))) // Specified column does not exist. return FR_E_ARG(0); // IF THE "COUNT" OPTION IS PRESENT, FULLY HANDLE THAT AND RETURN if (get_count) { int result; // Must be signed to support writing a col count of -1 to aOutputVar. DWORD_PTR msg_result; if (include_focused_only) // Listed first so that it takes precedence over include_selected_only. { if (!SendMessageTimeout(aHwnd, LVM_GETNEXTITEM, -1, LVNI_FOCUSED, SMTO_ABORTIFHUNG, 2000, &msg_result)) // Timed out or failed. return FR_E_WIN32; result = (int)msg_result + 1; // i.e. Set it to 0 if not found, or the 1-based row-number otherwise. } else if (include_selected_only) { if (!SendMessageTimeout(aHwnd, LVM_GETSELECTEDCOUNT, 0, 0, SMTO_ABORTIFHUNG, 2000, &msg_result)) // Timed out or failed. return FR_E_WIN32; result = (int)msg_result; } else if (col_option) // "Count Col" returns the number of columns. result = (int)col_count; else // Total row count. result = (int)row_count; aResultToken.SetValue(result); return OK; } // FINAL CHECKS if (row_count < 1 || !col_count) // But don't return when col_count == -1 (i.e. always make the attempt when col count is undetermined). return OK; // No text in the control, so indicate success. // Notes about the following struct definitions: The layout of LVITEM depends on // which platform THIS executable was compiled for, but we need it to match what // the TARGET process expects. If the target process is 32-bit and we are 64-bit // or vice versa, LVITEM can't be used. The following structs are copies of // LVITEM with UINT (32-bit) or UINT64 (64-bit) in place of the pointer fields. struct LVITEM32 { UINT mask; int iItem; int iSubItem; UINT state; UINT stateMask; UINT pszText; int cchTextMax; int iImage; UINT lParam; int iIndent; int iGroupId; UINT cColumns; UINT puColumns; UINT piColFmt; int iGroup; }; struct LVITEM64 { UINT mask; int iItem; int iSubItem; UINT state; UINT stateMask; UINT64 pszText; int cchTextMax; int iImage; UINT64 lParam; int iIndent; int iGroupId; UINT cColumns; UINT64 puColumns; UINT64 piColFmt; int iGroup; }; union { LVITEM32 i32; LVITEM64 i64; } local_lvi; const int LV_REMOTE_BUF_SIZE = 1024; // ALLOCATE INTERPROCESS MEMORY FOR TEXT RETRIEVAL HANDLE handle; LPVOID p_remote_lvi; // Not of type LPLVITEM to help catch bugs where p_remote_lvi->member is wrongly accessed here in our process. if ( !(p_remote_lvi = AllocInterProcMem(handle, sizeof(local_lvi) + _TSIZE(LV_REMOTE_BUF_SIZE), aHwnd, PROCESS_QUERY_INFORMATION)) ) // Allocate both the LVITEM struct and its internal string buffer in one go because VirtualAllocEx() is probably a high overhead call. return FR_E_WIN32; LPVOID p_remote_text = (LPVOID)((UINT_PTR)p_remote_lvi + sizeof(local_lvi)); // The next buffer is the memory area adjacent to, but after the struct. // PREPARE LVI STRUCT MEMBERS FOR TEXT RETRIEVAL if (IsProcess64Bit(handle)) { // See the section below for comments. local_lvi.i64.cchTextMax = LV_REMOTE_BUF_SIZE - 1; local_lvi.i64.pszText = (UINT64)p_remote_text; } else { // Subtract 1 because of that nagging doubt about size vs. length. Some MSDN examples subtract one, // such as TabCtrl_GetItem()'s cchTextMax: local_lvi.i32.cchTextMax = LV_REMOTE_BUF_SIZE - 1; // Note that LVM_GETITEM doesn't update this member to reflect the new length. local_lvi.i32.pszText = (UINT)(UINT_PTR)p_remote_text; // Extra cast avoids a truncation warning (C4311). } LRESULT i, next, length, total_length; bool is_selective = include_focused_only || include_selected_only; bool single_col_mode = (requested_col > -1 || col_count == -1); // Get only one column in these cases. // ESTIMATE THE AMOUNT OF MEMORY NEEDED TO STORE ALL THE TEXT // It's important to note that a ListView might legitimately have a collection of rows whose // fields are all empty. Since it is difficult to know whether the control is truly owner-drawn // (checking its style might not be enough?), there is no way to distinguish this condition // from one where the control's text can't be retrieved due to being owner-drawn. In any case, // this all-empty-field behavior simplifies the code and will be documented in the help file. for (i = 0, next = -1, total_length = 0; i < row_count; ++i) // For each row: { if (is_selective) { // Fix for v1.0.37.01: Prevent an infinite loop that might occur if the target control no longer // exists (perhaps having been closed in the middle of the operation) or is permanently hung. // If GetLastError() were to return zero after the below, it would mean the function timed out. // However, rather than checking and retrying, it seems better to abort the operation because: // 1) Timeout should be quite rare. // 2) Reduces code size. // 3) Having a retry really should be accompanied by SLEEP_WITHOUT_INTERRUPTION because all this // time our thread would not pumping messages (and worse, if the keyboard/mouse hooks are installed, // mouse/key lag would occur). if (!SendMessageTimeout(aHwnd, LVM_GETNEXTITEM, next, include_focused_only ? LVNI_FOCUSED : LVNI_SELECTED , SMTO_ABORTIFHUNG, 2000, (PDWORD_PTR)&next) // Timed out or failed. || (int)next == -1) // No next item. Relies on short-circuit boolean order. break; // End of estimation phase (if estimate is too small, the text retrieval below will truncate it). } else next = i; for (local_lvi.i32.iSubItem = (requested_col > -1) ? requested_col : 0 // iSubItem is which field to fetch. If it's zero, the item vs. subitem will be fetched. ; col_count == -1 || local_lvi.i32.iSubItem < col_count // If column count is undetermined (-1), always make the attempt. ; ++local_lvi.i32.iSubItem) // For each column: { if (WriteProcessMemory(handle, p_remote_lvi, &local_lvi, sizeof(local_lvi), NULL) && SendMessageTimeout(aHwnd, LVM_GETITEMTEXT, next, (LPARAM)p_remote_lvi, SMTO_ABORTIFHUNG, 2000, (PDWORD_PTR)&length)) total_length += length; //else timed out or failed, don't include the length in the estimate. Instead, the // text-fetching routine below will ensure the text doesn't overflow the var capacity. if (single_col_mode) break; } } // Add to total_length enough room for one linefeed per row, and one tab after each column // except the last (formula verified correct, though it's inflated by 1 for safety). "i" contains the // actual number of rows that will be transcribed, which might be less than row_count if is_selective==true. total_length += i * (single_col_mode ? 1 : col_count); // SET UP THE OUTPUT BUFFER if (!TokenSetResult(aResultToken, NULL, (size_t)total_length)) { FreeInterProcMem(handle, p_remote_lvi); return aResultToken.Exited() ? FR_FAIL : FR_ABORTED; } aResultToken.symbol = SYM_STRING; LPTSTR contents = aResultToken.marker; LRESULT capacity = total_length; // LRESULT avoids signed vs. unsigned compiler warnings. if (capacity > 0) // For maintainability, avoid going negative. --capacity; // Adjust to exclude the zero terminator, which simplifies things below. // RETRIEVE THE TEXT FROM THE REMOTE LISTVIEW // Start total_length at zero in case actual size is greater than estimate, in which case only a partial set of text along with its '\t' and '\n' chars will be written. for (i = 0, next = -1, total_length = 0; i < row_count; ++i) // For each row: { if (is_selective) { // Fix for v1.0.37.01: Prevent an infinite loop (for details, see comments in the estimation phase above). if (!SendMessageTimeout(aHwnd, LVM_GETNEXTITEM, next, include_focused_only ? LVNI_FOCUSED : LVNI_SELECTED , SMTO_ABORTIFHUNG, 2000, (PDWORD_PTR)&next) // Timed out or failed. || (int)next == -1) // No next item. break; // See comment above for why unconditional break vs. continue. } else // Retrieve every row, so the "next" row becomes the "i" index. next = i; // Insert a linefeed before each row except the first: if (i && total_length < capacity) // If we're at capacity, it will exit the loops when the next field is read. { *contents++ = '\n'; ++total_length; } // iSubItem is which field to fetch. If it's zero, the item vs. subitem will be fetched: for (local_lvi.i32.iSubItem = (requested_col > -1) ? requested_col : 0 ; col_count == -1 || local_lvi.i32.iSubItem < col_count // If column count is undetermined (-1), always make the attempt. ; ++local_lvi.i32.iSubItem) // For each column: { // Insert a tab before each column except the first and except when in single-column mode: if (!single_col_mode && local_lvi.i32.iSubItem && total_length < capacity) // If we're at capacity, it will exit the loops when the next field is read. { *contents++ = '\t'; ++total_length; } if (!WriteProcessMemory(handle, p_remote_lvi, &local_lvi, sizeof(local_lvi), NULL) || !SendMessageTimeout(aHwnd, LVM_GETITEMTEXT, next, (LPARAM)p_remote_lvi, SMTO_ABORTIFHUNG, 2000, (PDWORD_PTR)&length)) continue; // Timed out or failed. It seems more useful to continue getting text rather than aborting the operation. // Otherwise, the message was successfully sent. if (length > 0) { if (total_length + length > capacity) goto break_both; // "goto" for simplicity and code size reduction. // Otherwise: // READ THE TEXT FROM THE REMOTE PROCESS // Although MSDN has the following comment about LVM_GETITEM, it is not present for // LVM_GETITEMTEXT. Therefore, to improve performance (by avoiding a second call to // ReadProcessMemory) and to reduce code size, we'll take them at their word until // proven otherwise. Here is the MSDN comment about LVM_GETITEM: "Applications // should not assume that the text will necessarily be placed in the specified // buffer. The control may instead change the pszText member of the structure // to point to the new text, rather than place it in the buffer." if (ReadProcessMemory(handle, p_remote_text, contents, length * sizeof(TCHAR), NULL)) { contents += length; // Point it to the position where the next char will be written. total_length += length; // Recalculate length in case its different than the estimate (for any reason). } //else it failed; but even so, continue on to put in a tab (if called for). } //else length is zero; but even so, continue on to put in a tab (if called for). if (single_col_mode) break; } // for() each column } // for() each row break_both: *contents = '\0'; // Final termination. Above has reserved room for this one byte. aResultToken.marker_length = (size_t)total_length; // Update to actual vs. estimated length. FreeInterProcMem(handle, p_remote_lvi); return OK; } FResult ControlSetTab(HWND aHwnd, DWORD aTabIndex) { DWORD_PTR dwResult; // MSDN: "If the tab control does not have the TCS_BUTTONS style, changing the focus also changes // the selected tab. In this case, the tab control sends the TCN_SELCHANGING and TCN_SELCHANGE // notification codes to its parent window." if (!SendMessageTimeout(aHwnd, TCM_SETCURFOCUS, aTabIndex, 0, SMTO_ABORTIFHUNG, 2000, &dwResult)) return FR_E_WIN32; // Tab controls with the TCS_BUTTONS style need additional work: if (GetWindowLong(aHwnd, GWL_STYLE) & TCS_BUTTONS) { // Problem: // TCM_SETCURFOCUS does not change the selected tab if TCS_BUTTONS is set. // // False solution #1 (which used to be recommended in the docs): // Send a TCM_SETCURSEL method afterward. TCM_SETCURSEL changes the selected tab, // but doesn't notify the control's parent, so it doesn't update the tab's contents. // // False solution #2: // Send a WM_NOTIFY message to the parent window to notify it. Can't be done. // MSDN says: "For Windows 2000 and later systems, the WM_NOTIFY message cannot // be sent between processes." // // Solution #1: // Send VK_LEFT/VK_RIGHT as many times as needed. // // Solution #2: // Set the focus to an adjacent tab and then send VK_LEFT/VK_RIGHT. // - Must choose an appropriate tab index and vk depending on which tab is being // selected, since VK_LEFT/VK_RIGHT don't wrap around. // - Ends up tempting optimisations which increase code size, such as to avoid // TCM_SETCURFOCUS if an adjacent tab is already focused. // - Still needs VK_SPACE afterward to actually select the tab. // // Solution #3 (the one below): // Set the focus to the appropriate tab and then send VK_SPACE. // - Since we've already set the focus, all we need to do is send VK_SPACE. // - If the tab index is invalid and the user has focused but not selected // another tab, that tab will be selected. This seems harmless enough. // PostMessage(aHwnd, WM_KEYDOWN, VK_SPACE, 0x00000001); PostMessage(aHwnd, WM_KEYUP, VK_SPACE, 0xC0000001); } return OK; } bif_impl FResult StatusBarGetText(optl<int> aPart, WINTITLE_PARAMETERS_DECL, StrRet &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; // StatusBarUtil will handle any NULL control_window or zero part# for us. return StatusBarUtil(target_window, aPart.value_or(1), &aRetVal); } bif_impl FResult StatusBarWait(optl<StrArg> aText, optl<double> aTimeout, optl<int> aPart , ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<int> aInterval , optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText, int &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; // Make a copy of any memory areas that are volatile (due to caller passing a variable, // which could be reassigned by a new hotkey subroutine launched while we are waiting) // but whose contents we need to refer to while we are waiting: TCHAR text_to_wait_for[4096]; tcslcpy(text_to_wait_for, aText.value_or_empty(), _countof(text_to_wait_for)); // StatusBarUtil will handle any NULL control_window or zero part# for us. auto fr = StatusBarUtil(target_window, aPart.value_or(0), nullptr, text_to_wait_for , aTimeout.has_value() ? int(aTimeout.value() * 1000) : -1, aInterval.value_or(50)); if (fr != TRUE && fr != FALSE) return fr; aRetVal = fr; return OK; } static FResult PostSendMessage(UINT aMsg, ExprTokenType *aWParam, ExprTokenType *aLParam , CONTROL_PARAMETERS_DECL_OPT, optl<int> aTimeout = nullptr, UINT_PTR *aSendRetVal = nullptr) { bool successful = false; DETERMINE_TARGET_CONTROL2; INT_PTR param[2] = { 0, 0 }; ExprTokenType *aParam[] = { aWParam, aLParam }; for (int i = 0; i < 2; ++i) // Two iterations: wParam and lParam. { if (!aParam[i]) continue; ExprTokenType &this_param = *aParam[i]; if (this_param.symbol == SYM_VAR) this_param.var->ToTokenSkipAddRef(this_param); switch (this_param.symbol) { case SYM_INTEGER: param[i] = (INT_PTR)this_param.value_int64; break; case SYM_OBJECT: // Support Buffer-like objects, i.e, objects with a "Ptr" property. { size_t ptr_property_value; ResultToken result_token; result_token.SetResult(OK); GetBufferObjectPtr(result_token, this_param.object, ptr_property_value); if (result_token.Exited()) return FR_FAIL; param[i] = ptr_property_value; break; } case SYM_STRING: LPTSTR error_marker; param[i] = (INT_PTR)istrtoi64(this_param.marker, &error_marker); if (!*error_marker) // Valid number or empty string. break; //else: It's a non-numeric string; maybe the caller forgot StrPtr(). // Note that an empty string would satisfy the check above. // Fall through: default: // SYM_FLOAT: Seems best to treat it as an error rather than truncating the value. return FR_E_ARG(1 + i); } } DWORD_PTR dwResult; if (aSendRetVal) successful = SendMessageTimeout(control_window, aMsg, (WPARAM)param[0], (LPARAM)param[1], SMTO_ABORTIFHUNG, aTimeout.value_or(5000), &dwResult); else successful = PostMessage(control_window, aMsg, (WPARAM)param[0], (LPARAM)param[1]); if (!successful) { auto last_error = GetLastError(); if (aSendRetVal && last_error == ERROR_TIMEOUT) return FError(ERR_TIMEOUT, nullptr, ErrorPrototype::Timeout); return FR_E_WIN32(last_error); } if (aSendRetVal) *aSendRetVal = dwResult; return OK; } bif_impl FResult ScriptSendMessage(UINT aMsg, ExprTokenType *aWParam, ExprTokenType *aLParam , CONTROL_PARAMETERS_DECL_OPT, optl<int> aTimeout, UINT_PTR &aRetVal) { return PostSendMessage(aMsg, aWParam, aLParam, CONTROL_PARAMETERS, aTimeout, &aRetVal); } bif_impl FResult ScriptPostMessage(UINT aMsg, ExprTokenType *aWParam, ExprTokenType *aLParam , CONTROL_PARAMETERS_DECL_OPT) { return PostSendMessage(aMsg, aWParam, aLParam, CONTROL_PARAMETERS); } bif_impl FResult WinSetRegion(optl<StrArg> aOptions, WINTITLE_PARAMETERS_DECL) { HWND target_window; DETERMINE_TARGET_WINDOW; if (aOptions.is_blank_or_omitted()) // Attempt to restore the window's normal/correct region. { // Fix for v1.0.31.07: The old method used the following, but apparently it's not the correct // way to restore a window's proper/normal region because when such a window is later maximized, // it retains its incorrect/smaller region: //if (GetWindowRect(aWnd, &rect)) //{ // // Adjust the rect to keep the same size but have its upper-left corner at 0,0: // rect.right -= rect.left; // rect.bottom -= rect.top; // rect.left = 0; // rect.top = 0; // if (hrgn = CreateRectRgnIndirect(&rect)) // Assign // { // // Presumably, the system deletes the former region when upon a successful call to SetWindowRgn(). // if (SetWindowRgn(aWnd, hrgn, TRUE)) // _f_return_empty; // // Otherwise, get rid of it since it didn't take effect: // DeleteObject(hrgn); // } //} //// Since above didn't return: //return OK; // It's undocumented by MSDN, but apparently setting the Window's region to NULL restores it // to proper working order: if (!SetWindowRgn(target_window, NULL, TRUE)) return FR_E_WIN32; return OK; } #define MAX_REGION_POINTS 2000 // 2000 requires 16 KB of stack space. POINT pt[MAX_REGION_POINTS]; int pt_count; LPCTSTR cp; // Set defaults prior to parsing options in case any options are absent: int width = COORD_UNSPECIFIED; int height = COORD_UNSPECIFIED; int rr_width = COORD_UNSPECIFIED; // These two are for the rounded-rectangle method. int rr_height = COORD_UNSPECIFIED; bool use_ellipse = false; int fill_mode = ALTERNATE; // Concerning polygon regions: ALTERNATE is used by default (somewhat arbitrarily, but it seems to be the // more typical default). // MSDN: "In general, the modes [ALTERNATE vs. WINDING] differ only in cases where a complex, // overlapping polygon must be filled (for example, a five-sided polygon that forms a five-pointed // star with a pentagon in the center). In such cases, ALTERNATE mode fills every other enclosed // region within the polygon (that is, the points of the star), but WINDING mode fills all regions // (that is, the points and the pentagon)." for (pt_count = 0, cp = aOptions.value(); *(cp = omit_leading_whitespace(cp));) { // To allow the MAX to be increased in the future with less chance of breaking existing scripts, consider this an error. if (pt_count >= MAX_REGION_POINTS) return FR_E_ARG(0); if (cisdigit(*cp) || *cp == '-' || *cp == '+') // v1.0.38.02: Recognize leading minus/plus sign so that the X-coord is just as tolerant as the Y. { // Assume it's a pair of X/Y coordinates. It's done this way rather than using X and Y // as option letters because: // 1) The script is more readable when there are multiple coordinates (for polygon). // 2) It enforces the fact that each X must have a Y and that X must always come before Y // (which simplifies and reduces the size of the code). pt[pt_count].x = ATOI(cp); // For the delimiter, dash is more readable than pipe, even though it overlaps with "minus sign". // "x" is not used to avoid detecting "x" inside hex numbers. #define REGION_DELIMITER '-' if ( !(cp = _tcschr(cp + 1, REGION_DELIMITER)) ) // v1.0.38.02: cp + 1 to omit any leading minus sign. return FR_E_ARG(0); pt[pt_count].y = ATOI(++cp); // Increment cp by only 1 to support negative Y-coord. ++pt_count; // Move on to the next element of the pt array. } else { ++cp; switch(_totupper(cp[-1])) { case 'E': use_ellipse = true; break; case 'R': if (!*cp || *cp == ' ') // Use 30x30 default. { rr_width = 30; rr_height = 30; } else { rr_width = ATOI(cp); if (cp = _tcschr(cp, REGION_DELIMITER)) // Assign rr_height = ATOI(++cp); else // Avoid problems with going beyond the end of the string. return FR_E_ARG(0); } break; case 'W': if (!_tcsnicmp(cp, _T("ind"), 3)) // [W]ind. fill_mode = WINDING; else width = ATOI(cp); break; case 'H': height = ATOI(cp); break; default: // For simplicity and to reserve other letters for future use, unknown options result in failure. return FR_E_ARG(0); } // switch() } // else if ( !(cp = _tcschr(cp, ' ')) ) // No more items. break; } if (!pt_count) return FR_E_ARG(0); bool width_and_height_were_both_specified = !(width == COORD_UNSPECIFIED || height == COORD_UNSPECIFIED); if (width_and_height_were_both_specified) { width += pt[0].x; // Make width become the right side of the rect. height += pt[0].y; // Make height become the bottom. } HRGN hrgn; if (use_ellipse) // Ellipse. hrgn = width_and_height_were_both_specified ? CreateEllipticRgn(pt[0].x, pt[0].y, width, height) : NULL; else if (rr_width != COORD_UNSPECIFIED) // Rounded rectangle. hrgn = width_and_height_were_both_specified ? CreateRoundRectRgn(pt[0].x, pt[0].y, width, height, rr_width, rr_height) : NULL; else if (width_and_height_were_both_specified) // Rectangle. hrgn = CreateRectRgn(pt[0].x, pt[0].y, width, height); else // Polygon hrgn = CreatePolygonRgn(pt, pt_count, fill_mode); if (!hrgn) return FR_E_WIN32; // Since above didn't return, hrgn is now a non-NULL region ready to be assigned to the window. // Presumably, the system deletes the window's former region upon a successful call to SetWindowRgn(): if (!SetWindowRgn(target_window, hrgn, TRUE)) { DeleteObject(hrgn); return FR_E_WIN32; } //else don't delete hrgn since the system has taken ownership of it. // Since above didn't return, it's a success. return OK; } bif_impl FResult WinSetAlwaysOnTop(optl<int> aValue, WINTITLE_PARAMETERS_DECL) { HWND target_window, topmost_or_not; DETERMINE_TARGET_WINDOW; switch (aValue.value_or(1)) { case 1: topmost_or_not = HWND_TOPMOST; break; case 0: topmost_or_not = HWND_NOTOPMOST; break; case -1: topmost_or_not = (GetWindowLong(target_window, GWL_EXSTYLE) & WS_EX_TOPMOST) ? HWND_NOTOPMOST : HWND_TOPMOST; break; default: return FR_E_ARG(0); } // SetWindowLong() didn't seem to work, at least not on some windows. But this does. // As of v1.0.25.14, SWP_NOACTIVATE is also specified, though its absence does not actually // seem to activate the window, at least on XP (perhaps due to anti-focus-stealing measure // in Win98/2000 and beyond). Or perhaps its something to do with the presence of // topmost_or_not (HWND_TOPMOST/HWND_NOTOPMOST), which might always avoid activating the // window. return SetWindowPos(target_window, topmost_or_not, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE) ? OK : FR_E_WIN32; } bif_impl FResult WinGetAlwaysOnTop(WINTITLE_PARAMETERS_DECL, BOOL &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; aRetVal = (GetWindowLong(target_window, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0; return OK; } bif_impl FResult WinRedraw(WINTITLE_PARAMETERS_DECL) { HWND target_window; DETERMINE_TARGET_WINDOW; // Seems best to always have the last param be TRUE. Also, it seems best not to call // UpdateWindow(), which forces the window to immediately process a WM_PAINT message, // since that might not be desirable. Some other methods of getting a window to redraw: // SendMessage(mHwnd, WM_NCPAINT, 1, 0); // RedrawWindow(mHwnd, NULL, NULL, RDW_INVALIDATE|RDW_FRAME|RDW_UPDATENOW); // SetWindowPos(mHwnd, NULL, 0, 0, 0, 0, SWP_DRAWFRAME|SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); // GetClientRect(mHwnd, &client_rect); InvalidateRect(mHwnd, &client_rect, TRUE); InvalidateRect(target_window, NULL, TRUE); return OK; } static FResult WinMoveTopBottom(WINTITLE_PARAMETERS_DECL, HWND mode) { HWND target_window; DETERMINE_TARGET_WINDOW; // Note: SWP_NOACTIVATE must be specified otherwise the target window often fails to move: if (!SetWindowPos(target_window, mode, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE)) return FR_E_WIN32; return OK; } bif_impl FResult WinMoveTop(WINTITLE_PARAMETERS_DECL) { return WinMoveTopBottom(WINTITLE_PARAMETERS, HWND_TOP); } bif_impl FResult WinMoveBottom(WINTITLE_PARAMETERS_DECL) { return WinMoveTopBottom(WINTITLE_PARAMETERS, HWND_BOTTOM); } bif_impl FResult WinSetTitle(StrArg aNewTitle, WINTITLE_PARAMETERS_DECL) { HWND target_window; DETERMINE_TARGET_WINDOW; if (!SetWindowText(target_window, aNewTitle)) return FR_E_WIN32; return OK; } bif_impl FResult WinGetTitle(WINTITLE_PARAMETERS_DECL, StrRet &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; auto estimated_length = GetWindowTextLength(target_window); auto buf = aRetVal.Alloc(estimated_length); if (!buf) return FR_E_OUTOFMEM; // Update length using the actual length, rather than the estimate provided by GetWindowTextLength(): auto actual_length = GetWindowText(target_window, buf, estimated_length + 1); aRetVal.SetLength(actual_length); if (!actual_length) // There was no text to get or GetWindowText() failed. *buf = '\0'; return OK; } bif_impl FResult WinGetClass(WINTITLE_PARAMETERS_DECL, StrRet &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; TCHAR class_name[WINDOW_CLASS_SIZE]; if (!GetClassName(target_window, class_name, _countof(class_name))) return FR_E_WIN32; if (!aRetVal.Copy(class_name)) return FR_E_OUTOFMEM; return OK; } static FResult WinGetListCount(WINTITLE_PARAMETERS_DECL, WindowSearch &ws) { HWND target_window = NULL; bool hwnd_specified = false; if (aWinTitle) { auto fr = DetermineTargetHwnd(target_window, hwnd_specified, *aWinTitle); if (fr != OK) return fr; } auto title = aWinTitle ? TokenToString(*aWinTitle) : _T(""); auto text = aWinText.value_or_empty(); auto ex_title = aExcludeTitle.value_or_empty(); auto ex_text = aExcludeText.value_or_empty(); // Check if we were asked to count the active window: if (USE_FOREGROUND_WINDOW(title, text, ex_title, ex_text)) { SET_TARGET_TO_ALLOWABLE_FOREGROUND(g->DetectHiddenWindows) hwnd_specified = true; } if (hwnd_specified) { if (target_window) { if (ws.mArray) ws.mArray->Append((__int64)(size_t)target_window); ws.mFoundCount++; } return OK; } ws.mFindLastMatch = true; // Must set mFindLastMatch to get all matches rather than just the first. // Enumerate all windows which match the criteria: // If aTitle is ahk_id nnnn, the Enum() below will be inefficient. However, ahk_id is almost unheard of // in this context because it makes little sense, so no extra code is added to make that case efficient. if (ws.SetCriteria(*g, title, text, ex_title, ex_text)) // These criteria allow the possibility of a match. EnumWindows(EnumParentFind, (LPARAM)&ws); //else leave ws.mFoundCount set to zero (by the constructor). return OK; } bif_impl FResult WinGetCount(WINTITLE_PARAMETERS_DECL, int &aRetVal) { WindowSearch ws; auto fr = WinGetListCount(WINTITLE_PARAMETERS, ws); aRetVal = ws.mFoundCount; return fr; } bif_impl FResult WinGetList(WINTITLE_PARAMETERS_DECL, IObject *&aRetVal) { WindowSearch ws; if ( !(ws.mArray = Array::Create()) ) return FR_E_OUTOFMEM; auto fr = WinGetListCount(WINTITLE_PARAMETERS, ws); if (fr == OK) aRetVal = ws.mArray; else ws.mArray->Release(); return fr; } bif_impl FResult WinGetID(WINTITLE_PARAMETERS_DECL, UINT &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; aRetVal = (UINT)(UINT_PTR)target_window; return OK; } bif_impl FResult WinGetIDLast(WINTITLE_PARAMETERS_DECL, UINT &aRetVal) { HWND target_window; auto fr = DetermineTargetWindow(target_window, aWinTitle, aWinText.value_or_null(), aExcludeTitle.value_or_null(), aExcludeText.value_or_null() , true); // Pass true for aFindLastMatch. if (fr != OK) return fr; aRetVal = (UINT)(UINT_PTR)target_window; return OK; } bif_impl FResult WinGetPID(WINTITLE_PARAMETERS_DECL, UINT &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; DWORD pid; GetWindowThreadProcessId(target_window, &pid); aRetVal = pid; return OK; } static FResult WinGetProcessName(WINTITLE_PARAMETERS_DECL, StrRet &aRetVal, bool aGetNameOnly) { HWND target_window; DETERMINE_TARGET_WINDOW; DWORD pid; GetWindowThreadProcessId(target_window, &pid); TCHAR name[MAX_PATH]; if (!GetProcessName(pid, name, _countof(name), aGetNameOnly)) return FR_E_WIN32; if (!aRetVal.Copy(name)) return FR_E_OUTOFMEM; return OK; } bif_impl FResult WinGetProcessName(WINTITLE_PARAMETERS_DECL, StrRet &aRetVal) { return WinGetProcessName(WINTITLE_PARAMETERS, aRetVal, true); } bif_impl FResult WinGetProcessPath(WINTITLE_PARAMETERS_DECL, StrRet &aRetVal) { return WinGetProcessName(WINTITLE_PARAMETERS, aRetVal, false); } bif_impl FResult WinGetMinMax(WINTITLE_PARAMETERS_DECL, int &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; // Testing shows that it's not possible for a minimized window to also be maximized, // but GetWindowPlacement could be used to determine whether it *would* be maximized // upon restoration, and what the size will be. aRetVal = IsZoomed(target_window) ? 1 : (IsIconic(target_window) ? -1 : 0); return OK; } static FResult WinGetLong(WINTITLE_PARAMETERS_DECL, UINT &aRetVal, int nIndex) { HWND target_window; DETERMINE_TARGET_WINDOW; aRetVal = GetWindowLong(target_window, nIndex); return OK; } bif_impl FResult WinGetStyle(WINTITLE_PARAMETERS_DECL, UINT &aRetVal) { return WinGetLong(WINTITLE_PARAMETERS, aRetVal, GWL_STYLE); } bif_impl FResult WinGetExStyle(WINTITLE_PARAMETERS_DECL, UINT &aRetVal) { return WinGetLong(WINTITLE_PARAMETERS, aRetVal, GWL_EXSTYLE); } // Shared by WinSetStyle, ControlSetStyle and the Ex variants. FResult WinSetStyle(StrArg aValue, CONTROL_PARAMETERS_DECL_OPT, int style_index) { if (!*aValue) return FR_E_ARG(0); // Seems best to treat an explicit blank as an error. DETERMINE_TARGET_CONTROL2; // If this is WinSetStyle rather than ControlSetStyle, control_window == target_window. DWORD new_style, orig_style = GetWindowLong(control_window, style_index); // +/-/^ are used instead of |&^ because the latter is confusing, namely that & really means &=~style, etc. if (!_tcschr(_T("+-^"), *aValue)) new_style = ATOU(aValue); // No prefix, so this new style will entirely replace the current style. else { ++aValue; DWORD style_change = ATOU(aValue); switch(aValue[-1]) { case '+': new_style = orig_style | style_change; break; case '-': new_style = orig_style & ~style_change; break; case '^': new_style = orig_style ^ style_change; break; } } if (new_style == orig_style) // No change needed. Detection of success below relies on this check. return OK; // Currently, BM_SETSTYLE is not done when GetClassName() says that the control is a button/checkbox/groupbox. // This is because the docs for BM_SETSTYLE don't contain much, if anything, that anyone would ever // want to change. SetLastError(0); // Prior to SetWindowLong(), as recommended by MSDN. if (SetWindowLong(control_window, style_index, new_style) || !GetLastError()) // This is the precise way to detect success according to MSDN. { // Even if it indicated success, sometimes it failed anyway. Find out for sure: if (GetWindowLong(control_window, style_index) != orig_style) // Even a partial change counts as a success. { if (control_window == target_window) // WinSetStyle/WinSetExStyle { // SetWindowPos is also necessary, otherwise the frame thickness entirely around the window // does not get updated (just parts of it): SetWindowPos(target_window, NULL, 0, 0, 0, 0, SWP_DRAWFRAME|SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); // Since SetWindowPos() probably doesn't know that the style changed, below is probably necessary // too, at least in some cases: } InvalidateRect(control_window, NULL, TRUE); // Quite a few styles require this to become visibly manifest. return OK; } } return FR_E_WIN32; } bif_impl FResult WinSetStyle(StrArg aValue, WINTITLE_PARAMETERS_DECL) { return WinSetStyle(aValue, nullptr, WINTITLE_PARAMETERS, GWL_STYLE); } bif_impl FResult WinSetExStyle(StrArg aValue, WINTITLE_PARAMETERS_DECL) { return WinSetStyle(aValue, nullptr, WINTITLE_PARAMETERS, GWL_EXSTYLE); } bif_impl FResult WinGetTransparent(WINTITLE_PARAMETERS_DECL, ResultToken &aResultToken) { HWND target_window; DETERMINE_TARGET_WINDOW; BYTE alpha; DWORD flags; if (!(GetLayeredWindowAttributes(target_window, nullptr, &alpha, &flags))) return OK; if (flags & LWA_ALPHA) aResultToken.SetValue(alpha); return OK; } bif_impl FResult WinGetTransColor(WINTITLE_PARAMETERS_DECL, StrRet &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; COLORREF color; DWORD flags; if (!(GetLayeredWindowAttributes(target_window, &color, nullptr, &flags))) return OK; if (flags & LWA_COLORKEY) { // Store in hex format to aid in debugging scripts. Also, the color is always // stored in RGB format, since that's what WinSet uses: LPTSTR result = aRetVal.CallerBuf(); _stprintf(result, _T("0x%06X"), bgr_to_rgb(color)); aRetVal.SetTemp(result); } // Otherwise, this window does not have a transparent color (or it's not accessible to us, // perhaps for reasons described at MSDN GetLayeredWindowAttributes()). return OK; } static FResult WinSetTrans(COLORREF color, LPCTSTR aAlpha, WINTITLE_PARAMETERS_DECL) { // It appears that turning on WS_EX_LAYERED in an attempt to retrieve the window's // former transparency setting does not work. The OS probably does not store the // former transparency level (i.e. it forgets it the moment the WS_EX_LAYERED exstyle // is turned off). This is true even if the following are done after the SetWindowLong(): //MySetLayeredWindowAttributes(target_window, 0, 0, 0) // or: //if (MyGetLayeredWindowAttributes(target_window, &color, &alpha, &flags)) // MySetLayeredWindowAttributes(target_window, color, alpha, flags); // The above is why there is currently no "on" or "toggle" sub-command, just "Off". // Since the color of an HBRUSH can't be easily determined (since it can be a pattern and // since there seem to be no easy API calls to discover the colors of pixels in an HBRUSH), // the following is not yet implemented: Use window's own class background color (via // GetClassLong) if aValue is entirely blank. DWORD flags = color == CLR_NONE ? 0 : LWA_COLORKEY; BYTE alpha; if (aAlpha && *aAlpha) { flags |= LWA_ALPHA; LPCTSTR endptr; auto n = istrtoi64(aAlpha, &endptr); if (*endptr || n < 0 || n > 255) return FR_E_ARG(0); alpha = (BYTE)n; } HWND target_window; DETERMINE_TARGET_WINDOW; BOOL success; DWORD exstyle = GetWindowLong(target_window, GWL_EXSTYLE); if (!flags) // One user reported that turning off the attribute helps window's scrolling performance. success = SetWindowLong(target_window, GWL_EXSTYLE, exstyle & ~WS_EX_LAYERED); else { SetWindowLong(target_window, GWL_EXSTYLE, exstyle | WS_EX_LAYERED); success = SetLayeredWindowAttributes(target_window, color, alpha, flags); } return success ? OK : FR_E_WIN32; } bif_impl FResult WinSetTransparent(StrArg aAlpha, WINTITLE_PARAMETERS_DECL) { if (!_tcsicmp(aAlpha, _T("Off"))) aAlpha = nullptr; return WinSetTrans(CLR_NONE, aAlpha, WINTITLE_PARAMETERS); } bif_impl FResult WinSetTransColor(ExprTokenType &aValue, WINTITLE_PARAMETERS_DECL) { TCHAR aValue_copy[256]; COLORREF color = CLR_NONE; LPTSTR alpha = nullptr; switch (TypeOfToken(aValue)) { case SYM_INTEGER: // Handle pure numeric values this way rather than allowing them to be implicitly converted // to string, since the conversion would use decimal formatting, but the string is assumed // to use hexadecimal. color = rgb_to_bgr((DWORD)TokenToInt64(aValue)); break; default: // SYM_FLOAT, SYM_OBJECT return FR_E_ARG(0); case SYM_STRING: // The reason WinSetTransColor accepts both the color and an optional transparency settings // is that calling SetLayeredWindowAttributes() with only the LWA_COLORKEY flag causes the // window to lose its current transparency setting in favor of the transparent color. This // is true even though the LWA_ALPHA flag was not specified, which seems odd and is a little // disappointing, but that's the way it is on XP at least. tcslcpy(aValue_copy, TokenToString(aValue), _countof(aValue_copy)); // Make a modifiable copy. if (!_tcsicmp(aValue_copy, _T("Off"))) break; alpha = StrChrAny(aValue_copy, _T(" \t")); // Space or tab. if (alpha) { *alpha = '\0'; alpha = omit_leading_whitespace(alpha + 1); // Point it to the second substring. } if (*aValue_copy) // Seems more flexible to allow a leading space to omit the color key, rather than interpreting it as black or an error. { if (!ColorToBGR(aValue_copy, color)) return FR_E_ARG(0); } break; } return WinSetTrans(color, alpha, WINTITLE_PARAMETERS); } static FResult WinGetControls(WINTITLE_PARAMETERS_DECL, IObject *&aRetVal, bool aFetchHWNDs) // Caller must ensure that aTargetWindow is non-NULL and valid. // Every control is fetched rather than just a list of distinct class names (possibly with a // second script array containing the quantity of each class) because it's conceivable that the // z-order of the controls will be useful information to some script authors. { HWND target_window; DETERMINE_TARGET_WINDOW; control_list_type cl; // A big struct containing room to store class names and counts for each. if ( !(aRetVal = cl.target_array = Array::Create()) ) return FR_E_OUTOFMEM; CL_INIT_CONTROL_LIST(cl) cl.fetch_hwnds = aFetchHWNDs; EnumChildWindows(target_window, EnumChildGetControlList, (LPARAM)&cl); return OK; } bif_impl FResult WinGetControls(WINTITLE_PARAMETERS_DECL, IObject *&aRetVal) { return WinGetControls(WINTITLE_PARAMETERS, aRetVal, false); } bif_impl FResult WinGetControlsHwnd(WINTITLE_PARAMETERS_DECL, IObject *&aRetVal) { return WinGetControls(WINTITLE_PARAMETERS, aRetVal, true); } BOOL CALLBACK EnumChildGetControlList(HWND aWnd, LPARAM lParam) { control_list_type &cl = *(control_list_type *)lParam; // For performance and convenience. // cl.fetch_hwnds==true is a new mode in v1.0.43.06+ to help performance of AHK Window Info and other // scripts that want to operate directly on the HWNDs. if (cl.fetch_hwnds) { cl.target_array->Append((__int64)(size_t)aWnd); } else // The mode that fetches ClassNN vs. HWND. { TCHAR line[WINDOW_CLASS_SIZE + 5]; // +5 to allow room for the sequence number to be appended later below. int line_length; // Note: IsWindowVisible(aWnd) is not checked because although Window Spy does not reveal // hidden controls if the mouse happens to be hovering over one, it does include them in its // sequence numbering (which is a relieve, since results are probably much more consistent // then, esp. for apps that hide and unhide controls in response to actions on other controls). if ( !(line_length = GetClassName(aWnd, line, WINDOW_CLASS_SIZE)) ) // Don't include the +5 extra size since that is reserved for seq. number. return TRUE; // Probably very rare. Continue enumeration since Window Spy doesn't even check for failure. // It has been verified that GetClassName()'s returned length does not count the terminator. // Check if this class already exists in the class array: int class_index; for (class_index = 0; class_index < cl.total_classes; ++class_index) if (!_tcsicmp(cl.class_name[class_index], line)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales. break; if (class_index < cl.total_classes) // Match found. { ++cl.class_count[class_index]; // Increment the number of controls of this class that have been found so far. if (cl.class_count[class_index] > 99999) // Sanity check; prevents buffer overflow or number truncation in "line". return TRUE; // Continue the enumeration. } else // No match found, so create new entry if there's room. { if (cl.total_classes == CL_MAX_CLASSES // No pointers left. || CL_CLASS_BUF_SIZE - (cl.buf_free_spot - cl.class_buf) - 1 < line_length) // Insuff. room in buf. return TRUE; // Very rare. Continue the enumeration so that class names already found can be collected. // Otherwise: cl.class_name[class_index] = cl.buf_free_spot; // Set this pointer to its place in the buffer. _tcscpy(cl.class_name[class_index], line); // Copy the string into this place. cl.buf_free_spot += line_length + 1; // +1 because every string in the buf needs its own terminator. cl.class_count[class_index] = 1; // Indicate that the quantity of this class so far is 1. ++cl.total_classes; } _itot(cl.class_count[class_index], line + line_length, 10); // Append the seq. number to line. cl.target_array->Append(line); // Append class name+seq. number to the array. } return TRUE; // Continue enumeration through all the windows. } bif_impl FResult WinGetText(WINTITLE_PARAMETERS_DECL, StrRet &aRetVal) { HWND target_window; DETERMINE_TARGET_WINDOW; length_and_buf_type sab; sab.buf = NULL; // Tell it just to calculate the length this time around. sab.total_length = 0; // Init sab.capacity = 0; // EnumChildWindows(target_window, EnumChildGetText, (LPARAM)&sab); if (!sab.total_length) // No text in window. return OK; sab.buf = aRetVal.Alloc(sab.total_length); if (!sab.buf) return FR_E_OUTOFMEM; // Note: The capacity member below exists because granted capacity might be a little larger than we asked for, // which allows the actual text fetched to be larger than the length estimate retrieved by the first pass // (which generally shouldn't happen since MSDN docs say that the actual length can be less, but never greater, // than the estimate length): sab.capacity = sab.total_length + 1; // Capacity includes the zero terminator, i.e. it's the size of the memory area. sab.total_length = 0; // Reinitialize. EnumChildWindows(target_window, EnumChildGetText, (LPARAM)&sab); // Get the text. // Length is set explicitly below in case it wound up being smaller than expected/estimated. // MSDN says that can happen generally, and also specifically because: "ANSI applications may have // the string in the buffer reduced in size (to a minimum of half that of the wParam value) due to // conversion from ANSI to Unicode." aRetVal.SetLength(sab.total_length); if (!sab.total_length) // Something went wrong. return FR_E_FAILED; return OK; } BOOL CALLBACK EnumChildGetText(HWND aWnd, LPARAM lParam) { if (!g->DetectHiddenText && !IsWindowVisible(aWnd)) return TRUE; // This child/control is hidden and user doesn't want it considered, so skip it. length_and_buf_type &lab = *(length_and_buf_type *)lParam; // For performance and convenience. int length; if (lab.buf) length = GetWindowTextTimeout(aWnd, lab.buf + lab.total_length , (int)(lab.capacity - lab.total_length)); // Not +1. Verified correct because WM_GETTEXT accepts size of buffer, not its length. else length = GetWindowTextTimeout(aWnd); lab.total_length += length; if (length) { if (lab.buf) { if (lab.capacity - lab.total_length > 2) // Must be >2 due to zero terminator. { _tcscpy(lab.buf + lab.total_length, _T("\r\n")); // Something to delimit each control's text. lab.total_length += 2; } // else don't increment total_length } else lab.total_length += 2; // Since buf is NULL, accumulate the size that *would* be needed. } return TRUE; // Continue enumeration through all the child windows of this parent. } static FResult WinGetPos(int *aX, int *aY, int *aWidth, int *aHeight, WINTITLE_PARAMETERS_DECL, bool aClient) { HWND target_window; DETERMINE_TARGET_WINDOW; RECT rect; if (!aClient) { GetWindowRect(target_window, &rect); rect.right -= rect.left; // Convert right to width. rect.bottom -= rect.top; // Convert bottom to height. } else { GetClientRect(target_window, &rect); // Get client pos relative to client (position is always 0,0). // Since the position is always 0,0, right,bottom are already equivalent to width,height. MapWindowPoints(target_window, NULL, (LPPOINT)&rect, 1); // Convert position to screen coordinates. } if (aX) *aX = rect.left; if (aY) *aY = rect.top; if (aWidth) *aWidth = rect.right; if (aHeight) *aHeight = rect.bottom; return OK; } bif_impl FResult WinGetPos(int *aX, int *aY, int *aWidth, int *aHeight, WINTITLE_PARAMETERS_DECL) { return WinGetPos(aX, aY, aWidth, aHeight, WINTITLE_PARAMETERS, false); } bif_impl FResult WinGetClientPos(int *aX, int *aY, int *aWidth, int *aHeight, WINTITLE_PARAMETERS_DECL) { return WinGetPos(aX, aY, aWidth, aHeight, WINTITLE_PARAMETERS, true); } DECLSPEC_NOINLINE // Lexikos: noinline saves ~300 bytes. Originally the duplicated code prevented inlining. HWND Line::DetermineTargetWindow(LPCTSTR aTitle, LPCTSTR aText, LPCTSTR aExcludeTitle, LPCTSTR aExcludeText) { // Lexikos: Not sure why these checks were duplicated here and in WinExist(), // so they're left here for reference: //HWND target_window; // A variable of this name is used by the macros below. //IF_USE_FOREGROUND_WINDOW(g->DetectHiddenWindows, aTitle, aText, aExcludeTitle, aExcludeText) //else if (*aTitle || *aText || *aExcludeTitle || *aExcludeText) // target_window = WinExist(*g, aTitle, aText, aExcludeTitle, aExcludeText); //else // Use the "last found" window. // target_window = GetValidLastUsedWindow(*g); return WinExist(*g, aTitle, aText, aExcludeTitle, aExcludeText); } ResultType DetermineTargetHwnd(HWND &aWindow, ResultToken &aResultToken, ExprTokenType &aToken) { __int64 n = NULL; if (IObject *obj = TokenToObject(aToken)) { if (!GetObjectIntProperty(obj, _T("Hwnd"), n, aResultToken)) return FAIL; } else if (TokenIsPureNumeric(aToken) == PURE_INTEGER) n = TokenToInt64(aToken); else return CONDITION_FALSE; aWindow = (HWND)(UINT_PTR)n; // Callers expect the return value to be either a valid HWND or 0: if (!IsWindow(aWindow) && aWindow != HWND_BROADCAST) // HWND_BROADCAST is probably only meaningful for SendMessage, but is permitted for all, for reasons of code size vs. rarity. aWindow = 0; return OK; } FResult DetermineTargetHwnd(HWND &aWindow, bool &aDetermined, ExprTokenType &aToken) { // TODO: Factor out the use of ResultToken just for error-reporting. ResultToken result_token; // Only result_token.result is used. result_token.SetResult(OK); // Must be initialized. auto result = DetermineTargetHwnd(aWindow, result_token, aToken); aDetermined = result == OK; return result ? OK : result_token.Exited() ? FR_FAIL : FR_ABORTED; } FResult DetermineTargetWindow(HWND &aWindow, WINTITLE_PARAMETERS_DECL, bool aFindLastMatch) { TCHAR number_buf[MAX_NUMBER_SIZE]; LPCTSTR title = _T(""); if (aWinTitle) { ResultToken result_token; // TODO: Factor out the use of ResultToken just for error-reporting. result_token.SetResult(OK); // Must be initialized. auto result = DetermineTargetHwnd(aWindow, result_token, *aWinTitle); if (result != CONDITION_FALSE) { if (result == OK && !aWindow) return FError(ERR_NO_WINDOW, nullptr, ErrorPrototype::Target); return result ? OK : result_token.Exited() ? FR_FAIL : FR_ABORTED; } title = TokenToString(*aWinTitle, number_buf); } aWindow = WinExist(*g, title, aWinText.value_or_empty(), aExcludeTitle.value_or_empty() , aExcludeText.value_or_empty(), aFindLastMatch); if (aWindow) return OK; return FError(ERR_NO_WINDOW, title, ErrorPrototype::Target); } FResult DetermineTargetControl(HWND &aControl, HWND &aWindow, CONTROL_PARAMETERS_DECL, bool aThrowIfNotFound) { return DetermineTargetControl(aControl, aWindow, &CONTROL_PARAMETERS, aThrowIfNotFound); } FResult DetermineTargetControl(HWND &aControl, HWND &aWindow, CONTROL_PARAMETERS_DECL_OPT, bool aThrowIfNotFound) { aWindow = aControl = NULL; TCHAR number_buf[MAX_NUMBER_SIZE]; LPCTSTR control_spec = nullptr; if (aControlSpec) { bool hwnd_specified; auto fr = DetermineTargetHwnd(aWindow, hwnd_specified, *aControlSpec); if (fr != OK) return fr; if (hwnd_specified) { aControl = aWindow; if (!aControl) return FError(ERR_NO_WINDOW, nullptr, ErrorPrototype::Target); return OK; } // Since above didn't return, it wasn't a pure Integer or object {Hwnd}. control_spec = TokenToString(*aControlSpec, number_buf); } auto fr = DetermineTargetWindow(aWindow, WINTITLE_PARAMETERS); if (fr != OK) return fr; aControl = control_spec ? ControlExist(aWindow, control_spec) : aWindow; if (!aControl && aThrowIfNotFound) return FError(ERR_NO_CONTROL, control_spec, ErrorPrototype::Target); return OK; } ResultType DetermineTargetWindow(HWND &aWindow, ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount, int aNonWinParamCount) { if (aParamCount > 0) { auto result = DetermineTargetHwnd(aWindow, aResultToken, *aParam[0]); if (result != CONDITION_FALSE) { if (result == OK && !aWindow) return aResultToken.Error(ERR_NO_WINDOW, ErrorPrototype::Target); return result; } } TCHAR number_buf[4][MAX_NUMBER_SIZE]; LPTSTR param[4]; for (int i = 0, j = 0; i < 4; ++i, ++j) { if (i == 2) j += aNonWinParamCount; param[i] = j < aParamCount ? TokenToString(*aParam[j], number_buf[i]) : _T(""); } aWindow = Line::DetermineTargetWindow(param[0], param[1], param[2], param[3]); if (aWindow) return OK; return aResultToken.Error(ERR_NO_WINDOW, param[0], ErrorPrototype::Target); } BIF_DECL(BIF_WinExistActive) { bool hwnd_specified = false; HWND hwnd; if (!ParamIndexIsOmitted(0)) { switch (DetermineTargetHwnd(hwnd, aResultToken, *aParam[0])) { case FAIL: return; case OK: hwnd_specified = true; // DetermineTargetHwnd() already called IsWindow() to verify hwnd. // g->DetectHiddenWindows is intentionally ignored for these cases. if (_f_callee_id == FID_WinActive && GetForegroundWindow() != hwnd) hwnd = 0; if (hwnd) g->hWndLastUsed = hwnd; break; } } if (!hwnd_specified) // Do not call WinExist()/WinActive() even if the specified hwnd was 0. { TCHAR *param[4], param_buf[4][MAX_NUMBER_SIZE]; for (int j = 0; j < 4; ++j) // For each formal parameter, including optional ones. { if (ParamIndexIsOmitted(j)) param[j] = _T(""); else if (ParamIndexToObject(j)) _f_throw_param(j, _T("String")); else param[j] = ParamIndexToString(j, param_buf[j]); } hwnd = _f_callee_id == FID_WinExist ? WinExist(*g, param[0], param[1], param[2], param[3], false, true) : WinActive(*g, param[0], param[1], param[2], param[3], true); } _f_return_i((size_t)hwnd); } bif_impl void WinMinimizeAll() { PostMessage(FindWindow(_T("Shell_TrayWnd"), NULL), WM_COMMAND, 419, 0); DoWinDelay; } bif_impl void WinMinimizeAllUndo() { PostMessage(FindWindow(_T("Shell_TrayWnd"), NULL), WM_COMMAND, 416, 0); DoWinDelay; }
90,663
C++
.cpp
2,057
41.42246
272
0.735681
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,106
sound.cpp
AutoHotkey_AutoHotkey/source/lib/sound.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" // pre-compiled headers #include "script.h" #include "globaldata.h" #include "application.h" #include "qmath.h" #include <mmdeviceapi.h> #include <endpointvolume.h> #include <functiondiscoverykeys.h> #include "script_func_impl.h" #pragma region Sound support functions - Vista and later enum class SoundControlType { Volume, Mute, Name, IID }; LPWSTR SoundDeviceGetName(IMMDevice *aDev) { IPropertyStore *store; PROPVARIANT prop; if (SUCCEEDED(aDev->OpenPropertyStore(STGM_READ, &store))) { if (FAILED(store->GetValue(PKEY_Device_FriendlyName, &prop))) prop.pwszVal = nullptr; store->Release(); return prop.pwszVal; } return nullptr; } HRESULT SoundSetGet_GetDevice(LPTSTR aDeviceString, IMMDevice *&aDevice) { IMMDeviceEnumerator *deviceEnum; IMMDeviceCollection *devices; HRESULT hr; aDevice = NULL; hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&deviceEnum); if (SUCCEEDED(hr)) { if (!*aDeviceString) { // Get default playback device. hr = deviceEnum->GetDefaultAudioEndpoint(eRender, eConsole, &aDevice); } else { // Parse Name:Index, Name or Index. int target_index = 0; LPWSTR target_name = L""; size_t target_name_length = 0; LPTSTR delim = _tcsrchr(aDeviceString, ':'); if (delim) { target_index = ATOI(delim + 1) - 1; target_name = aDeviceString; target_name_length = delim - aDeviceString; } else if (ParseInteger(aDeviceString, target_index)) { --target_index; } else { target_name = aDeviceString; target_name_length = _tcslen(aDeviceString); } // Enumerate devices; include unplugged devices so that indices don't change when a device is plugged in. hr = deviceEnum->EnumAudioEndpoints(eAll, DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED, &devices); if (SUCCEEDED(hr)) { if (target_name_length) { IMMDevice *dev; for (UINT u = 0; SUCCEEDED(hr = devices->Item(u, &dev)); ++u) { if (LPWSTR dev_name = SoundDeviceGetName(dev)) { if (!_wcsnicmp(dev_name, target_name, target_name_length) && target_index-- == 0) { CoTaskMemFree(dev_name); aDevice = dev; break; } CoTaskMemFree(dev_name); } dev->Release(); } } else hr = devices->Item((UINT)target_index, &aDevice); devices->Release(); } } deviceEnum->Release(); } return hr; } struct SoundComponentSearch { // Parameters of search: GUID target_iid; int target_instance; SoundControlType target_control; TCHAR target_name[128]; // Arbitrary; probably larger than any real component name. // Internal use/results: IUnknown *control; LPWSTR name; // Valid only when target_control == SoundControlType::Name. int count; // Internal use: DataFlow data_flow; bool ignore_remaining_subunits; }; void SoundConvertComponent(LPTSTR aBuf, SoundComponentSearch &aSearch) { if (ParseInteger(aBuf, aSearch.target_instance)) { *aSearch.target_name = '\0'; } else { tcslcpy(aSearch.target_name, aBuf, _countof(aSearch.target_name)); LPTSTR colon_pos = _tcsrchr(aSearch.target_name, ':'); aSearch.target_instance = colon_pos ? ATOI(colon_pos + 1) : 1; if (colon_pos) *colon_pos = '\0'; } } bool SoundSetGet_FindComponent(IPart *aRoot, SoundComponentSearch &aSearch) { HRESULT hr; IPartsList *parts; IPart *part; UINT part_count; PartType part_type; LPWSTR part_name; bool check_name = *aSearch.target_name; if (aSearch.data_flow == In) hr = aRoot->EnumPartsIncoming(&parts); else hr = aRoot->EnumPartsOutgoing(&parts); if (FAILED(hr)) return NULL; if (FAILED(parts->GetCount(&part_count))) part_count = 0; for (UINT i = 0; i < part_count; ++i) { if (FAILED(parts->GetPart(i, &part))) continue; if (SUCCEEDED(part->GetPartType(&part_type))) { if (part_type == Connector) { if ( part_count == 1 // Ignore Connectors with no Subunits of their own. && (!check_name || (SUCCEEDED(part->GetName(&part_name)) && !_wcsicmp(part_name, aSearch.target_name))) ) { if (++aSearch.count == aSearch.target_instance) { switch (aSearch.target_control) { case SoundControlType::IID: // Permit retrieving the IPart or IConnector itself. Since there may be // multiple connected Subunits (and they can be enumerated or retrieved // via the Connector IPart), this is only done for the Connector. part->QueryInterface(aSearch.target_iid, (void **)&aSearch.control); break; case SoundControlType::Name: // check_name would typically be false in this case, since a value of true // would mean the caller already knows the component's name. part->GetName(&aSearch.name); break; } part->Release(); parts->Release(); return true; } } } else // Subunit { // Recursively find the Connector nodes linked to this part. if (SoundSetGet_FindComponent(part, aSearch)) { // A matching connector part has been found with this part as one of the nodes used // to reach it. Therefore, if this part supports the requested control interface, // it can in theory be used to control the component. An example path might be: // Output < Master Mute < Master Volume < Sum < Mute < Volume < CD Audio // Parts are considered from right to left, as we return from recursion. if (!aSearch.control && !aSearch.ignore_remaining_subunits) { // Query this part for the requested interface and let caller check the result. part->Activate(CLSCTX_ALL, aSearch.target_iid, (void **)&aSearch.control); // If this subunit has siblings, ignore any controls further up the line // as they're likely shared by other components (i.e. master controls). if (part_count > 1) aSearch.ignore_remaining_subunits = true; } part->Release(); parts->Release(); return true; } } } part->Release(); } parts->Release(); return false; } bool SoundSetGet_FindComponent(IMMDevice *aDevice, SoundComponentSearch &aSearch) { IDeviceTopology *topo; IConnector *conn, *conn_to; IPart *part; aSearch.count = 0; aSearch.control = nullptr; aSearch.name = nullptr; aSearch.ignore_remaining_subunits = false; if (SUCCEEDED(aDevice->Activate(__uuidof(IDeviceTopology), CLSCTX_ALL, NULL, (void**)&topo))) { if (SUCCEEDED(topo->GetConnector(0, &conn))) { if (SUCCEEDED(conn->GetDataFlow(&aSearch.data_flow)) && SUCCEEDED(conn->GetConnectedTo(&conn_to))) { if (SUCCEEDED(conn_to->QueryInterface(&part))) { // Search; the result is stored in the search struct. SoundSetGet_FindComponent(part, aSearch); part->Release(); } conn_to->Release(); } conn->Release(); } topo->Release(); } return aSearch.count == aSearch.target_instance; } #pragma endregion BIF_DECL(BIF_Sound) { LPTSTR aSetting = nullptr; SoundComponentSearch search; if (_f_callee_id >= FID_SoundSetVolume) { search.target_control = SoundControlType(_f_callee_id - FID_SoundSetVolume); aSetting = ParamIndexToString(0, _f_number_buf); if (!IsNumeric(aSetting, TRUE, FALSE, TRUE)) _f_throw_param(0); ++aParam; --aParamCount; } else search.target_control = SoundControlType(_f_callee_id); switch (search.target_control) { case SoundControlType::Volume: search.target_iid = __uuidof(IAudioVolumeLevel); break; case SoundControlType::Mute: search.target_iid = __uuidof(IAudioMute); break; case SoundControlType::IID: LPTSTR iid; iid = ParamIndexToString(0); if (*iid != '{' || FAILED(CLSIDFromString(iid, &search.target_iid))) _f_throw_param(0); ++aParam; --aParamCount; break; } _f_param_string_opt(aComponent, 0); _f_param_string_opt(aDevice, 1); #define SOUND_MODE_IS_SET aSetting // Boolean: i.e. if it's not NULL, the mode is "SET". _f_set_retval_p(_T(""), 0); // Set default. float setting_scalar; if (SOUND_MODE_IS_SET) { setting_scalar = (float)(ATOF(aSetting) / 100); if (setting_scalar < -1) setting_scalar = -1; else if (setting_scalar > 1) setting_scalar = 1; } // Does user want to adjust the current setting by a certain amount? bool adjust_current_setting = aSetting && (*aSetting == '-' || *aSetting == '+'); IMMDevice *device; HRESULT hr; hr = SoundSetGet_GetDevice(aDevice, device); if (FAILED(hr)) _f_throw(ERR_SOUND_DEVICE, ErrorPrototype::Target); LPCTSTR errorlevel = NULL; float result_float; BOOL result_bool; if (!*aComponent) // Component is Master (omitted). { if (search.target_control == SoundControlType::IID) { void *result_ptr = nullptr; if (FAILED(device->QueryInterface(search.target_iid, (void **)&result_ptr))) device->Activate(search.target_iid, CLSCTX_ALL, NULL, &result_ptr); // For consistency with ComObjQuery, the result is returned even on failure. aResultToken.SetValue((UINT_PTR)result_ptr); } else if (search.target_control == SoundControlType::Name) { if (auto name = SoundDeviceGetName(device)) { aResultToken.Return(name); CoTaskMemFree(name); } } else { // For Master/Speakers, use the IAudioEndpointVolume interface. Some devices support master // volume control, but do not actually have a volume subunit (so the other method would fail). IAudioEndpointVolume *aev; hr = device->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, (void**)&aev); if (SUCCEEDED(hr)) { if (search.target_control == SoundControlType::Volume) { if (!SOUND_MODE_IS_SET || adjust_current_setting) { hr = aev->GetMasterVolumeLevelScalar(&result_float); } if (SUCCEEDED(hr)) { if (SOUND_MODE_IS_SET) { if (adjust_current_setting) { setting_scalar += result_float; if (setting_scalar > 1) setting_scalar = 1; else if (setting_scalar < 0) setting_scalar = 0; } hr = aev->SetMasterVolumeLevelScalar(setting_scalar, NULL); } else { result_float *= 100.0; } } } else // Mute. { if (!SOUND_MODE_IS_SET || adjust_current_setting) { hr = aev->GetMute(&result_bool); } if (SOUND_MODE_IS_SET && SUCCEEDED(hr)) { hr = aev->SetMute(adjust_current_setting ? !result_bool : setting_scalar > 0, NULL); } } aev->Release(); } } } else { SoundConvertComponent(aComponent, search); if (!SoundSetGet_FindComponent(device, search)) { errorlevel = ERR_SOUND_COMPONENT; } else if (search.target_control == SoundControlType::IID) { aResultToken.SetValue((UINT_PTR)search.control); search.control = nullptr; // Don't release it. } else if (search.target_control == SoundControlType::Name) { aResultToken.Return(search.name); } else if (!search.control) { errorlevel = ERR_SOUND_CONTROLTYPE; } else if (search.target_control == SoundControlType::Volume) { IAudioVolumeLevel *avl = (IAudioVolumeLevel *)search.control; UINT channel_count = 0; if (FAILED(avl->GetChannelCount(&channel_count))) goto control_fail; float *level = (float *)_alloca(sizeof(float) * 3 * channel_count); float *level_min = level + channel_count; float *level_range = level_min + channel_count; float f, db, min_db, max_db, max_level = 0; for (UINT i = 0; i < channel_count; ++i) { if (FAILED(avl->GetLevel(i, &db)) || FAILED(avl->GetLevelRange(i, &min_db, &max_db, &f))) goto control_fail; // Convert dB to scalar. level_min[i] = (float)qmathExp10(min_db/20); level_range[i] = (float)qmathExp10(max_db/20) - level_min[i]; // Compensate for differing level ranges. (No effect if range is -96..0 dB.) level[i] = ((float)qmathExp10(db/20) - level_min[i]) / level_range[i]; // Windows reports the highest level as the overall volume. if (max_level < level[i]) max_level = level[i]; } if (SOUND_MODE_IS_SET) { if (adjust_current_setting) { setting_scalar += max_level; if (setting_scalar > 1) setting_scalar = 1; else if (setting_scalar < 0) setting_scalar = 0; } for (UINT i = 0; i < channel_count; ++i) { f = setting_scalar; if (max_level) f *= (level[i] / max_level); // Preserve balance. // Compensate for differing level ranges. f = level_min[i] + f * level_range[i]; // Convert scalar to dB. level[i] = 20 * (float)qmathLog10(f); } hr = avl->SetLevelAllChannels(level, channel_count, NULL); } else { result_float = max_level * 100; } } else if (search.target_control == SoundControlType::Mute) { IAudioMute *am = (IAudioMute *)search.control; if (!SOUND_MODE_IS_SET || adjust_current_setting) { hr = am->GetMute(&result_bool); } if (SOUND_MODE_IS_SET && SUCCEEDED(hr)) { hr = am->SetMute(adjust_current_setting ? !result_bool : setting_scalar > 0, NULL); } } control_fail: if (search.control) search.control->Release(); if (search.name) CoTaskMemFree(search.name); } device->Release(); if (errorlevel) _f_throw(errorlevel, ErrorPrototype::Target); if (FAILED(hr)) // This would be rare and unexpected. _f_throw_win32(hr); if (SOUND_MODE_IS_SET) return; switch (search.target_control) { case SoundControlType::Volume: aResultToken.Return(result_float); break; case SoundControlType::Mute: aResultToken.Return(result_bool); break; } } bif_impl FResult SoundPlay(StrArg aFilespec, optl<StrArg> aWait) { auto cp = omit_leading_whitespace(aFilespec); if (*cp == '*') { // ATOU() returns 0xFFFFFFFF for -1, which is relied upon to support the -1 sound. // Even if there are no enabled sound devices, MessageBeep() indicates success // (tested on Windows 10). It's hard to imagine how the script would handle a // failure anyway, so just omit error checking. MessageBeep(ATOU(cp + 1)); return OK; } // See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_play.asp // for some documentation mciSendString() and related. // MAX_PATH note: There's no chance this API supports long paths even on Windows 10. // Research indicates it limits paths to 127 chars (not even MAX_PATH), but since there's // no apparent benefit to reducing it, we'll keep this size to ensure backward-compatibility. // Note that using a relative path does not help, but using short (8.3) names does. TCHAR buf[MAX_PATH * 2]; // Allow room for filename and commands. mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" (so close it before trying to re-open with a new aFilespec). mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); sntprintf(buf, _countof(buf), _T("open \"%s\" alias ") SOUNDPLAY_ALIAS, aFilespec); if (mciSendString(buf, NULL, 0, NULL)) // Failure. return FR_E_FAILED; g_SoundWasPlayed = true; // For use by Script's destructor. if (mciSendString(_T("play ") SOUNDPLAY_ALIAS, NULL, 0, NULL)) // Failure. return FR_E_FAILED; // Otherwise, the sound is now playing. if ( !(aWait.has_value() && (aWait.value()[0] == '1' && !aWait.value()[1] || !_tcsicmp(aWait.value(), _T("Wait"))))) return OK; // Otherwise, caller wants us to wait until the file is done playing. To allow our app to remain // responsive during this time, use a loop that checks our message queue: // Older method: "mciSendString("play " SOUNDPLAY_ALIAS " wait", NULL, 0, NULL)" for (;;) { mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (!*buf) // Probably can't happen given the state we're in. break; if (!_tcscmp(buf, _T("stopped"))) // The sound is done playing. { mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); break; } // Sleep a little longer than normal because I'm not sure how much overhead // and CPU utilization the above incurs: MsgSleep(20); } return OK; } bif_impl void SoundBeep(optl<int> aFrequency, optl<int> aDuration) { // Negative values are checked to avoid interpreting them as a very long duration. int duration = aDuration.value_or(150); if (duration < 0) duration = 150; Beep(aFrequency.value_or(523), duration); }
16,993
C++
.cpp
532
28.120301
123
0.68513
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,107
file.cpp
AutoHotkey_AutoHotkey/source/lib/file.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "globaldata.h" #include "application.h" #include "TextIO.h" #include "script_func_impl.h" #include "abi.h" typedef BOOL (* FilePatternCallback)(LPCTSTR aFilename, WIN32_FIND_DATA &aFile, void *aCallbackData); struct FilePatternStruct { TCHAR path[T_MAX_PATH]; // Directory and naked filename or pattern. TCHAR pattern[MAX_PATH]; // Naked filename or pattern. size_t dir_length, pattern_length; FilePatternCallback aCallback; void *aCallbackData; FileLoopModeType aOperateOnFolders; bool aDoRecurse; int failure_count; }; static void FilePatternApply(FilePatternStruct &fps); static FResult FilePatternApply(LPCTSTR aFilePattern, FileLoopModeType aOperateOnFolders , bool aDoRecurse, FilePatternCallback aCallback, void *aCallbackData); static bool FileCreateDirRecursive(LPTSTR aDirSpec); // As of 2019-09-29, noinline reduces code size by over 20KB on VC++ 2019. // Prior to merging Util_CreateDir with this, it wasn't inlined. DECLSPEC_NOINLINE bool FileCreateDir(LPCTSTR aDirSpec) { if (!aDirSpec || !*aDirSpec) { SetLastError(ERROR_INVALID_PARAMETER); return false; } // Make a modifiable copy to be used by recursive calls (supports long paths). // Use GetFullPathName() instead of tmemcpy() or similar to normalize the path, // which has at least two benefits: // 1) Indirectly supports forward slash as a path separator. // 2) Relative components such as "x\y\.." would otherwise cause the function // to report failure due to the order of checks and CreateDirectory calls. TCHAR buf[T_MAX_PATH]; auto len = GetFullPathName(aDirSpec, _countof(buf), buf, nullptr); if (!len || len >= _countof(buf)) { SetLastError(ERROR_BUFFER_OVERFLOW); return false; } return FileCreateDirRecursive(buf); } static bool FileCreateDirRecursive(LPTSTR aDirSpec) { // The following check also serves to support UNC paths like "\\server\share\path" // by preventing the section below from recursing into "\\server\share" (or further) // if the share exists. DWORD attr = GetFileAttributes(aDirSpec); if (attr != 0xFFFFFFFF) // aDirSpec already exists. { SetLastError(ERROR_ALREADY_EXISTS); return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; // Indicate success if it already exists as a dir. } // If it has a backslash, make sure all its parent directories exist before we attempt // to create this directory: LPTSTR last_backslash = _tcsrchr(aDirSpec, '\\'); if (last_backslash > aDirSpec // v1.0.48.04: Changed "last_backslash" to "last_backslash > aDirSpec" so that an aDirSpec with a leading \ (but no other backslashes), such as \dir, is supported. && last_backslash[-1] != ':') // v1.1.31.00: Don't attempt FileCreateDir("C:") since that's equivalent to either "C:\" or the working directory (which already exists), or FileCreateDir("\\?\C:") since it always fails. { *last_backslash = '\0'; // Temporarily terminate for parent directory. auto exists = FileCreateDirRecursive(aDirSpec); // Recursively create all needed ancestor directories. *last_backslash = '\\'; // Undo temporary termination. if (!exists) return exists; } // The above has recursively created all parent directories of aDirSpec if needed. // Now we can create aDirSpec. return CreateDirectory(aDirSpec, NULL) || GetLastError() == ERROR_ALREADY_EXISTS; } static FResult ConvertFileOptions(LPCTSTR aOptions, UINT &codepage, bool &translate_crlf_to_lf, unsigned __int64 *pmax_bytes_to_load) { if (aOptions) for (LPCTSTR next, cp = aOptions; cp && *(cp = omit_leading_whitespace(cp)); cp = next) { if (*cp == '\n') { translate_crlf_to_lf = true; // Rather than treating "`nxxx" as invalid or ignoring "xxx", let the delimiter be // optional for `n. Treating "`nxxx" and "m1024`n" and "utf-8`n" as invalid would // require larger code, and would produce confusing error messages because the `n // isn't visible; e.g. "Invalid option. Specifically: utf-8" next = cp + 1; continue; } // \n is included below to allow "m1024`n" and "utf-8`n" (see above). next = StrChrAny(cp, _T(" \t\n")); switch (ctoupper(*cp)) { case 'M': if (pmax_bytes_to_load) // i.e. caller is FileRead. { *pmax_bytes_to_load = ATOU64(cp + 1); // Relies upon the fact that it ceases conversion upon reaching a space or tab. break; } // Otherwise, fall through to treat it as invalid: default: TCHAR name[12]; // Large enough for any valid encoding. if (next && (next - cp) < _countof(name)) { // Create a temporary null-terminated copy. wmemcpy(name, cp, next - cp); name[next - cp] = '\0'; cp = name; } if (!_tcsicmp(cp, _T("Raw"))) { codepage = -1; } else { codepage = Line::ConvertFileEncoding(cp); if (codepage == -1 || cisdigit(*cp)) // Require "cp" prefix in FileRead/FileAppend options. return FValueError(ERR_INVALID_OPTION, cp); } break; } // switch() } // for() return OK; } bif_impl FResult FileRead(StrArg aFilespec, optl<StrArg> aOptions, ResultToken &aResultToken) { g->LastError = 0; // Set default for successful early return or non-Win32 errors. if (!*aFilespec) return FR_E_ARG(0); // Seems more helpful than throwing OSError(3). // Set default options: bool translate_crlf_to_lf = false; unsigned __int64 max_bytes_to_load = ULLONG_MAX; // By default, fail if the file is too large. See comments near bytes_to_read below. UINT codepage = g->Encoding; auto fr = ConvertFileOptions(aOptions.value_or_null(), codepage, translate_crlf_to_lf, &max_bytes_to_load); if (fr != OK) return fr; // It already displayed the error. // It seems more flexible to allow other processes to read and write the file while we're reading it. // For example, this allows the file to be appended to during the read operation, which could be // desirable, especially it's a very large log file that would take a long time to read. // MSDN: "To enable other processes to share the object while your process has it open, use a combination // of one or more of [FILE_SHARE_READ, FILE_SHARE_WRITE]." HANDLE hfile = CreateFile(aFilespec, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING , FILE_FLAG_SEQUENTIAL_SCAN, NULL); // MSDN says that FILE_FLAG_SEQUENTIAL_SCAN will often improve performance if (hfile == INVALID_HANDLE_VALUE) // in cases like these (and it seems best even if max_bytes_to_load was specified). { g->LastError = GetLastError(); return FR_E_WIN32(g->LastError); } unsigned __int64 bytes_to_read = GetFileSize64(hfile); if (bytes_to_read == ULLONG_MAX) // GetFileSize64() failed. { g->LastError = GetLastError(); CloseHandle(hfile); return FR_E_WIN32(g->LastError); } // In addition to imposing the limit set by the *M option, the following check prevents an error // caused by 64 to 32-bit truncation -- that is, a file size of 0x100000001 would be truncated to // 0x1, allowing the command to complete even though it should fail. UPDATE: This check was never // sufficient since max_bytes_to_load could exceed MAXDWORD on x64 (prior to v1.1.16). It's now // checked separately below to try to match the documented behaviour (truncating the data only to // the caller-specified limit). if (bytes_to_read > max_bytes_to_load) // This is the limit set by the caller. bytes_to_read = max_bytes_to_load; // Fixed for v1.1.16: Show an error message if the file is larger than MAXDWORD, otherwise the // truncation issue described above could occur. Reading more than MAXDWORD could be supported // by calling ReadFile() in a loop, but it seems unlikely that a script will genuinely want to // do this AND actually be able to allocate a 4GB+ memory block (having 4GB of total free memory // is usually not sufficient, perhaps due to memory fragmentation). #ifdef _WIN64 if (bytes_to_read > MAXDWORD) #else // Reserve 2 bytes to avoid integer overflow below. Although any amount larger than 2GB is almost // guaranteed to fail at the malloc stage, that might change if we ever become large address aware. if (bytes_to_read > MAXDWORD - sizeof(wchar_t)) #endif { CloseHandle(hfile); return FR_E_OUTOFMEM; // Using this instead of "File too large." to reduce code size, since this condition is very rare (and malloc succeeding would be even rarer). } if (!bytes_to_read && codepage != -1) // In RAW mode, return a Buffer even if the file has zero bytes. { g->LastError = GetLastError(); CloseHandle(hfile); return OK; // Indicate success (a zero-length file results in an empty string). } LPBYTE output_buf = (LPBYTE)malloc(size_t(bytes_to_read + (bytes_to_read & 1) + sizeof(wchar_t))); if (!output_buf) { CloseHandle(hfile); return FR_E_OUTOFMEM; } DWORD bytes_actually_read; BOOL result = ReadFile(hfile, output_buf, (DWORD)bytes_to_read, &bytes_actually_read, NULL); CloseHandle(hfile); // Upon result==success, bytes_actually_read is not checked against bytes_to_read because it // shouldn't be different (result should have set to failure if there was a read error). // If it ever is different, a partial read is considered a success since ReadFile() told us // that nothing bad happened. if (result) { if (codepage != -1) // Text mode, not "RAW" mode. { codepage &= CP_AHKCP; // Convert to plain Win32 codepage (remove CP_AHKNOBOM, which has no meaning here). bool has_bom; if ( (has_bom = (bytes_actually_read >= 2 && output_buf[0] == 0xFF && output_buf[1] == 0xFE)) // UTF-16LE BOM || codepage == CP_UTF16 ) // Covers FileEncoding UTF-16 and FileEncoding UTF-16-RAW. { #ifndef UNICODE #error FileRead UTF-16 to ANSI string not implemented. #endif LPWSTR text = (LPWSTR)output_buf; DWORD length = bytes_actually_read / sizeof(WCHAR); if (has_bom) { // Move the data to eliminate the byte order mark. // Seems likely to perform better than allocating new memory and copying to it. --length; wmemmove(text, text + 1, length); } text[length] = '\0'; // Ensure text is terminated where indicated. Two bytes were reserved for this purpose. aResultToken.AcceptMem(text, length); output_buf = NULL; // Don't free it; caller will take over. } else { LPCSTR text = (LPCSTR)output_buf; DWORD length = bytes_actually_read; if (length >= 3 && output_buf[0] == 0xEF && output_buf[1] == 0xBB && output_buf[2] == 0xBF) // UTF-8 BOM { codepage = CP_UTF8; length -= 3; text += 3; } #ifndef UNICODE if (codepage == CP_ACP || codepage == GetACP()) { // Avoid any unnecessary conversion or copying by using our malloc'd buffer directly. // This should be worth doing since the string must otherwise be converted to UTF-16 and back. output_buf[bytes_actually_read] = 0; // Ensure text is terminated where indicated. aResultToken.AcceptMem((LPSTR)output_buf, bytes_actually_read); output_buf = NULL; // Don't free it; caller will take over. } else #error FileRead non-ACP-ANSI to ANSI string not fully implemented. #endif { int wlen = MultiByteToWideChar(codepage, 0, text, length, NULL, 0); if (wlen > 0) { if (!TokenSetResult(aResultToken, NULL, wlen)) { free(output_buf); return aResultToken.Exited() ? FR_FAIL : FR_ABORTED; } wlen = MultiByteToWideChar(codepage, 0, text, length, aResultToken.marker, wlen); aResultToken.symbol = SYM_STRING; aResultToken.marker[wlen] = 0; aResultToken.marker_length = wlen; if (!wlen) result = FALSE; } } } if (output_buf) // i.e. it wasn't "claimed" above. free(output_buf); if (translate_crlf_to_lf && aResultToken.marker_length) { // Since a larger string is being replaced with a smaller, there's a good chance the 2 GB // address limit will not be exceeded by StrReplace even if the file is close to the // 1 GB limit as described above: StrReplace(aResultToken.marker, _T("\r\n"), _T("\n"), SCS_SENSITIVE, UINT_MAX, -1, NULL, &aResultToken.marker_length); } } else // codepage == -1 ("RAW" mode) { // Return the buffer to our caller. aResultToken.Return(BufferObject::Create(output_buf, bytes_actually_read)); } } else { // ReadFile() failed. Since MSDN does not document what is in the buffer at this stage, or // whether bytes_to_read contains a valid value, it seems best to abort the entire operation // rather than try to return partial file contents. An exception will indicate the failure. free(output_buf); } if (!result) { g->LastError = GetLastError(); return FR_E_WIN32(g->LastError); } return OK; } bif_impl FResult FileAppend(ExprTokenType &aValue, optl<StrArg> aFilename, optl<StrArg> aOptions) { g->LastError = 0; // Set default for successful early return or non-Win32 errors. size_t aBuf_length; TCHAR aBuf_buf[MAX_NUMBER_SIZE]; LPCTSTR aBuf = TokenToString(aValue, aBuf_buf, &aBuf_length); IObject *aBuf_obj = TokenToObject(aValue); // Allow a Buffer-like object. if (aBuf_obj) { size_t ptr; FuncResult rt; GetBufferObjectPtr(rt, aBuf_obj, ptr, aBuf_length); ASSERT(rt.symbol == SYM_INTEGER && !rt.mem_to_free); if (rt.Exited()) return FR_FAIL; aBuf = (LPTSTR)ptr; } else aBuf_length *= sizeof(TCHAR); // Convert to byte count. // The below is avoided because want to allow "nothing" to be written to a file in case the // user is doing this to reset it's timestamp (or create an empty file). //if (!aBuf || !*aBuf) // return OK; // Use the read-file loop's current item if filename was explicitly left blank (i.e. not just // a reference to a variable that's blank): auto aCurrentReadFile = aFilename.has_value() ? nullptr : g->mLoopReadFile; auto aFilespec = aCurrentReadFile ? aCurrentReadFile->mWriteFileName : aFilename.value_or_empty(); if (!*aFilespec) // Nothing to write to. return FR_E_ARG(1); TextStream *ts = aCurrentReadFile ? aCurrentReadFile->mWriteFile : NULL; bool file_was_already_open = ts; #ifdef CONFIG_DEBUGGER if (*aFilespec == '*' && !aFilespec[1] && !aBuf_obj && g_Debugger.OutputStdOut(aBuf)) { // StdOut has been redirected to the debugger, and this "FileAppend" call has been // fully handled by the call above, so just return. return OK; } #endif UINT codepage; // Check if the file needs to be opened. This is done here rather than at the time the // loop first begins so that: // 1) Any options/encoding specified in the first FileAppend call can take effect. // 2) To avoid opening the file if the file-reading loop has zero iterations (i.e. it's // opened only upon first actual use to help performance and avoid changing the // file-modification time when no actual text will be appended). if (!file_was_already_open) { codepage = aBuf_obj ? -1 : g->Encoding; // Never default to BOM if a Buffer object was passed. bool translate_crlf_to_lf = false; auto fr = ConvertFileOptions(aOptions.value_or_null(), codepage, translate_crlf_to_lf, nullptr); if (fr != OK) return fr; DWORD flags = TextStream::APPEND | (translate_crlf_to_lf ? TextStream::EOL_CRLF : 0); ASSERT( (~CP_AHKNOBOM) == CP_AHKCP ); // codepage may include CP_AHKNOBOM, in which case below will not add BOM_UTFxx flag. if (codepage == CP_UTF8) flags |= TextStream::BOM_UTF8; else if (codepage == CP_UTF16) flags |= TextStream::BOM_UTF16; else if (codepage != -1) codepage &= CP_AHKCP; // Open the output file (if one was specified). Unlike the input file, this is not // a critical error if it fails. We want it to be non-critical so that FileAppend // commands in the body of the loop will throw to indicate the problem: ts = new TextFile; // ts was already verified NULL via !file_was_already_open. if ( !ts->Open(aFilespec, flags, codepage) ) { g->LastError = GetLastError(); delete ts; // Must be deleted explicitly! return FR_E_WIN32(g->LastError); } if (aCurrentReadFile) aCurrentReadFile->mWriteFile = ts; } else codepage = ts->GetCodePage(); // Write to the file: DWORD result = 1; if (aBuf_length) { if (codepage == -1 || aBuf_obj) // "RAW" mode. result = ts->Write((LPCVOID)aBuf, (DWORD)aBuf_length); else result = ts->Write(aBuf, DWORD(aBuf_length / sizeof(TCHAR))); g->LastError = GetLastError(); } //else: aBuf is empty; we've already succeeded in creating the file and have nothing further to do. if (!aCurrentReadFile) delete ts; // else it's the caller's responsibility, or it's caller's, to close it. return result == 0 ? FR_E_WIN32(g->LastError) : OK; } BOOL FileDeleteCallback(LPCTSTR aFilename, WIN32_FIND_DATA &aFile, void *aCallbackData) { return DeleteFile(aFilename); } bif_impl FResult FileDelete(StrArg aFilePattern) { if (!*aFilePattern) return FR_E_ARG(0); // The no-wildcard case could be handled via FilePatternApply(), but handling it this // way ensures deleting a non-existent path without wildcards is considered a failure: if (!StrChrAny(aFilePattern, _T("?*"))) // No wildcards; just a plain path/filename. { if (!DeleteFile(aFilePattern)) { g->LastError = GetLastError(); return FR_E_WIN32(g->LastError); } } // Otherwise aFilePattern contains wildcards, so we'll search for all matches and delete them. return FilePatternApply(aFilePattern, FILE_LOOP_FILES_ONLY, false, FileDeleteCallback, NULL); } static bool FileInstallExtract(LPCTSTR aSource, LPCTSTR aDest, bool aOverwrite) { // Open the file first since it's the most likely to fail: HANDLE hfile = CreateFile(aDest, GENERIC_WRITE, 0, NULL, aOverwrite ? CREATE_ALWAYS : CREATE_NEW, 0, NULL); if (hfile == INVALID_HANDLE_VALUE) return false; // Create a temporary copy of aSource to ensure it is the correct case (upper-case). // Ahk2Exe converts it to upper-case before adding the resource. My testing showed that // using lower or mixed case in some instances prevented the resource from being found. // Since file paths are case-insensitive, it certainly doesn't seem harmful to do this: TCHAR source[T_MAX_PATH]; size_t source_length = _tcslen(aSource); if (source_length >= _countof(source)) // Probably can't happen; for simplicity, truncate it. source_length = _countof(source) - 1; tmemcpy(source, aSource, source_length + 1); _tcsupr(source); // Find and load the resource. HRSRC res; HGLOBAL res_load; LPVOID res_lock; bool success = false; if ( (res = FindResource(NULL, source, RT_RCDATA)) && (res_load = LoadResource(NULL, res)) && (res_lock = LockResource(res_load)) ) { DWORD num_bytes_written; // Write the resource data to file. success = WriteFile(hfile, res_lock, SizeofResource(NULL, res), &num_bytes_written, NULL); } CloseHandle(hfile); return success; } #ifndef AUTOHOTKEYSC static bool FileInstallCopy(LPCTSTR aSource, LPCTSTR aDest, bool aOverwrite) { // v1.0.35.11: Must search in A_ScriptDir by default because that's where ahk2exe will search by default. // The old behavior was to search in A_WorkingDir, which seems pointless because ahk2exe would never // be able to use that value if the script changes it while running. TCHAR source_path[T_MAX_PATH], dest_path[T_MAX_PATH]; GetFullPathName(aDest, _countof(dest_path), dest_path, NULL); // Avoid attempting the copy if both paths are the same (since it would fail with ERROR_SHARING_VIOLATION), // but resolve both to full paths in case mFileDir != g_WorkingDir. There is a more thorough way to detect // when two *different* paths refer to the same file, but it doesn't work with different network shares, and // the additional complexity wouldn't be warranted. Also, the limitations of this method are clearer. SetCurrentDirectory(g_script.mFileDir); GetFullPathName(aSource, _countof(source_path), source_path, NULL); SetCurrentDirectory(g_WorkingDir); // Restore to proper value. if (!ostrcmpi(source_path, dest_path) // Full paths are equal. && !(GetFileAttributes(source_path) & FILE_ATTRIBUTE_DIRECTORY)) // Source file exists and is not a directory (otherwise, an error should be thrown). return true; return CopyFile(source_path, dest_path, !aOverwrite); } #endif bif_impl FResult FileInstall(StrArg aSource, StrArg aDest, optl<int> aFlag) { bool success; bool allow_overwrite = (aFlag.has_value() && *aFlag == 1); #ifndef AUTOHOTKEYSC if (g_script.mKind != Script::ScriptKindResource) success = FileInstallCopy(aSource, aDest, allow_overwrite); else #endif success = FileInstallExtract(aSource, aDest, allow_overwrite); return success ? OK : FR_E_FAILED; } static FResult FileCopyOrMove(LPCTSTR aSource, LPCTSTR aDest, optl<int> aFlag, bool aMove) { if (!*aSource) // v2: Empty Source is likely to be a mistake. return FR_E_ARG(0); if (!*aDest) // Fix for v1.1.34.03: Previous behaviour was a Critical Error. return FR_E_ARG(1); int error_count = Line::Util_CopyFile(aSource, aDest, aFlag.has_value() && *aFlag == 1, aMove , g->LastError); return error_count ? FR_THROW_INT(error_count) : OK; } bif_impl FResult FileCopy(StrArg aSource, StrArg aDest, optl<int> aFlag) { return FileCopyOrMove(aSource, aDest, aFlag, false); } bif_impl FResult FileMove(StrArg aSource, StrArg aDest, optl<int> aFlag) { return FileCopyOrMove(aSource, aDest, aFlag, true); } bif_impl FResult FileGetAttrib(optl<StrArg> aPath, StrRet &aRetVal) { g->LastError = 0; // Set default for successful return or non-Win32 errors. auto path = aPath.has_value() ? aPath.value() : g->mLoopFile ? g->mLoopFile->file_path : _T(""); if (!*path) return FR_E_ARG(0); DWORD attr = GetFileAttributes(path); if (attr == 0xFFFFFFFF) // Failure, probably because file doesn't exist. { g->LastError = GetLastError(); return FR_E_WIN32(g->LastError); } aRetVal.SetTemp(FileAttribToStr(aRetVal.CallerBuf(), attr)); return OK; } BOOL FileSetAttribCallback(LPCTSTR aFilename, WIN32_FIND_DATA &aFile, void *aCallbackData); struct FileSetAttribData { DWORD and_mask, xor_mask; }; bif_impl FResult FileSetAttrib(StrArg aAttributes, optl<StrArg> aFilePattern, optl<StrArg> aMode) { auto path = aFilePattern.has_value() ? aFilePattern.value() : g->mLoopFile ? g->mLoopFile->file_path : _T(""); if (!*path) return FR_E_ARG(0); FileLoopModeType mode = Line::ConvertLoopMode(aMode.value_or_null()); if (mode == FILE_LOOP_INVALID) return FR_E_ARG(2); FileLoopModeType aOperateOnFolders = mode & ~FILE_LOOP_RECURSE; bool aDoRecurse = mode & FILE_LOOP_RECURSE; // Convert the attribute string to three bit-masks: add, remove and toggle. FileSetAttribData attrib; DWORD mask; int op = 0; attrib.and_mask = 0xFFFFFFFF; // Set default: keep all bits. attrib.xor_mask = 0; // Set default: affect none. for (auto cp = aAttributes; *cp; ++cp) { switch (ctoupper(*cp)) { case '+': case '-': case '^': op = *cp; case ' ': case '\t': continue; default: return FR_E_ARG(0); // Note that D (directory) and C (compressed) are currently not supported: case 'R': mask = FILE_ATTRIBUTE_READONLY; break; case 'A': mask = FILE_ATTRIBUTE_ARCHIVE; break; case 'S': mask = FILE_ATTRIBUTE_SYSTEM; break; case 'H': mask = FILE_ATTRIBUTE_HIDDEN; break; // N: Docs say it's valid only when used alone. But let the API handle it if this is not so. case 'N': mask = FILE_ATTRIBUTE_NORMAL; break; case 'O': mask = FILE_ATTRIBUTE_OFFLINE; break; case 'T': mask = FILE_ATTRIBUTE_TEMPORARY; break; } switch (op) { case '+': attrib.and_mask &= ~mask; // Reset bit to 0. attrib.xor_mask |= mask; // Set bit to 1. break; case '-': attrib.and_mask &= ~mask; // Reset bit to 0. attrib.xor_mask &= ~mask; // Override any prior + or ^. break; case '^': attrib.xor_mask ^= mask; // Toggle bit. ^= vs |= to invert any prior + or ^. // Leave and_mask as is, so any prior + or - will be inverted. break; default: // No +/-/^ specified, so overwrite attributes (equal and opposite to FileGetAttrib). attrib.and_mask = 0; // Reset all bits to 0. attrib.xor_mask |= mask; // Set bit to 1. |= to accumulate if multiple attributes are present. break; } } return FilePatternApply(path, aOperateOnFolders, aDoRecurse, FileSetAttribCallback, &attrib); } BOOL FileSetAttribCallback(LPCTSTR file_path, WIN32_FIND_DATA &current_file, void *aCallbackData) { FileSetAttribData &attrib = *(FileSetAttribData *)aCallbackData; DWORD file_attrib = ((current_file.dwFileAttributes & attrib.and_mask) ^ attrib.xor_mask); if (!SetFileAttributes(file_path, file_attrib)) { g->LastError = GetLastError(); return FALSE; } return TRUE; } static FResult FilePatternApply(LPCTSTR aFilePattern, FileLoopModeType aOperateOnFolders , bool aDoRecurse, FilePatternCallback aCallback, void *aCallbackData) { if (!*aFilePattern) { g->LastError = ERROR_INVALID_PARAMETER; return FR_E_WIN32(g->LastError); } if (aOperateOnFolders == FILE_LOOP_INVALID) // In case runtime dereference of a var was an invalid value. aOperateOnFolders = FILE_LOOP_FILES_ONLY; // Set default. g->LastError = 0; // Set default. Overridden only when a failure occurs. FilePatternStruct fps; auto last_backslash = _tcsrchr(aFilePattern, '\\'); if (last_backslash) fps.dir_length = last_backslash - aFilePattern + 1; // Include the slash. else // Use current working directory, e.g. if user specified only *.* fps.dir_length = 0; fps.pattern_length = _tcslen(aFilePattern + fps.dir_length); // Testing shows that the ANSI version of FindFirstFile() will not accept a path+pattern longer // than 259, even if the pattern would match files whose names are short enough to be legal. if (fps.dir_length + fps.pattern_length >= _countof(fps.path) || fps.pattern_length >= _countof(fps.pattern)) { g->LastError = ERROR_BUFFER_OVERFLOW; return FR_E_WIN32(g->LastError); } // Make copies in case of overwrite of deref buf during LONG_OPERATION/MsgSleep, // and to allow modification: _tcscpy(fps.path, aFilePattern); // Include the pattern initially. _tcscpy(fps.pattern, aFilePattern + fps.dir_length); // Just the naked filename or pattern, for use with aDoRecurse. if (!StrChrAny(fps.pattern, _T("?*"))) // Since no wildcards, always operate on this single item even if it's a folder. aOperateOnFolders = FILE_LOOP_FILES_AND_FOLDERS; // Passing the parameters this way reduces code size: fps.aCallback = aCallback; fps.aCallbackData = aCallbackData; fps.aDoRecurse = aDoRecurse; fps.aOperateOnFolders = aOperateOnFolders; fps.failure_count = 0; FilePatternApply(fps); return fps.failure_count ? FR_THROW_INT(fps.failure_count) : OK; } static void FilePatternApply(FilePatternStruct &fps) { size_t dir_length = fps.dir_length; // Length of this directory (saved before recursion). LPTSTR append_pos = fps.path + dir_length; // This is where the changing part gets appended. size_t space_remaining = _countof(fps.path) - dir_length - 1; // Space left in file_path for the changing part. LONG_OPERATION_INIT int failure_count = 0; WIN32_FIND_DATA current_file; HANDLE file_search = FindFirstFile(fps.path, &current_file); if (file_search != INVALID_HANDLE_VALUE) { do { // Since other script threads can interrupt during LONG_OPERATION_UPDATE, it's important that // this command not refer to sArgDeref[] and sArgVar[] anytime after an interruption becomes // possible. This is because an interrupting thread usually changes the values to something // inappropriate for this thread. LONG_OPERATION_UPDATE if (current_file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (current_file.cFileName[0] == '.' && (!current_file.cFileName[1] // Relies on short-circuit boolean order. || current_file.cFileName[1] == '.' && !current_file.cFileName[2]) // // Regardless of whether this folder will be recursed into, this folder // will not be affected when the mode is files-only: || fps.aOperateOnFolders == FILE_LOOP_FILES_ONLY) continue; // Never operate upon or recurse into these. } else // It's a file, not a folder. if (fps.aOperateOnFolders == FILE_LOOP_FOLDERS_ONLY) continue; if (_tcslen(current_file.cFileName) > space_remaining) { // v1.0.45.03: Don't even try to operate upon truncated filenames in case they accidentally // match the name of a real/existing file. g->LastError = ERROR_BUFFER_OVERFLOW; ++failure_count; continue; } // Otherwise, make file_path be the filespec of the file to operate upon: _tcscpy(append_pos, current_file.cFileName); // Above has ensured this won't overflow. // // This is the part that actually does something to the file: if (!fps.aCallback(fps.path, current_file, fps.aCallbackData)) ++failure_count; // } while (FindNextFile(file_search, &current_file)); FindClose(file_search); } // if (file_search != INVALID_HANDLE_VALUE) if (fps.aDoRecurse && space_remaining > 1) // The space_remaining check ensures there's enough room to append "*", though if false, that would imply lfs.pattern is empty. { _tcscpy(append_pos, _T("*")); // Above has ensured this won't overflow. file_search = FindFirstFile(fps.path, &current_file); if (file_search != INVALID_HANDLE_VALUE) { do { LONG_OPERATION_UPDATE if (!(current_file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || current_file.cFileName[0] == '.' && (!current_file.cFileName[1] // Relies on short-circuit boolean order. || current_file.cFileName[1] == '.' && !current_file.cFileName[2])) // continue; size_t filename_length = _tcslen(current_file.cFileName); // v1.0.45.03: Skip over folders whose paths are too long to be supported by FindFirst. if (fps.pattern_length + filename_length >= space_remaining) // >= vs. > to reserve 1 for the backslash to be added between cFileName and naked_filename_or_pattern. continue; // Never recurse into these. // This will build the string CurrentDir+SubDir+FilePatternOrName. // If FilePatternOrName doesn't contain a wildcard, the recursion // process will attempt to operate on the originally-specified // single filename or folder name if it occurs anywhere else in the // tree, e.g. recursing C:\Temp\temp.txt would affect all occurrences // of temp.txt both in C:\Temp and any subdirectories it might contain: _stprintf(append_pos, _T("%s\\%s") // Above has ensured this won't overflow. , current_file.cFileName, fps.pattern); fps.dir_length = dir_length + filename_length + 1; // Include the slash. // // Apply the callback to files in this subdirectory: FilePatternApply(fps); // } while (FindNextFile(file_search, &current_file)); FindClose(file_search); } // if (file_search != INVALID_HANDLE_VALUE) } // if (aDoRecurse) fps.failure_count += failure_count; // Update failure count (produces smaller code than doing ++fps.failure_count directly). } bif_impl FResult FileGetTime(optl<StrArg> aPath, optl<StrArg> aWhichTime, StrRet &aRetVal) { g->LastError = 0; // Set default for successful return or non-Win32 errors. auto path = aPath.has_value() ? aPath.value() : g->mLoopFile ? g->mLoopFile->file_path : _T(""); if (!*path) return FR_E_ARG(0); FILETIME *which_time; WIN32_FIND_DATA found_file; switch (aWhichTime.has_nonempty_value() ? ctoupper(*aWhichTime.value()) : 'M') { case 'C': which_time = &found_file.ftCreationTime; break; case 'A': which_time = &found_file.ftLastAccessTime; break; case 'M': which_time = &found_file.ftLastWriteTime; break; default: return FR_E_ARG(1); } // Don't use CreateFile() & GetFileTime() since they will fail to work on a file that's in use. // Research indicates that this method has no disadvantages compared to the other method. HANDLE file_search = FindFirstFile(path, &found_file); if (file_search == INVALID_HANDLE_VALUE) { g->LastError = GetLastError(); return FR_E_WIN32(g->LastError); } FindClose(file_search); FILETIME local_file_time; FileTimeToLocalFileTime(which_time, &local_file_time); aRetVal.SetTemp(FileTimeToYYYYMMDD(aRetVal.CallerBuf(), local_file_time)); return OK; } BOOL FileSetTimeCallback(LPCTSTR aFilename, WIN32_FIND_DATA &aFile, void *aCallbackData); struct FileSetTimeData { FILETIME Time; TCHAR WhichTime; }; bif_impl FResult FileSetTime(optl<StrArg> aYYYYMMDD, optl<StrArg> aFilePattern, optl<StrArg> aWhichTime, optl<StrArg> aMode) { auto path = aFilePattern.has_value() ? aFilePattern.value() : g->mLoopFile ? g->mLoopFile->file_path : _T(""); if (!*path) return FR_E_ARG(1); FileLoopModeType mode = Line::ConvertLoopMode(aMode.value_or_null()); if (mode == FILE_LOOP_INVALID) return FR_E_ARG(3); FileLoopModeType aOperateOnFolders = mode & ~FILE_LOOP_RECURSE; bool aDoRecurse = mode & FILE_LOOP_RECURSE; FileSetTimeData callbackData; switch (callbackData.WhichTime = aWhichTime.has_value() ? ctoupper(*aWhichTime.value()) : 0) { case 'M': case 'C': case 'A': case '\0': break; default: return FR_E_ARG(2); } FILETIME ft; if (aYYYYMMDD.has_nonempty_value()) { if ( !YYYYMMDDToFileTime(aYYYYMMDD.value(), ft) // Convert the arg into the time struct as local (non-UTC) time. || !LocalFileTimeToFileTime(&ft, &callbackData.Time) ) // Convert from local to UTC. { // Invalid parameters are the only likely cause of this condition. return FR_E_ARG(0); } } else // User wants to use the current time (i.e. now) as the new timestamp. GetSystemTimeAsFileTime(&callbackData.Time); return FilePatternApply(path, aOperateOnFolders, aDoRecurse, FileSetTimeCallback, &callbackData); } BOOL FileSetTimeCallback(LPCTSTR aFilename, WIN32_FIND_DATA &aFile, void *aCallbackData) { HANDLE hFile; // Open existing file. // FILE_FLAG_NO_BUFFERING might improve performance because all we're doing is // changing one of the file's attributes. FILE_FLAG_BACKUP_SEMANTICS must be // used, otherwise changing the time of a directory under NT and beyond will // not succeed. Win95 (not sure about Win98/Me) does not support this, but it // should be harmless to specify it even if the OS is Win95: hFile = CreateFile(aFilename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE , (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING , FILE_FLAG_NO_BUFFERING | FILE_FLAG_BACKUP_SEMANTICS, NULL); if (hFile == INVALID_HANDLE_VALUE) { g->LastError = GetLastError(); return FALSE; } BOOL success; FileSetTimeData &a = *(FileSetTimeData *)aCallbackData; switch (a.WhichTime) // ctoupper() was already applied by FileSetTime(). { case 'C': // File's creation time. success = SetFileTime(hFile, &a.Time, NULL, NULL); break; case 'A': // File's last access time. success = SetFileTime(hFile, NULL, &a.Time, NULL); break; default: // 'M', unspecified, or some other value. Use the file's modification time. success = SetFileTime(hFile, NULL, NULL, &a.Time); } if (!success) g->LastError = GetLastError(); CloseHandle(hFile); return success; } bif_impl FResult FileGetSize(optl<StrArg> aPath, optl<StrArg> aUnits, __int64 &aRetVal) { g->LastError = 0; // Set default for successful return or non-Win32 errors. auto path = aPath.has_value() ? aPath.value() : g->mLoopFile ? g->mLoopFile->file_path : _T(""); if (!*path) return FR_E_ARG(0); BOOL got_file_size = false; UINT64 size; // UINT64 vs. __int64 produces slightly smaller code due to how /= is compiled. // Try CreateFile() and GetFileSizeEx() first, since they can be more accurate. // See "Why is the file size reported incorrectly for files that are still being written to?" // http://blogs.msdn.com/b/oldnewthing/archive/2011/12/26/10251026.aspx HANDLE hfile = CreateFile(path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE , NULL, OPEN_EXISTING, 0, NULL); if (hfile != INVALID_HANDLE_VALUE) { got_file_size = GetFileSizeEx(hfile, (PLARGE_INTEGER)&size); CloseHandle(hfile); } if (!got_file_size) { WIN32_FIND_DATA found_file; HANDLE file_search = FindFirstFile(path, &found_file); if (file_search == INVALID_HANDLE_VALUE) { g->LastError = GetLastError(); return FR_E_WIN32(g->LastError); } FindClose(file_search); size = ((UINT64)found_file.nFileSizeHigh << 32) | found_file.nFileSizeLow; } switch (aUnits.has_nonempty_value() ? ctoupper(*aUnits.value()) : 'B') { case 'K': size /= 1024; break; // KB case 'M': size /= (1024 * 1024); break; // MB case 'B': break; // Bytes default: return FR_E_ARG(1); } g->LastError = 0; aRetVal = (__int64)size; return OK; } static void FileOrDirExist(LPCTSTR aFilePattern, StrRet &aRetVal, DWORD aRequiredAttr) { LPTSTR buf = aRetVal.CallerBuf(); aRetVal.SetTemp(buf); DWORD attr; if (DoesFilePatternExist(aFilePattern, &attr, aRequiredAttr)) { // Yield the attributes of the first matching file. If not match, yield an empty string. // This relies upon the fact that a file's attributes are never legitimately zero, which // seems true but in case it ever isn't, this forces a non-empty string be used. // UPDATE for v1.0.44.03: Someone reported that an existing file (created by NTbackup.exe) can // apparently have undefined/invalid attributes (i.e. attributes that have no matching letter in // "RASHNDOCT"). Although this is unconfirmed, it's easy to handle that possibility here by // checking for a blank string. This allows FileExist() to report boolean TRUE rather than FALSE // for such "mystery files": FileAttribToStr(buf, attr); if (!*buf) // See above. { // The attributes might be all 0, but more likely the file has some of the newer attributes // such as FILE_ATTRIBUTE_ENCRYPTED (or has undefined attributes). So rather than storing attr as // a hex number (which could be zero and thus defeat FileExist's ability to detect the file), it // seems better to store some arbitrary letter (other than those in "RASHNDOCT") so that FileExist's // return value is seen as boolean "true". buf[0] = 'X'; buf[1] = '\0'; } } else // Empty string is the indicator of "not found". *buf = '\0'; } bif_impl void FileExist(StrArg aFilePattern, StrRet &aRetVal) { return FileOrDirExist(aFilePattern, aRetVal, 0); } bif_impl void DirExist(StrArg aFilePattern, StrRet &aRetVal) { return FileOrDirExist(aFilePattern, aRetVal, FILE_ATTRIBUTE_DIRECTORY); } bif_impl FResult DirCopy(StrArg aSource, StrArg aDest, optl<int> aOverwrite) { if (!*aSource) return FR_E_ARG(0); if (!*aDest) return FR_E_ARG(1); return Line::Util_CopyDir(aSource, aDest, aOverwrite.value_or(FALSE), false) ? OK : FR_E_FAILED; } bif_impl FResult DirMove(StrArg aSource, StrArg aDest, optl<StrArg> aFlag) { if (!*aSource) return FR_E_ARG(0); if (!*aDest) return FR_E_ARG(1); int flag = 0; auto flag_str = aFlag.value_or_null(); if (flag_str && *flag_str) { // The documentation says "Specify one of the following single characters", // so specifically allow only the values "0", "1", "2", "R" and "r". if (flag_str[1]) return FR_E_ARG(2); if (*flag_str == 'R' || *flag_str == 'r') { // Perform a simple rename instead, which prevents the operation from being only partially // complete if the source directory is in use (due to being a working dir for a currently // running process, or containing a file that is being written to). In other words, // the operation will be "all or none": return MoveFile(aSource, aDest) ? OK : FR_E_WIN32; } if (*flag_str < '0' || *flag_str > '2') return FR_E_ARG(2); flag = *flag_str - '0'; } if (!Line::Util_CopyDir(aSource, aDest, flag, true)) return FR_E_FAILED; return OK; } bif_impl FResult DirCreate(StrArg aPath) { SetLastError(0); auto result = FileCreateDir(aPath); g->LastError = GetLastError(); return result ? OK : FR_E_WIN32; } bif_impl FResult DirDelete(StrArg aPath, optl<BOOL> aRecurse) { return Line::Util_RemoveDir(aPath, aRecurse.value_or(FALSE)) ? OK : FR_E_FAILED; }
40,610
C++
.cpp
946
40.075053
219
0.72137
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,108
env.cpp
AutoHotkey_AutoHotkey/source/lib/env.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "window.h" // for MonitorInfoPackage #include "script_func_impl.h" #include "abi.h" #pragma region Environment Variables bif_impl FResult EnvGet(StrArg aEnvVarName, StrRet &aRetVal) { // According to MSDN, 32767 is exactly large enough to handle the largest variable plus its zero terminator. // Update: In practice, at least on Windows 7, the limit only applies to the ANSI functions. TCHAR stack_buf[32767]; // GetEnvironmentVariable() could be called twice, the first time to get the actual size. But calling it once // and then copying the string performs better, except in the rare cases where the initial buffer is too small. DWORD length = GetEnvironmentVariable(aEnvVarName, stack_buf, _countof(stack_buf)); //_tcscpy(stack_buf, _T("Hello, world")); //DWORD length = (DWORD)_tcslen(_T("Hello, world")); if (!length) // Generally empty or undefined. { //aRetVal->SetEmpty(); return OK; } LPTSTR buf = aRetVal.Alloc(length); if (!buf) return FR_E_OUTOFMEM; if (length >= _countof(stack_buf)) { // In this case, length indicates the required buffer size, and the contents of the buffer are undefined. // Since our buffer is 32767 characters, the var apparently exceeds the documented limit, as can happen // if the var was set with the Unicode API. auto size = length; length = GetEnvironmentVariable(aEnvVarName, buf, size); if (!length || length >= size) // Check against size in case the value could have changed since the first call. { *buf = '\0'; // Ensure var is null-terminated. length = 0; } } else tmemcpy(buf, stack_buf, (size_t)length + 1); //tmemcpy(buf, _T("Hello, world"), (size_t)length + 1); aRetVal.SetLength(length); return OK; } bif_impl FResult EnvSet(StrArg aName, optl<StrArg> aValue) { // MSDN: "If [the 2nd] parameter is NULL, the variable is deleted from the current process's environment." // No checking is currently done to ensure that aValue isn't longer than 32K, since testing shows that // larger values are supported by the Unicode functions, at least in some OSes. If not supported, // SetEnvironmentVariable() should return 0 (fail) anyway. // Note: It seems that env variable names can contain spaces and other symbols, so it's best not to // validate aEnvVarName the same way we validate script variables (i.e. just let the return value // determine whether there's an error). return SetEnvironmentVariable(aName, aValue.value_or_null()) ? OK : FR_E_WIN32; } #pragma endregion bif_impl int SysGet(int aIndex) { return GetSystemMetrics(aIndex); } #pragma region MonitorGet and related static BOOL CALLBACK EnumMonitorProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM lParam) { MonitorInfoPackage &mip = *(MonitorInfoPackage *)lParam; // For performance and convenience. if (mip.monitor_number_to_find == COUNT_ALL_MONITORS) { ++mip.count; return TRUE; // Enumerate all monitors so that they can be counted. } if (!GetMonitorInfo(hMonitor, &mip.monitor_info_ex)) // Failed. Probably very rare. return FALSE; // Due to the complexity of needing to stop at the correct monitor number, do not continue. // In the unlikely event that the above fails when the caller wanted us to find the primary // monitor, the caller will think the primary is the previously found monitor (if any). // This is just documented here as a known limitation since this combination of circumstances // is probably impossible. ++mip.count; // So that caller can detect failure, increment only now that failure conditions have been checked. if (mip.monitor_number_to_find) // Caller gave a specific monitor number, so don't search for the primary monitor. { if (mip.count == mip.monitor_number_to_find) // Since the desired monitor has been found, must not continue. return FALSE; } else // Caller wants the primary monitor found. // MSDN docs are unclear that MONITORINFOF_PRIMARY is a bitwise value, but the name "dwFlags" implies so: if (mip.monitor_info_ex.dwFlags & MONITORINFOF_PRIMARY) return FALSE; // Primary has been found and "count" contains its number. Must not continue the enumeration. // Above assumes that it is impossible to not have a primary monitor in a system that has at least // one monitor. MSDN certainly implies this through multiple references to the primary monitor. // Otherwise, continue the enumeration: return TRUE; } static void EnumForMonitorGet(MonitorInfoPackage &mip, int aIndex) { mip.monitor_info_ex.cbSize = sizeof(MONITORINFOEX); mip.monitor_number_to_find = aIndex; // If 0, it will default to the primary monitor. EnumDisplayMonitors(NULL, NULL, EnumMonitorProc, (LPARAM)&mip); } // For the next few BIFs, I'm not sure if it is possible to have zero monitors. Obviously it's possible // to not have a monitor turned on or not connected at all. But it seems likely that these various API // functions will provide a "default monitor" in the absence of a physical monitor connected to the // system. To be safe, all of the below will assume that zero is possible, at least on some OSes or // under some conditions. bif_impl int MonitorGetCount() { // Don't use GetSystemMetrics(SM_CMONITORS) because of this: // MSDN: "GetSystemMetrics(SM_CMONITORS) counts only display monitors. This is different from // EnumDisplayMonitors, which enumerates display monitors and also non-display pseudo-monitors." MonitorInfoPackage mip = {0}; EnumForMonitorGet(mip, COUNT_ALL_MONITORS); return mip.count; } bif_impl int MonitorGetPrimary() { // Even if the first monitor to be retrieved by the EnumProc is always the primary (which is doubtful // since there's no mention of this in the MS docs) it seems best to have this function in case that // policy ever changes. MonitorInfoPackage mip = {0}; EnumForMonitorGet(mip, 0); return mip.count; } static FResult MonitorGet(optl<int> aIndex, int *aLeft, int *aTop, int *aRight, int *aBottom, int &aRetVal, bool aWorkArea) { MonitorInfoPackage mip = {0}; EnumForMonitorGet(mip, aIndex.value_or(0)); if (!mip.count) // Might be virtually impossible. return FR_E_WIN32; if (mip.monitor_number_to_find && mip.monitor_number_to_find != mip.count) return FR_E_ARG(0); // Otherwise: auto &monitor_rect = aWorkArea ? mip.monitor_info_ex.rcWork : mip.monitor_info_ex.rcMonitor; if (aLeft) *aLeft = monitor_rect.left; if (aTop) *aTop = monitor_rect.top; if (aRight) *aRight = monitor_rect.right; if (aBottom) *aBottom = monitor_rect.bottom; aRetVal = mip.count; return OK; } bif_impl FResult MonitorGet(optl<int> aIndex, int *aLeft, int *aTop, int *aRight, int *aBottom, int &aRetVal) { return MonitorGet(aIndex, aLeft, aTop, aRight, aBottom, aRetVal, false); } bif_impl FResult MonitorGetWorkArea(optl<int> aIndex, int *aLeft, int *aTop, int *aRight, int *aBottom, int &aRetVal) { return MonitorGet(aIndex, aLeft, aTop, aRight, aBottom, aRetVal, true); } bif_impl FResult MonitorGetName(optl<int> aIndex, StrRet &aRetVal) { MonitorInfoPackage mip = {0}; EnumForMonitorGet(mip, aIndex.value_or(0)); if (!mip.count) // Might be virtually impossible. return FR_E_WIN32; if (mip.monitor_number_to_find && mip.monitor_number_to_find != mip.count) return FR_E_ARG(0); // Using _countof() vs. _tcslen() may help both code size and performance, // due to inlining of Alloc() and its use of mCallerBuf for small strings: LPTSTR buf = aRetVal.Alloc(_countof(mip.monitor_info_ex.szDevice)); if (!buf) return FR_E_OUTOFMEM; _tcscpy(buf, mip.monitor_info_ex.szDevice); return OK; } #pragma endregion
8,191
C++
.cpp
172
45.482558
123
0.758024
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,109
interop.cpp
AutoHotkey_AutoHotkey/source/lib/interop.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "script_func_impl.h" struct NumGetParams { size_t target, right_side_bound; size_t num_size = sizeof(DWORD_PTR); BOOL is_integer = TRUE, is_signed = FALSE; }; void ConvertNumGetType(ExprTokenType &aToken, NumGetParams &op) { LPTSTR type = TokenToString(aToken); // No need to pass aBuf since any numeric value would not be recognized anyway. if (ctoupper(*type) == 'U') // Unsigned. { ++type; // Remove the first character from further consideration. op.is_signed = FALSE; } else op.is_signed = TRUE; switch(ctoupper(*type)) // Override "size" and aResultToken.symbol if type warrants it. Note that the above has omitted the leading "U", if present, leaving type as "Int" vs. "Uint", etc. { case 'P': // Nothing extra needed in this case. op.num_size = sizeof(void *), op.is_integer = TRUE; break; case 'I': if (_tcschr(type, '6')) // Int64. It's checked this way for performance, and to avoid access violation if string is bogus and too short such as "i64". op.num_size = 8, op.is_integer = TRUE; else op.num_size = 4, op.is_integer = TRUE; break; case 'S': op.num_size = 2, op.is_integer = TRUE; break; // Short. case 'C': op.num_size = 1, op.is_integer = TRUE; break; // Char. case 'D': op.num_size = 8, op.is_integer = FALSE; break; // Double. case 'F': op.num_size = 4, op.is_integer = FALSE; break; // Float. default: op.num_size = 0; break; } } void *BufferObject::sVTable = getVTable(); // Placing this here vs. in script_object.cpp improves some simple benchmarks by as much as 7%. void GetBufferObjectPtr(ResultToken &aResultToken, IObject *obj, size_t &aPtr, size_t &aSize) { if (BufferObject::IsInstanceExact(obj)) { // Some primitive benchmarks showed that this was about as fast as passing // a pointer directly, whereas invoking the properties (below) doubled the // overall time taken by NumGet/NumPut. aPtr = (size_t)((BufferObject *)obj)->Data(); aSize = ((BufferObject *)obj)->Size(); } else { if (GetObjectPtrProperty(obj, _T("Ptr"), aPtr, aResultToken)) GetObjectPtrProperty(obj, _T("Size"), aSize, aResultToken); } } void GetBufferObjectPtr(ResultToken &aResultToken, IObject *obj, size_t &aPtr) // See above for comments. { if (BufferObject::IsInstanceExact(obj)) aPtr = (size_t)((BufferObject *)obj)->Data(); else GetObjectPtrProperty(obj, _T("Ptr"), aPtr, aResultToken); } void ConvertNumGetTarget(ResultToken &aResultToken, ExprTokenType &target_token, NumGetParams &op) { if (IObject *obj = TokenToObject(target_token)) { GetBufferObjectPtr(aResultToken, obj, op.target, op.right_side_bound); if (aResultToken.Exited()) return; op.right_side_bound += op.target; } else { op.target = (size_t)TokenToInt64(target_token); op.right_side_bound = SIZE_MAX; } } BIF_DECL(BIF_NumGet) { NumGetParams op; ConvertNumGetTarget(aResultToken, *aParam[0], op); if (aResultToken.Exited()) return; if (aParamCount > 2) // Offset was specified. { op.target += (ptrdiff_t)TokenToInt64(*aParam[1]); aParam++; } // MinParams ensures there is always one more parameter. ConvertNumGetType(*aParam[1], op); // If the target is a variable, the following check ensures that the memory to be read lies within its capacity. // This seems superior to an exception handler because exception handlers only catch illegal addresses, // not ones that are technically legal but unintentionally bugs due to being beyond a variable's capacity. // Moreover, __try/except is larger in code size. Another possible alternative is IsBadReadPtr()/IsBadWritePtr(), // but those are discouraged by MSDN. // The following aren't covered by the check below: // - Due to rarity of negative offsets, only the right-side boundary is checked, not the left. // - Due to rarity and to simplify things, Float/Double aren't checked. if (!op.num_size || op.target < 65536 // Basic sanity check to catch incoming raw addresses that are zero or blank. On Win32, the first 64KB of address space is always invalid. || op.target+op.num_size > op.right_side_bound) // i.e. it's ok if target+size==right_side_bound because the last byte to be read is actually at target+size-1. In other words, the position of the last possible terminator within the variable's capacity is considered an allowable address. { _f_throw_value(ERR_PARAM_INVALID); } switch (op.num_size) { case 4: // Listed first for performance. if (!op.is_integer) aResultToken.value_double = *(float *)op.target; else if (op.is_signed) aResultToken.value_int64 = *(int *)op.target; // aResultToken.symbol defaults to SYM_INTEGER. else aResultToken.value_int64 = *(unsigned int *)op.target; break; case 8: if (op.is_integer) // Unsigned 64-bit integers aren't supported because variables/expressions can't support them. aResultToken.value_int64 = *(__int64 *)op.target; else aResultToken.value_double = *(double *)op.target; break; case 2: if (op.is_signed) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *(short *)op.target; else aResultToken.value_int64 = *(unsigned short *)op.target; break; case 1: if (op.is_signed) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *(char *)op.target; else aResultToken.value_int64 = *(unsigned char *)op.target; break; } if (!op.is_integer) aResultToken.symbol = SYM_FLOAT; } BIF_DECL(BIF_NumPut) { // Params can be any non-zero number of type-number pairs, followed by target[, offset]. // Prior validation has ensured that there are at least three parameters. // NumPut(t1, n1, t2, n2, p, o) // NumPut(t1, n1, t2, n2, p) // NumPut(t1, n1, p, o) // NumPut(t1, n1, p) // Split target[,offset] from aParam. bool offset_was_specified = !(aParamCount & 1); aParamCount -= 1 + int(offset_was_specified); ExprTokenType &target_token = *aParam[aParamCount]; NumGetParams op; ConvertNumGetTarget(aResultToken, target_token, op); if (aResultToken.Exited()) return; if (offset_was_specified) op.target += (ptrdiff_t)TokenToInt64(*aParam[aParamCount + 1]); size_t num_end; for (int n_param = 1; n_param < aParamCount; n_param += 2, op.target = num_end) { ConvertNumGetType(*aParam[n_param - 1], op); // Type name. ExprTokenType &token_to_write = *aParam[n_param]; // Numeric value. num_end = op.target + op.num_size; // This is used below and also as NumPut's return value. It's the address to the right of the item to be written. // See comments in NumGet about the following section: if (!op.num_size || !TokenIsNumeric(token_to_write) || op.target < 65536 // Basic sanity check to catch incoming raw addresses that are zero or blank. On Win32, the first 64KB of address space is always invalid. || num_end > op.right_side_bound) // i.e. it's ok if target+size==right_side_bound because the last byte to be read is actually at target+size-1. In other words, the position of the last possible terminator within the variable's capacity is considered an allowable address. { _f_throw_value(ERR_PARAM_INVALID); } union { __int64 num_i64; double num_f64; float num_f32; }; // Note that since v2.0-a083-97803aeb, TokenToInt64 supports conversion of large unsigned 64-bit // numbers from strings (producing a negative value, but with the right bit representation). if (op.is_integer) num_i64 = TokenToInt64(token_to_write); else { num_f64 = TokenToDouble(token_to_write); if (op.num_size == 4) num_f32 = (float)num_f64; } // This method benchmarked marginally faster than memcpy for the multi-param mode. switch (op.num_size) { case 8: *(UINT64 *)op.target = (UINT64)num_i64; break; case 4: *(UINT32 *)op.target = (UINT32)num_i64; break; case 2: *(UINT16 *)op.target = (UINT16)num_i64; break; case 1: *(UINT8 *)op.target = (UINT8)num_i64; break; } } aResultToken.value_int64 = num_end; // aResultToken.symbol was set to SYM_INTEGER by our caller. } BIF_DECL(BIF_StrGetPut) // BIF_DECL(BIF_StrGet), BIF_DECL(BIF_StrPut) { // To simplify flexible handling of parameters: ExprTokenType **aParam_end = aParam + aParamCount, **next_param = aParam; LPCVOID source_string; // This may hold an intermediate UTF-16 string in ANSI builds. int source_length; if (_f_callee_id == FID_StrPut) { // StrPut(String, Address[, Length][, Encoding]) ExprTokenType &source_token = *aParam[0]; if (TokenToObject(source_token)) _f_throw_param(0, _T("String")); source_string = (LPCVOID)TokenToString(source_token, _f_number_buf); // Safe to use _f_number_buf since StrPut won't use it for the result. source_length = (int)((source_token.symbol == SYM_VAR) ? source_token.var->CharLength() : _tcslen((LPCTSTR)source_string)); ++next_param; // Remove the String param from further consideration. } else { // StrGet(Address[, Length][, Encoding]) source_string = NULL; source_length = 0; } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Set default in case of early return. IObject *buffer_obj; LPVOID address; size_t max_bytes = SIZE_MAX; int length = -1; // actual length bool length_is_max_size = false; UINT encoding = UorA(CP_UTF16, CP_ACP); // native encoding // Parameters are interpreted according to the following rules (highest to lowest precedence): // Legend: StrPut(String[, X, Y, Z]) or StrGet(Address[, Y, Z]) // - If X is non-numeric, it is Encoding. Calculates required buffer size but does nothing else. Y and Z must be omitted. // - If X is numeric, it is Address. (For StrGet, non-numeric Address is treated as an error.) // - If Y is numeric, it is Length. Otherwise "Actual length" is assumed. // - If a parameter remains, it is Encoding. // Encoding may therefore only be purely numeric if Address(X) and Length(Y) are specified. const LPVOID FIRST_VALID_ADDRESS = (LPVOID)65536; if (next_param < aParam_end && TokenIsNumeric(**next_param)) { address = (LPVOID)TokenToInt64(**next_param); ++next_param; } else if (next_param < aParam_end && (buffer_obj = TokenToObject(**next_param))) { size_t ptr; GetBufferObjectPtr(aResultToken, buffer_obj, ptr, max_bytes); if (aResultToken.Exited()) return; address = (LPVOID)ptr; ++next_param; } else { if (!source_string || aParamCount > 2) { // See the "Legend" above. Either this is StrGet and Address was invalid (it can't be omitted due // to prior min-param checks), or it is StrPut and there are too many parameters. _f_throw_value(source_string ? ERR_PARAM_INVALID : ERR_PARAM1_INVALID); // StrPut : StrGet } // else this is the special measuring mode of StrPut, where Address and Length are omitted. // A length of 0 when passed to the Win API conversion functions (or the code below) means // "calculate the required buffer size, but don't do anything else." length = 0; address = FIRST_VALID_ADDRESS; // Skip validation below; address should never be used when length == 0. } if (next_param < aParam_end) { if (length == -1) // i.e. not StrPut(String, Encoding) { if (TokenIsNumeric(**next_param)) // Length parameter { length = (int)TokenToInt64(**next_param); if (!source_string) // StrGet { if (length == 0) return; // Get 0 chars. if (length < 0) length = -length; // Retrieve exactly this many chars, even if there are null chars. else length_is_max_size = true; // Limit to this, but stop at the first null char. } else if (length <= 0) _f_throw_value(ERR_INVALID_LENGTH); ++next_param; // Let encoding be the next param, if present. } else if ((*next_param)->symbol == SYM_MISSING) { // Length was "explicitly omitted", as in StrGet(Address,, Encoding), // which allows Encoding to be an integer without specifying Length. ++next_param; } // aParam now points to aParam_end or the Encoding param. } if (next_param < aParam_end) { encoding = Line::ConvertFileEncoding(**next_param); if (encoding == -1) _f_throw_value(ERR_INVALID_ENCODING); } } // Note: CP_AHKNOBOM is not supported; "-RAW" must be omitted. // Check for obvious errors to prevent an Access Violation. // Address can be zero for StrPut if length is also zero (see below). // Address can be zero for StrGet if buffer size is zero (if length was zero, the function already returned). if ( address < FIRST_VALID_ADDRESS && max_bytes != 0 // Also check for overlap, in case memcpy is used instead of MultiByteToWideChar/WideCharToMultiByte. // (Behaviour for memcpy would be "undefined", whereas MBTWC/WCTBM would fail.) Overlap in the // other direction (source_string beginning inside address..length) should not be possible. || (address >= source_string && address <= ((LPTSTR)source_string + source_length) && source_string) // The following catches StrPut(X, StrPtr(Y)) where Y has zero capacity. || (address == Var::sEmptyString && source_length) ) { _f_throw_param(source_string ? 1 : 0); } if (max_bytes != SIZE_MAX) { // Target is a Buffer object with known size, so limit length accordingly. int max_chars = int(max_bytes >> int(encoding == CP_UTF16)); if (length > max_chars) _f_throw_value(ERR_INVALID_LENGTH); if (source_length > max_chars) _f_throw_param(1); if (length == -1) { length = max_chars; length_is_max_size = true; } } if (source_string) // StrPut { int char_count; // Either bytes or characters, depending on the target encoding. aResultToken.symbol = SYM_INTEGER; // Most paths below return an integer. if (!source_length) { // Take a shortcut when source_string is empty, since some paths below might not handle it correctly. if (length) // true except when in measuring mode. { if (encoding == CP_UTF16) *(LPWSTR)address = '\0'; else *(LPSTR)address = '\0'; } aResultToken.value_int64 = encoding == CP_UTF16 ? sizeof(WCHAR) : sizeof(CHAR); return; } if (encoding == UorA(CP_UTF16, CP_ACP)) { // No conversion required: target encoding is the same as the native encoding of this build. char_count = source_length + 1; // + 1 because generally a null-terminator is wanted. if (length) { // Check for sufficient buffer space. Cast to UINT and compare unsigned values: if length is // -1 it should be interpreted as a very large unsigned value, in effect bypassing this check. if ((UINT)source_length <= (UINT)length) { if (source_length == length) // Exceptional case: caller doesn't want a null-terminator (or passed this length in error). --char_count; // Copy the string, including null-terminator if requested. tmemcpy((LPTSTR)address, (LPCTSTR)source_string, char_count); } else // For consistency with the sections below, don't truncate the string. _f_throw_value(ERR_INVALID_LENGTH); } //else: Caller just wants the the required buffer size (char_count), which will be returned below. // Note that although this seems equivalent to StrLen(), the caller might have explicitly // passed an Encoding; in that case, the result of StrLen() might be different on the // opposite build (ANSI vs Unicode) as the section below would be executed instead of this one. } else { // Conversion is required. For Unicode builds, this means encoding != CP_UTF16; #ifndef UNICODE // therefore, this section is relevant only to ANSI builds: if (encoding == CP_UTF16) { // See similar section below for comments. if (length <= 0) { char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, NULL, 0) + 1; if (length == 0) { aResultToken.value_int64 = char_count * (1 + (encoding == CP_UTF16)); return; } length = char_count; } char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, (LPWSTR)address, length); if (char_count && char_count < length) ((LPWSTR)address)[char_count++] = '\0'; } else // encoding != CP_UTF16 { // Convert native ANSI string to UTF-16 first. CStringWCharFromChar wide_buf((LPCSTR)source_string, source_length, CP_ACP); source_string = wide_buf.GetString(); source_length = wide_buf.GetLength(); #endif // UTF-8 does not support this flag. Although the check further below would probably // compensate for this, UTF-8 is probably common enough to leave this exception here. DWORD flags = (encoding == CP_UTF8) ? 0 : WC_NO_BEST_FIT_CHARS; if (length <= 0) // -1 or 0 { // Determine required buffer size. char_count = WideCharToMultiByte(encoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL); if (!char_count) // Above has ensured source is not empty, so this must be an error. { if (GetLastError() == ERROR_INVALID_FLAGS) { // Try again without flags. MSDN lists a number of code pages for which flags must be 0, including UTF-7 and UTF-8 (but UTF-8 is handled above). flags = 0; // Must be set for this call and the call further below. char_count = WideCharToMultiByte(encoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL); } if (!char_count) _f_throw_win32(); } ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). if (length == 0) // Caller just wants the required buffer size. { aResultToken.value_int64 = char_count * (1 + (encoding == CP_UTF16)); return; } // Assume there is sufficient buffer space and hope for the best: length = char_count; } // Convert to target encoding. char_count = WideCharToMultiByte(encoding, flags, (LPCWSTR)source_string, source_length, (LPSTR)address, length, NULL, NULL); if (!char_count && flags && GetLastError() == ERROR_INVALID_FLAGS) // See the similar check above for comments; this one covers cases where length was specified. char_count = WideCharToMultiByte(encoding, 0, (LPCWSTR)source_string, source_length, (LPSTR)address, length, NULL, NULL); // Since above did not null-terminate, check for buffer space and null-terminate if there's room. // It is tempting to always null-terminate (potentially replacing the last byte of data), // but that would exclude this function as a means to copy a string into a fixed-length array. if (char_count && char_count < length) ((LPSTR)address)[char_count++] = '\0'; // else no space to null-terminate; or conversion failed. #ifndef UNICODE } #endif if (!char_count) _f_throw_win32(); } // Return the number of bytes written. aResultToken.value_int64 = char_count * (1 + (encoding == CP_UTF16)); } else // StrGet { if (length_is_max_size) // Implies length != -1. { // Caller specified the maximum character count, not the exact length. // If the length includes null characters, the conversion functions below // would convert more than necessary and we'd still have to recalculate the // length. So find the exact length up front: if (encoding == CP_UTF16) length = (int)wcsnlen((LPWSTR)address, length); else length = (int)strnlen((LPSTR)address, length); } if (encoding != UorA(CP_UTF16, CP_ACP)) { // Conversion is required. int conv_length; // MS docs: "Note that, if cbMultiByte is 0, the function fails." if (!length) _f_return_empty; #ifdef UNICODE // Convert multi-byte encoded string to UTF-16. conv_length = MultiByteToWideChar(encoding, 0, (LPCSTR)address, length, NULL, 0); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. return; // Out of memory. conv_length = MultiByteToWideChar(encoding, 0, (LPCSTR)address, length, aResultToken.marker, conv_length); #else CStringW wide_buf; // If the target string is not UTF-16, convert it to that first. if (encoding != CP_UTF16) { StringCharToWChar((LPCSTR)address, wide_buf, length, encoding); address = (void *)wide_buf.GetString(); length = wide_buf.GetLength(); } // Now convert UTF-16 to ACP. conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)address, length, NULL, 0, NULL, NULL); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { aResult = FAIL; return; // Out of memory. } conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)address, length, aResultToken.marker, conv_length, NULL, NULL); #endif if (!conv_length) // This can only be failure, since ... (see below) _f_throw_win32(); if (length == -1) // conv_length includes a null-terminator in this case. --conv_length; else aResultToken.marker[conv_length] = '\0'; // It wasn't terminated above. aResultToken.marker_length = conv_length; // Update it. } else if (length == -1) { // Return this null-terminated string, no conversion necessary. aResultToken.marker = (LPTSTR) address; aResultToken.marker_length = _tcslen(aResultToken.marker); } else { // No conversion necessary, but we might not want the whole string. // Copy and null-terminate the string; some callers might require it. TokenSetResult(aResultToken, (LPCTSTR)address, length); } } } BIF_DECL(BIF_StrPtr) { switch (aParam[0]->symbol) { case SYM_STRING: _f_return((UINT_PTR)aParam[0]->marker); case SYM_VAR: if (!aParam[0]->var->IsPureNumericOrObject()) _f_return((UINT_PTR)aParam[0]->var->Contents(FALSE)); // VAR_NORMAL and the above condition imply passing FALSE is safe. default: _f_throw_type(_T("String"), *aParam[0]); } }
22,422
C++
.cpp
532
38.781955
289
0.703778
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,110
drive.cpp
AutoHotkey_AutoHotkey/source/lib/drive.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include <winioctl.h> // For PREVENT_MEDIA_REMOVAL and CD lock/unlock. #include "script.h" #include "script_func_impl.h" #include "abi.h" static bool IsValidDriveLetter(LPCTSTR aDrive) { return cisalpha(*aDrive) && (!aDrive[1] || (aDrive[1] == ':' && !aDrive[2] || (aDrive[2] == '\\' && !aDrive[3]))); } template<size_t n> static void DriveFixPath(LPCTSTR &aDrive, TCHAR (&aBuf)[n]) { // Append a backslash because certain API calls or OS versions might require it; // but leave aDrive as-is if it's too long for the buffer, so that if long path // support within the OS is improved in future, callers can utilize it. auto path_length = _tcslen(aDrive); if (path_length && path_length < _countof(aBuf) && aDrive[path_length - 1] != '\\') { tmemcpy(aBuf, aDrive, path_length); aBuf[path_length++] = '\\'; aBuf[path_length] = '\0'; aDrive = aBuf; } } static FResult DriveSpace(LPCTSTR aPath, __int64 &aRetVal, bool aGetFreeSpace) // Because of NTFS's ability to mount volumes into a directory, a path might not necessarily // have the same amount of free space as its root drive. However, I'm not sure if this // method here actually takes that into account. { if (!*aPath) return FR_E_ARG(0); TCHAR buf[MAX_PATH]; // MAX_PATH vs T_MAX_PATH because testing shows it doesn't support long paths even with \\?\. tcslcpy(buf, aPath, _countof(buf)); size_t length = _tcslen(buf); if (buf[length - 1] != '\\' // Trailing backslash is absent, && length + 1 < _countof(buf)) // and there's room to fix it. { buf[length++] = '\\'; buf[length] = '\0'; } //else it should still work unless this is a UNC path. // MSDN: "The GetDiskFreeSpaceEx function returns correct values for all volumes, including those // that are greater than 2 gigabytes." ULARGE_INTEGER total, free, used; if (!GetDiskFreeSpaceEx(buf, &free, &total, &used)) return FR_E_WIN32; // Casting this way allows sizes of up to 2,097,152 gigabytes: aRetVal = (__int64)((unsigned __int64)(aGetFreeSpace ? free.QuadPart : total.QuadPart) / 1048576); return OK; } bif_impl FResult DriveGetCapacity(StrArg aPath, __int64 &aRetVal) { return DriveSpace(aPath, aRetVal, false); } bif_impl FResult DriveGetSpaceFree(StrArg aPath, __int64 &aRetVal) { return DriveSpace(aPath, aRetVal, true); } static FResult DriveEject(optl<StrArg> aDrive, bool aEject) { // Don't do DRIVE_SET_PATH in this case since trailing backslash is not wanted. // It seems best not to do the below check since: // 1) aValue usually lacks a trailing backslash, which might prevent DriveGetType() from working on some OSes. // 2) Eject (and more rarely, retract) works on some other drive types. // 3) CreateFile or DeviceIoControl will simply fail or have no effect if the drive isn't of the right type. //if (GetDriveType(aDrive) != DRIVE_CDROM) // return FR_E_FAILED; TCHAR path[] { '\\', '\\', '.', '\\', 0, ':', '\0', '\0' }; LPCTSTR drive; if (aDrive.has_value()) { drive = aDrive.value(); // Testing showed that a Volume GUID of the form \\?\Volume{...} will work even when // the drive isn't mapped to a drive letter. if (IsValidDriveLetter(drive)) { path[4] = drive[0]; drive = path; } } else // When drive is omitted, operate upon the first CD/DVD drive. { path[6] = '\\'; // GetDriveType technically requires a slash, although it may work without. // Testing with mciSendString() while changing or removing drive letters showed that // its "default" drive is really just the first drive found in alphabetical order, // which is also the most obvious/intuitive choice. for (TCHAR c = 'A'; ; ++c) { path[4] = c; if (GetDriveType(path) == DRIVE_CDROM) break; if (c == 'Z') return FR_E_FAILED; // No CD/DVD drive found with a drive letter. } path[6] = '\0'; // Remove the trailing slash for CreateFile to open the volume. drive = path; } // Testing indicates neither this method nor the MCI method work with mapped drives or UNC paths. // That makes sense when one considers that the following opens the *volume*, whereas a network // share would correspond to a directory; i.e. this needs "\\.\D:" and not "\\.\D:\". HANDLE hVol = CreateFile(drive, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hVol == INVALID_HANDLE_VALUE) return FR_E_WIN32; DWORD unused; auto successful = DeviceIoControl(hVol, aEject ? IOCTL_STORAGE_EJECT_MEDIA : IOCTL_STORAGE_LOAD_MEDIA, NULL, 0, NULL, 0, &unused, NULL); CloseHandle(hVol); return successful ? OK : FR_E_WIN32; } bif_impl FResult DriveEject(optl<StrArg> aDrive) { return DriveEject(aDrive, true); } bif_impl FResult DriveRetract(optl<StrArg> aDrive) { return DriveEject(aDrive, false); } bif_impl FResult DriveSetLabel(StrArg aDrive, optl<StrArg> aLabel) { TCHAR buf[MAX_PATH]; // MAX_PATH vs. T_MAX_PATH because SetVolumeLabel() can't seem to make use of long paths. DriveFixPath(aDrive, buf); return SetVolumeLabel(aDrive, aLabel.value_or_null()) ? OK : FR_E_WIN32; } static FResult DriveLock(StrArg aDrive, bool aLockIt) { if (!IsValidDriveLetter(aDrive)) return FR_E_ARG(0); HANDLE hdevice; DWORD unused; BOOL result; TCHAR filename[64]; _stprintf(filename, _T("\\\\.\\%c:"), *aDrive); // FILE_READ_ATTRIBUTES is not enough; it yields "Access Denied" error. So apparently all or part // of the sub-attributes in GENERIC_READ are needed. An MSDN example implies that GENERIC_WRITE is // only needed for GetDriveType() == DRIVE_REMOVABLE drives, and maybe not even those when all we // want to do is lock/unlock the drive (that example did quite a bit more). In any case, research // indicates that all CD/DVD drives are ever considered DRIVE_CDROM, not DRIVE_REMOVABLE. // Due to this and the unlikelihood that GENERIC_WRITE is ever needed anyway, GetDriveType() is // not called for the purpose of conditionally adding the GENERIC_WRITE attribute. hdevice = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hdevice == INVALID_HANDLE_VALUE) return FR_E_WIN32; PREVENT_MEDIA_REMOVAL pmr; pmr.PreventMediaRemoval = aLockIt; result = DeviceIoControl(hdevice, IOCTL_STORAGE_MEDIA_REMOVAL, &pmr, sizeof(PREVENT_MEDIA_REMOVAL) , NULL, 0, &unused, NULL); CloseHandle(hdevice); return result ? OK : FR_E_WIN32; } bif_impl FResult DriveLock(StrArg aDrive) { return DriveLock(aDrive, true); } bif_impl FResult DriveUnlock(StrArg aDrive) { return DriveLock(aDrive, false); } bif_impl FResult DriveGetList(optl<StrArg> aType, StrRet &aRetVal) { UINT drive_type; #define ALL_DRIVE_TYPES 256 if (!aType.has_value()) drive_type = ALL_DRIVE_TYPES; else if (!_tcsicmp(aType.value(), _T("CDROM"))) drive_type = DRIVE_CDROM; else if (!_tcsicmp(aType.value(), _T("Removable"))) drive_type = DRIVE_REMOVABLE; else if (!_tcsicmp(aType.value(), _T("Fixed"))) drive_type = DRIVE_FIXED; else if (!_tcsicmp(aType.value(), _T("Network"))) drive_type = DRIVE_REMOTE; else if (!_tcsicmp(aType.value(), _T("RAMDisk"))) drive_type = DRIVE_RAMDISK; else if (!_tcsicmp(aType.value(), _T("Unknown"))) drive_type = DRIVE_UNKNOWN; else return FR_E_ARG(0); LPTSTR found_drives = aRetVal.Alloc(26); // Need room for all 26 possible drive letters. if (!found_drives) return FR_E_OUTOFMEM; int found_drives_count; TCHAR letter[] = { 0, ':', '\\', '\0' }; for (found_drives_count = 0, *letter = 'A'; *letter <= 'Z'; ++*letter) { UINT this_type = GetDriveType(letter); if (this_type == drive_type || (drive_type == ALL_DRIVE_TYPES && this_type != DRIVE_NO_ROOT_DIR)) found_drives[found_drives_count++] = *letter; // Store just the drive letters. } found_drives[found_drives_count] = '\0'; // Terminate the string of found drive letters. // An empty list should not be flagged as failure, even for FIXED drive_type. // For example, when booting Windows PE from a REMOVABLE drive, it mounts a RAMDISK // drive but there may be no FIXED drives present. //if (!*found_drives) // return FR_E_FAILED; return OK; } bif_impl FResult DriveGetFilesystem(StrArg aDrive, StrRet &aRetVal) { TCHAR buf[MAX_PATH]; // MAX_PATH vs. T_MAX_PATH because testing in 2019 indicated GetVolumeInformation() did not support long paths. DriveFixPath(aDrive, buf); LPTSTR file_system = aRetVal.CallerBuf(); if (!GetVolumeInformation(aDrive, NULL, 0, NULL, NULL, NULL, file_system, StrRet::CallerBufSize)) return FR_E_WIN32; aRetVal.SetTemp(file_system); return OK; } bif_impl FResult DriveGetLabel(StrArg aDrive, StrRet &aRetVal) { TCHAR buf[MAX_PATH]; // MAX_PATH vs. T_MAX_PATH because testing in 2019 indicated GetVolumeInformation() did not support long paths. DriveFixPath(aDrive, buf); LPTSTR volume_name = aRetVal.CallerBuf(); if (!GetVolumeInformation(aDrive, volume_name, StrRet::CallerBufSize, NULL, NULL, NULL, NULL, 0)) return FR_E_WIN32; aRetVal.SetTemp(volume_name); return OK; } bif_impl FResult DriveGetSerial(StrArg aDrive, __int64 &aRetVal) { TCHAR buf[MAX_PATH]; // MAX_PATH vs. T_MAX_PATH because testing in 2019 indicated GetVolumeInformation() did not support long paths. DriveFixPath(aDrive, buf); DWORD serial_number; if (!GetVolumeInformation(aDrive, NULL, 0, &serial_number, NULL, NULL, NULL, 0)) return FR_E_WIN32; aRetVal = serial_number; return OK; } bif_impl FResult DriveGetType(StrArg aDrive, StrRet &aRetVal) { TCHAR buf[T_MAX_PATH]; // T_MAX_PATH vs. MAX_PATH because GetDriveType() can support long paths. DriveFixPath(aDrive, buf); switch (GetDriveType(aDrive)) { case DRIVE_UNKNOWN: aRetVal.SetStatic(_T("Unknown")); break; case DRIVE_REMOVABLE: aRetVal.SetStatic(_T("Removable")); break; case DRIVE_FIXED: aRetVal.SetStatic(_T("Fixed")); break; case DRIVE_REMOTE: aRetVal.SetStatic(_T("Network")); break; case DRIVE_CDROM: aRetVal.SetStatic(_T("CDROM")); break; case DRIVE_RAMDISK: aRetVal.SetStatic(_T("RAMDisk")); break; default: // DRIVE_NO_ROOT_DIR aRetVal.SetEmpty(); } return OK; } bif_impl FResult DriveGetStatus(StrArg aDrive, StrRet &aRetVal) { TCHAR buf[MAX_PATH]; // MAX_PATH vs. T_MAX_PATH because testing in 2019 indicated GetDiskFreeSpace() did not support long paths. DriveFixPath(aDrive, buf); DWORD sectors_per_cluster, bytes_per_sector, free_clusters, total_clusters; switch (GetDiskFreeSpace(aDrive, &sectors_per_cluster, &bytes_per_sector, &free_clusters, &total_clusters) ? ERROR_SUCCESS : GetLastError()) { case ERROR_SUCCESS: aRetVal.SetStatic(_T("Ready")); break; case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: aRetVal.SetStatic(_T("Invalid")); break; case ERROR_NOT_READY: aRetVal.SetStatic(_T("NotReady")); break; case ERROR_WRITE_PROTECT: aRetVal.SetStatic(_T("ReadOnly")); break; default: aRetVal.SetStatic(_T("Unknown")); break; } return OK; } bif_impl FResult DriveGetStatusCD(optl<StrArg> aDrive, StrRet &aRetVal) { // Explicitly validate aDrive since it'll be inserted into the MCI command string. if (aDrive.has_value() && !IsValidDriveLetter(aDrive.value())) return FR_E_ARG(0); // Don't do DRIVE_SET_PATH in this case since trailing backslash might prevent it from // working on some OSes. // It seems best not to do the below check since: // 1) aValue usually lacks a trailing backslash so that it will work correctly with "open c: type cdaudio". // That lack might prevent DriveGetType() from working on some OSes. // 2) It's conceivable that tray eject/retract might work on certain types of drives even though // they aren't of type DRIVE_CDROM. // 3) One or both of the calls to mciSendString() will simply fail if the drive isn't of the right type. //if (GetDriveType(aValue) != DRIVE_CDROM) // Testing reveals that the below method does not work on Network CD/DVD drives. // return FR_E_FAILED; TCHAR mci_string[256]; const auto status_size = 16; LPTSTR status = aRetVal.Alloc(status_size); // Note that there is apparently no way to determine via mciSendString() whether the tray is ejected // or not, since "open" is returned even when the tray is closed but there is no media. if (!aDrive.has_value()) // When drive is omitted, operate upon default CD/DVD drive. { if (mciSendString(_T("status cdaudio mode"), status, status_size, NULL)) // Error. return FR_E_FAILED; } else // Operate upon a specific drive letter. { sntprintf(mci_string, _countof(mci_string), _T("open %s type cdaudio alias cd wait shareable"), aDrive.value()); if (mciSendString(mci_string, NULL, 0, NULL)) // Error. return FR_E_FAILED; MCIERROR error = mciSendString(_T("status cd mode"), status, status_size, NULL); mciSendString(_T("close cd wait"), NULL, 0, NULL); if (error) return FR_E_FAILED; } // Otherwise, success: return OK; }
13,373
C++
.cpp
305
41.665574
137
0.728537
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,111
DllCall.cpp
AutoHotkey_AutoHotkey/source/lib/DllCall.cpp
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #include "stdafx.h" #include "script.h" #include "globaldata.h" #include "script_func_impl.h" #ifdef ENABLE_DLLCALL #ifdef WIN32_PLATFORM // Interface for DynaCall(): #define DC_MICROSOFT 0x0000 // Default #define DC_BORLAND 0x0001 // Borland compat #define DC_CALL_CDECL 0x0010 // __cdecl #define DC_CALL_STD 0x0020 // __stdcall #define DC_RETVAL_MATH4 0x0100 // Return value in ST #define DC_RETVAL_MATH8 0x0200 // Return value in ST #define DC_CALL_STD_BO (DC_CALL_STD | DC_BORLAND) #define DC_CALL_STD_MS (DC_CALL_STD | DC_MICROSOFT) #define DC_CALL_STD_M8 (DC_CALL_STD | DC_RETVAL_MATH8) #endif union DYNARESULT // Various result types { int Int; // Generic four-byte type long Long; // Four-byte long void *Pointer; // 32-bit pointer float Float; // Four byte real double Double; // 8-byte real __int64 Int64; // big int (64-bit) UINT_PTR UIntPtr; }; struct DYNAPARM { union { int value_int; // Args whose width is less than 32-bit are also put in here because they are right justified within a 32-bit block on the stack. float value_float; __int64 value_int64; UINT_PTR value_uintptr; double value_double; char *astr; wchar_t *wstr; void *ptr; }; // Might help reduce struct size to keep other members last and adjacent to each other (due to // 8-byte alignment caused by the presence of double and __int64 members in the union above). DllArgTypes type; union { int struct_size; struct { bool passed_by_address; bool is_unsigned; // Allows return value and output parameters to be interpreted as unsigned vs. signed. bool is_hresult; // Only used for the return value. }; }; }; #ifdef _WIN64 // This function was borrowed from http://dyncall.org/ extern "C" UINT_PTR PerformDynaCall(size_t stackArgsSize, DWORD_PTR* stackArgs, DWORD_PTR* regArgs, void* aFunction); // Retrieve a float or double return value. These don't actually do anything, since the value we // want is already in the xmm0 register which is used to return float or double values. // Many thanks to http://locklessinc.com/articles/c_abi_hacks/ for the original idea. extern "C" float GetFloatRetval(); extern "C" double GetDoubleRetval(); static inline UINT_PTR DynaParamToElement(DYNAPARM& parm) { if(parm.passed_by_address) return (UINT_PTR) &parm.value_uintptr; else return parm.value_uintptr; } #endif #ifdef WIN32_PLATFORM void DynaCall(int aFlags, void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD &aException , void *aRet, int aRetSize, DWORD aExtraStackSize = 0) #elif defined(_WIN64) void DynaCall(void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD &aException, void *aRet, int aRetSize) #else #error DllCall not supported on this platform #endif // Based on the code by Ton Plooy <tonp@xs4all.nl>. // Call the specified function with the given parameters. Build a proper stack and take care of correct // return value processing. { aException = 0; // Set default output parameter for caller. SetLastError(g->LastError); // v1.0.46.07: In case the function about to be called doesn't change last-error, this line serves to retain the script's previous last-error rather than some arbitrary one produced by AutoHotkey's own internal API calls. This line has no measurable impact on performance. DYNARESULT Res = {0}; bool register_return = (aRetSize < 3 || aRetSize == 4 || aRetSize == 8); // i.e. 0, 1, 2, 4 or 8. #ifdef WIN32_PLATFORM // Declaring all variables early should help minimize stack interference of C code with asm. DWORD *our_stack; // Used to read the structure DWORD *pdword; DWORD esp_start, esp_end; int i, esp_delta; // Declare this here rather than later to prevent C code from interfering with esp. // Reserve enough space on the stack to handle the worst case of our args (which is currently a // maximum of 8 bytes per arg). This avoids any chance that compiler-generated code will use // the stack in a way that disrupts our insertion of args onto the stack. DWORD reserved_stack_size = aParamCount * 8 + aExtraStackSize; _asm { mov our_stack, esp // our_stack is the location where we will write our args (bypassing "push"). mov esp_start, esp // For detecting whether a DC_CALL_STD function was sent too many or too few args. sub esp, reserved_stack_size // The stack grows downward, so this "allocates" space on the stack. } // "Push" args onto the portion of the stack reserved above. Every argument is aligned on a 4-byte boundary. // We start at the rightmost argument (i.e. reverse order). for (i = aParamCount - 1; i > -1; --i) { DYNAPARM &this_param = aParam[i]; // For performance and convenience. if (this_param.type == DLL_ARG_STRUCT) { int& size = this_param.struct_size; ASSERT(!(size % 4)); for (pdword = (DWORD*)(this_param.value_uintptr + size); size; size -= 4) *--our_stack = *--pdword; } // Push the arg or its address onto the portion of the stack that was reserved for our use above. else if (this_param.passed_by_address) *--our_stack = (DWORD)&this_param.value_int; // Any union member would work. else // this_param's value is contained directly inside the union. { if (this_param.type == DLL_ARG_INT64 || this_param.type == DLL_ARG_DOUBLE) { our_stack -= 2; *(__int64*)our_stack = this_param.value_int64; } else *--our_stack = this_param.value_uintptr; } } if (!register_return) { // Return value isn't passed through registers, memory copy // is performed instead. Pass the pointer as hidden arg. *--our_stack = (DWORD)aRet; // ESP = ESP - 4, SS:[ESP] = pMem } // Call the function. __try // Each try/except section adds at most 240 bytes of uncompressed code, and typically doesn't measurably affect performance. { _asm { mov esp, our_stack // Adjust ESP to indicate that the args have already been pushed onto the stack. call[aFunction] // Stack is now properly built, we can call the function } } __except(EXCEPTION_EXECUTE_HANDLER) { aException = GetExceptionCode(); // aException is an output parameter for our caller. } // Even if an exception occurred (perhaps due to the callee having been passed a bad pointer), // attempt to restore the stack to prevent making things even worse. _asm { mov esp_end, esp // See below. mov esp, esp_start // // For DC_CALL_STD functions (since they pop their own arguments off the stack): // Since the stack grows downward in memory, if the value of esp after the call is less than // that before the call's args were pushed onto the stack, there are still items left over on // the stack, meaning that too many args (or an arg too large) were passed to the callee. // Conversely, if esp is now greater that it should be, too many args were popped off the // stack by the callee, meaning that too few args were provided to it. In either case, // and even for CDECL, the following line restores esp to what it was before we pushed the // function's args onto the stack, which in the case of DC_CALL_STD helps prevent crashes // due to too many or to few args having been passed. mov DWORD PTR [Res], eax // These will be overwritten if return type is floating-point. mov DWORD PTR [Res + 4], edx // Note that eax/edx might be reused by the if()s below. } // Possibly adjust stack and read return values. // The following is commented out because the stack (esp) is restored above, for both CDECL and STD. //if (aFlags & DC_CALL_CDECL) // _asm add esp, our_stack_size // CDECL requires us to restore the stack after the call. if (aFlags & DC_RETVAL_MATH4) _asm fstp dword ptr [Res] else if (aFlags & DC_RETVAL_MATH8) _asm fstp qword ptr [Res] #endif // WIN32_PLATFORM #ifdef _WIN64 int params_left = aParamCount, i = 0, r = 0; DWORD_PTR regArgs[4]; DWORD_PTR* stackArgs = NULL; size_t stackArgsSize = 0; if (!register_return) { // Return value isn't passed through registers, memory copy // is performed instead. Pass the pointer as hidden arg. regArgs[r++] = (DWORD_PTR)aRet; } // The first four parameters are passed in x64 through registers... like ARM :D for (; r < 4 && params_left; --params_left) regArgs[r++] = DynaParamToElement(aParam[i++]); // Copy the remaining parameters if(params_left) { stackArgsSize = params_left * 8; stackArgs = (DWORD_PTR*) _alloca(stackArgsSize); for(int i = 0; i < params_left; i ++) stackArgs[i] = DynaParamToElement(aParam[i+4]); } // Call the function. __try { Res.UIntPtr = PerformDynaCall(stackArgsSize, stackArgs, regArgs, aFunction); } __except(EXCEPTION_EXECUTE_HANDLER) { aException = GetExceptionCode(); // aException is an output parameter for our caller. } #endif if (register_return) // aRet wasn't passed as a "hidden" parameter. memcpy(aRet, &Res, aRetSize ? aRetSize : 8); // aRetSize == 0 indicates aRet points to a DYNARESULT. // v1.0.42.03: The following supports A_LastError. It's called even if an exception occurred because it // might add value in some such cases. Benchmarks show that this has no measurable impact on performance. // A_LastError was implemented rather than trying to change things so that a script could use DllCall to // call GetLastError() because: Even if we could avoid calling any API function that resets LastError // (which seems unlikely) it would be difficult to maintain (and thus a source of bugs) as revisions are // made in the future. g->LastError = GetLastError(); TCHAR buf[32]; #ifdef WIN32_PLATFORM esp_delta = esp_start - esp_end; // Positive number means too many args were passed, negative means too few. // For v2.1, DC_CALL_STD is omitted from aFlags by default so CDecl can be omitted in all cases. // Errors are still detected for stdcall functions that accept at least 1 parameter. aFlags is // ignored when esp_end != (DWORD)our_stack since that means it really isn't CDecl. if (esp_delta && ((aFlags & DC_CALL_STD) || esp_end != (DWORD)our_stack)) { _itot(esp_delta, buf, 10); if (esp_delta > 0) g_script.ThrowRuntimeException(_T("Parameter list too large."), buf); else g_script.ThrowRuntimeException(_T("Parameter list too small."), buf); } else #endif // Too many or too few args takes precedence over reporting the exception because it's more informative. // In other words, any exception was likely caused by the fact that there were too many or too few. if (aException) { // It's a little easier to recognize the common error codes when they're in hex format. buf[0] = '0'; buf[1] = 'x'; _ultot(aException, buf + 2, 16); g_script.ThrowRuntimeException(ERR_EXCEPTION, buf); } } void ConvertDllArgType(LPTSTR aBuf, DYNAPARM &aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. { LPTSTR type_string = aBuf; TCHAR buf[32]; if (ctoupper(*type_string) == 'U') // Unsigned { aDynaParam.is_unsigned = true; ++type_string; // Omit the 'U' prefix from further consideration. } else aDynaParam.is_unsigned = false; // Check for empty string before checking for pointer suffix, so that we can skip the first character. This is needed to simplify "Ptr" type-name support. if (!*type_string) { aDynaParam.type = DLL_ARG_INVALID; return; } tcslcpy(buf, type_string, _countof(buf)); // Make a modifiable copy for easier parsing below. // v1.0.30.02: The addition of 'P'. // However, the current detection below relies upon the fact that none of the types currently // contain the letter P anywhere in them, so it would have to be altered if that ever changes. LPTSTR cp = StrChrAny(buf + 1, _T("*pP")); // Asterisk or the letter P. Relies on the check above to ensure type_string is not empty (and buf + 1 is valid). if (cp && !*omit_leading_whitespace(cp + 1)) // Additional validation: ensure nothing following the suffix. { aDynaParam.passed_by_address = true; // Remove trailing options so that stricmp() can be used below. // Allow optional space in front of asterisk (seems okay even for 'P'). if (IS_SPACE_OR_TAB(cp[-1])) { cp = omit_trailing_whitespace(buf, cp - 1); cp[1] = '\0'; // Terminate at the leftmost whitespace to remove all whitespace and the suffix. } else *cp = '\0'; // Terminate at the suffix to remove it. } else aDynaParam.passed_by_address = false; // Using a switch benchmarks better than the old approach, which was an if-else-if ladder // of string comparisons. The old approach appeared to penalize Int64 vs. Int, perhaps due // to position in the ladder. switch (ctolower(*buf)) { case 'i': // This method currently benchmarks better than _tcsnicmp, especially for Int64. if (ctolower(buf[1]) == 'n' && ctolower(buf[2]) == 't') { if (!buf[3]) aDynaParam.type = DLL_ARG_INT; else if (buf[3] == '6' && buf[4] == '4' && !buf[5]) aDynaParam.type = DLL_ARG_INT64; else break; return; } break; case 'p': if (!_tcsicmp(buf, _T("Ptr"))) { aDynaParam.type = Exp32or64(DLL_ARG_INT, DLL_ARG_INT64); return; } break; case 's': if (!_tcsicmp(buf, _T("Str")) && !aDynaParam.is_unsigned) { aDynaParam.type = DLL_ARG_STR; return; } if (!_tcsicmp(buf, _T("Short"))) { aDynaParam.type = DLL_ARG_SHORT; return; } break; case 'd': if (!_tcsicmp(buf, _T("Double"))) { aDynaParam.type = DLL_ARG_DOUBLE; return; } break; case 'f': if (!_tcsicmp(buf, _T("Float"))) { aDynaParam.type = DLL_ARG_FLOAT; return; } break; case 'a': if (!_tcsicmp(buf, _T("AStr"))) { aDynaParam.type = DLL_ARG_ASTR; return; } break; case 'w': if (!_tcsicmp(buf, _T("WStr"))) { aDynaParam.type = DLL_ARG_WSTR; return; } break; case 'c': if (!_tcsicmp(buf, _T("Char"))) { aDynaParam.type = DLL_ARG_CHAR; return; } break; } aDynaParam.type = DLL_ARG_INVALID; } void *GetDllProcAddress(LPCTSTR aDllFileFunc, HMODULE *hmodule_to_free) // L31: Contains code extracted from BIF_DllCall for reuse in ExpressionToPostfix. { int i; void *function = NULL; TCHAR param1_buf[MAX_PATH*2], *_tfunction_name, *dll_name; // Must use MAX_PATH*2 because the function name is INSIDE the Dll file, and thus MAX_PATH can be exceeded. #ifndef UNICODE char *function_name; #endif // Define the standard libraries here. If they reside in %SYSTEMROOT%\system32 it is not // necessary to specify the full path (it wouldn't make sense anyway). static HMODULE sStdModule[] = {GetModuleHandle(_T("user32")), GetModuleHandle(_T("kernel32")) , GetModuleHandle(_T("comctl32")), GetModuleHandle(_T("gdi32"))}; // user32 is listed first for performance. static const int sStdModule_count = _countof(sStdModule); // Make a modifiable copy of param1 so that the DLL name and function name can be parsed out easily, and so that "A" or "W" can be appended if necessary (e.g. MessageBoxA): tcslcpy(param1_buf, aDllFileFunc, _countof(param1_buf) - 1); // -1 to reserve space for the "A" or "W" suffix later below. if ( !(_tfunction_name = _tcsrchr(param1_buf, '\\')) ) // No DLL name specified, so a search among standard defaults will be done. { dll_name = NULL; #ifdef UNICODE char function_name[MAX_PATH]; WideCharToMultiByte(CP_ACP, 0, param1_buf, -1, function_name, _countof(function_name), NULL, NULL); #else function_name = param1_buf; #endif // Since no DLL was specified, search for the specified function among the standard modules. for (i = 0; i < sStdModule_count; ++i) if ( sStdModule[i] && (function = (void *)GetProcAddress(sStdModule[i], function_name)) ) break; if (!function) { // Since the absence of the "A" suffix (e.g. MessageBoxA) is so common, try it that way // but only here with the standard libraries since the risk of ambiguity (calling the wrong // function) seems unacceptably high in a custom DLL. For example, a custom DLL might have // function called "AA" but not one called "A". strcat(function_name, WINAPI_SUFFIX); // 1 byte of memory was already reserved above for the 'A'. for (i = 0; i < sStdModule_count; ++i) if ( sStdModule[i] && (function = (void *)GetProcAddress(sStdModule[i], function_name)) ) break; } } else // DLL file name is explicitly present. { dll_name = param1_buf; *_tfunction_name = '\0'; // Terminate dll_name to split it off from function_name. ++_tfunction_name; // Set it to the character after the last backslash. #ifdef UNICODE char function_name[MAX_PATH]; WideCharToMultiByte(CP_ACP, 0, _tfunction_name, -1, function_name, _countof(function_name), NULL, NULL); #else function_name = _tfunction_name; #endif // Get module handle. This will work when DLL is already loaded and might improve performance if // LoadLibrary is a high-overhead call even when the library already being loaded. If // GetModuleHandle() fails, fall back to LoadLibrary(). HMODULE hmodule; if ( !(hmodule = GetModuleHandle(dll_name)) ) if ( !hmodule_to_free || !(hmodule = *hmodule_to_free = LoadLibrary(dll_name)) ) { if (hmodule_to_free) // L31: BIF_DllCall wants us to set throw. ExpressionToPostfix passes NULL. g_script.ThrowRuntimeException(_T("Failed to load DLL."), dll_name); return NULL; } if ( !(function = (void *)GetProcAddress(hmodule, function_name)) ) { // v1.0.34: If it's one of the standard libraries, try the "A" suffix. // jackieku: Try it anyway, there are many other DLLs that use this naming scheme, and it doesn't seem expensive. // If an user really cares he or she can always work around it by editing the script. //for (i = 0; i < sStdModule_count; ++i) // if (hmodule == sStdModule[i]) // Match found. // { strcat(function_name, WINAPI_SUFFIX); // 1 byte of memory was already reserved above for the 'A'. function = (void *)GetProcAddress(hmodule, function_name); // break; // } } } if (!function && hmodule_to_free) // Caller wants us to throw. { // This must be done here since only we know for certain that the dll // was loaded okay (if GetModuleHandle succeeded, nothing is passed // back to the caller). g_script.ThrowRuntimeException(ERR_NONEXISTENT_FUNCTION, _tfunction_name); } return function; } void GetDllArgObjectPtr(ResultToken &aResultToken, IObject *obj, size_t &aPtr) { if (BufferObject::IsInstanceExact(obj)) { aPtr = (size_t)((BufferObject *)obj)->Data(); return; } auto result = GetObjectPtrProperty(obj, _T("Ptr"), aPtr, aResultToken, obj->IsOfType(Object::sPrototype)); if (result != INVOKE_NOT_HANDLED) return; Object *b = (Object *)obj; if (b->GetDataPtr(aPtr) != OK) aResultToken.UnknownMemberError(ExprTokenType(obj), IT_GET, _T("Ptr")); } BIF_DECL(BIF_DllCall) // Stores a number or a SYM_STRING result in aResultToken. // Caller has set up aParam to be viewable as a left-to-right array of params rather than a stack. // It has also ensured that the array has exactly aParamCount items in it. // Author: Marcus Sonntag (Ultra) { LPTSTR function_name = NULL; void *function = NULL; // Will hold the address of the function to be called. int vf_index = -1; // Set default: not ComCall. if (_f_callee_id == FID_ComCall) { function = NULL; if (!ParamIndexIsNumeric(0)) _f_throw_param(0, _T("Integer")); vf_index = (int)ParamIndexToInt64(0); if (vf_index < 0) // But positive values aren't checked since there's no known upper bound. _f_throw_param(0); // Cheat a bit to make the second arg both the source of the virtual function // and the first parameter value (always an interface pointer): static ExprTokenType t_this_arg_type = _T("Ptr"); aParam[0] = &t_this_arg_type; } else { // Check that the mandatory first parameter (DLL+Function) is valid. // (load-time validation has ensured at least one parameter is present). switch (TypeOfToken(*aParam[0])) { case SYM_INTEGER: // Might be the most common case, due to FinalizeExpression resolving function names at load time. // v1.0.46.08: Allow script to specify the address of a function, which might be useful for // calling functions that the script discovers through unusual means such as C++ member functions. function = (void *)ParamIndexToInt64(0); // A check like the following is not present due to rarity of need and because if the address // is zero or negative, the same result will occur as for any other invalid address: // an exception code of 0xc0000005. //if ((UINT64)temp64 < 0x10000 || (UINT64)temp64 > UINTPTR_MAX) // _f_throw_param(0); // Stage 1 error: Invalid first param. //// Otherwise, assume it's a valid address: // function = (void *)temp64; break; case SYM_STRING: // For performance, don't even consider the possibility that a string like "33" is a function-address. //function = NULL; // Already set: indicates that no function has been specified yet. break; case SYM_OBJECT: // Permit an object with Ptr property. This enables DllCall or DllCall.Bind() to be used directly // as a method of an object, such as one used for wrapping a dll function. It could also have other // uses, such as resolving and memoizing function addresses on first use. __int64 n; if (!GetObjectIntProperty(ParamIndexToObject(0), _T("Ptr"), n, aResultToken)) return; function = (void *)n; break; default: // SYM_FLOAT, SYM_MISSING or (should be impossible) something else. _f_throw(ERR_PARAM1_INVALID, ErrorPrototype::Type); } if (!function) function_name = TokenToString(*aParam[0]); ++aParam; // Normalize aParam to simplify ComCall vs. DllCall. --aParamCount; } // Determine the type of return value. DYNAPARM return_attrib = {0}; // Init all to default in case ConvertDllArgType() isn't called below. This struct holds the type and other attributes of the function's return value. void* return_struct_ptr = nullptr; Object *return_class = nullptr, *return_proto = nullptr; int return_struct_size = 0; #ifdef WIN32_PLATFORM int dll_call_mode = 0; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. int struct_extra_size = 0; #endif #ifdef UNICODE #define UorA_(u, a) u #else #define UorA_(u, a) a #endif // UNICODE struct _AutoFree { HMODULE hmodule_to_free; IObject** pObj; UorA_(CStringA**, CStringW**) pStr; int nStr, nObj; ~_AutoFree() { for (int i = 0; i < nStr; ++i) if (pStr[i]) delete pStr[i]; while (nObj) if (pObj[--nObj]) pObj[nObj]->Release(); if (hmodule_to_free) FreeLibrary(hmodule_to_free); } } free_after_exit{0}; // Avoid memory leaks when _f_throw_xxx #undef UorA_ int arg_count = aParamCount/2; auto pStr = UorA(CStringA**, CStringW**)_alloca(arg_count * sizeof(void*)); // _alloca vs malloc can make a significant difference to performance in some cases. auto pObj = (IObject**)_alloca((arg_count + 1) * sizeof(IObject*)); // The complexity of combining this with pStr to reduce stack usage doesn't seem worth it. free_after_exit.pStr = pStr; free_after_exit.pObj = pObj; auto &nStr = free_after_exit.nStr; auto &nObj = free_after_exit.nObj; if ( !(aParamCount % 2) ) // An even number of parameters indicates the return type has been omitted. aParamCount excludes DllCall's first parameter at this point. { return_attrib.type = DLL_ARG_INT; if (vf_index >= 0) // Default to HRESULT for ComCall. return_attrib.is_hresult = true; // Otherwise, assume normal INT (also covers BOOL). } else { // Check validity of this arg's return type: ExprTokenType &token = *aParam[aParamCount - 1]; LPTSTR return_type_string = TokenToString(token); // If non-numeric it will return "", which is detected as invalid below. // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string, _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string = omit_leading_whitespace(return_type_string + 5); if (!*return_type_string) { // Take a shortcut since we know this empty string will be used as "Int": return_attrib.type = DLL_ARG_INT; goto has_valid_return_type; } } if (!_tcsicmp(return_type_string, _T("HRESULT"))) { return_attrib.type = DLL_ARG_INT; return_attrib.is_hresult = true; //return_attrib.is_unsigned = true; // Not relevant since an exception is thrown for any negative value. } else if (IObject *obj = TokenToObject(token)) { if (obj->IsOfType(Object::sPrototype)) { return_class = (Object*)obj; obj = return_class->GetOwnPropObj(_T("Prototype")); if (obj && obj->IsOfType(Object::sPrototype)) { return_proto = (Object*)obj; if (return_struct_size = (int)return_proto->LockStructSize()) return_attrib.type = DLL_ARG_STRUCT; } } } else { ConvertDllArgType(return_type_string, return_attrib); } if (return_attrib.type == DLL_ARG_INVALID) _f_throw_value(ERR_INVALID_RETURN_TYPE); has_valid_return_type: --aParamCount; // Remove the last parameter from further consideration. #ifdef WIN32_PLATFORM if (!return_attrib.passed_by_address) // i.e. the special return flags below are not needed when an address is being returned. { if (return_attrib.type == DLL_ARG_DOUBLE) dll_call_mode |= DC_RETVAL_MATH8; else if (return_attrib.type == DLL_ARG_FLOAT) dll_call_mode |= DC_RETVAL_MATH4; } #endif } if (return_struct_size) { aResultToken.symbol = SYM_STRING; // Set default for Invoke. aResultToken.marker = _T(""); auto obj = Object::Create(); if (obj->New(aResultToken, aParam + aParamCount, 1) != OK) return; // New releases obj on failure. return_struct_ptr = (void*)obj->DataPtr(); pObj[nObj++] = obj; aResultToken.symbol = SYM_INTEGER; // Ensure it is not SYM_OBJECT, for maintainability (in case of early exit due to an error). } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. DYNAPARM *dyna_param = arg_count ? (DYNAPARM *)_alloca(arg_count * sizeof(DYNAPARM)) : NULL; // Above: _alloca() has been checked for code-bloat and it doesn't appear to be an issue. // Above: Fix for v1.0.36.07: According to MSDN, on failure, this implementation of _alloca() generates a // stack overflow exception rather than returning a NULL value. Therefore, NULL is no longer checked, // nor is an exception block used since stack overflow in this case should be exceptionally rare (if it // does happen, it would probably mean the script or the program has a design flaw somewhere, such as // infinite recursion). LPTSTR arg_type_string; int i; // Above has already ensured that after the first parameter, there are either zero additional parameters // or an even number of them. In other words, each arg type will have an arg value to go with it. // It has also verified that the dyna_param array is large enough to hold all of the args. for (arg_count = 0, i = 0; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { // Store each arg into a dyna_param struct, using its arg type to determine how. DYNAPARM &this_dyna_param = dyna_param[arg_count]; Object *param_class = nullptr, *param_proto = nullptr; if (IObject *obj = TokenToObject(*aParam[i])) { this_dyna_param.type = DLL_ARG_INVALID; if (obj->IsOfType(Object::sPrototype)) { param_class = (Object*)obj; obj = param_class->GetOwnPropObj(_T("Prototype")); if (obj && obj->IsOfType(Object::sPrototype)) { param_proto = (Object*)obj; if (this_dyna_param.struct_size = (int)param_proto->LockStructSize()) this_dyna_param.type = DLL_ARG_STRUCT; } } } else { arg_type_string = TokenToString(*aParam[i]); // aBuf not needed since floating-point and "" are equally invalid. ConvertDllArgType(arg_type_string, this_dyna_param); } if (this_dyna_param.type == DLL_ARG_INVALID) _f_throw_value(ERR_INVALID_ARG_TYPE); IObject *this_param_obj = TokenToObject(*aParam[i + 1]); if (this_param_obj && this_dyna_param.type != DLL_ARG_STRUCT) { if ((this_dyna_param.passed_by_address || this_dyna_param.type == DLL_ARG_STR) && this_param_obj->Base() == Object::sVarRefPrototype) { aParam[i + 1] = (ExprTokenType *)_alloca(sizeof(ExprTokenType)); aParam[i + 1]->SetVarRef(static_cast<VarRef*>(this_param_obj)); this_param_obj = nullptr; } else if (ctoupper(*arg_type_string) == 'P') { // Support Buffer.Ptr, but only for "Ptr" type. All other types are reserved for possible // future use, which might be general like obj.ToValue(), or might be specific to DllCall // or the particular type of this arg (Int, Float, etc.). GetDllArgObjectPtr(aResultToken, this_param_obj, this_dyna_param.value_uintptr); if (aResultToken.Exited()) return; continue; } } ExprTokenType &this_param = *aParam[i + 1]; if (this_param.symbol == SYM_MISSING && this_dyna_param.type != DLL_ARG_STRUCT) // Permit struct classes with __value to handle unset. _f_throw(ERR_PARAM_REQUIRED); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol) || this_param_obj) { // For now, string args must be real strings rather than floats or ints. An alternative // to this would be to convert it to number using persistent memory from the caller (which // is necessary because our own stack memory should not be passed to any function since // that might cause it to return a pointer to stack memory, or update an output-parameter // to be stack memory, which would be invalid memory upon return to the caller). // The complexity of this doesn't seem worth the rarity of the need, so this will be // documented in the help file. _f_throw_type(_T("String"), this_param); } // Otherwise, it's a supported type of string. this_dyna_param.ptr = TokenToString(this_param); // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). // NOTES ABOUT THE ABOVE: // UPDATE: The v1.0.44.14 item below doesn't work in release mode, only debug mode (turning off // "string pooling" doesn't help either). So it's commented out until a way is found // to pass the address of a read-only empty string (if such a thing is possible in // release mode). Such a string should have the following properties: // 1) The first byte at its address should be '\0' so that functions can read it // and recognize it as a valid empty string. // 2) The memory address should be readable but not writable: it should throw an // access violation if the function tries to write to it (like "" does in debug mode). // SO INSTEAD of the following, DllCall() now checks further below for whether sEmptyString // has been overwritten/trashed by the call, and if so displays a warning dialog. // See note above about this: v1.0.44.14: If a variable is being passed that has no capacity, pass a // read-only memory area instead of a writable empty string. There are two big benefits to this: // 1) It forces an immediate exception (catchable by DllCall's exception handler) so // that the program doesn't crash from memory corruption later on. // 2) It avoids corrupting the program's static memory area (because sEmptyString // resides there), which can save many hours of debugging for users when the program // crashes on some seemingly unrelated line. // Of course, it's not a complete solution because it doesn't stop a script from // passing a variable whose capacity is non-zero yet too small to handle what the // function will write to it. But it's a far cry better than nothing because it's // common for a script to (unintentionally) pass an empty/uninitialized variable to // some function that writes a string to it. //if (this_dyna_param.str == Var::sEmptyString) // To improve performance, compare directly to Var::sEmptyString rather than calling Capacity(). // this_dyna_param.str = _T(""); // Make it read-only to force an exception. See comments above. break; case DLL_ARG_xSTR: // See the section above for comments. if (IS_NUMERIC(this_param.symbol) || this_param_obj) _f_throw_type(_T("String"), this_param); // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[nStr++] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = (void*)pStr[nStr-1]->GetString(); break; case DLL_ARG_DOUBLE: case DLL_ARG_FLOAT: // This currently doesn't validate that this_dyna_param.is_unsigned==false, since it seems // too rare and mostly harmless to worry about something like "Ufloat" having been specified. if (!TokenIsNumeric(this_param)) _f_throw_type(_T("Number"), this_param); this_dyna_param.value_double = TokenToDouble(this_param); if (this_dyna_param.type == DLL_ARG_FLOAT) this_dyna_param.value_float = (float)this_dyna_param.value_double; break; case DLL_ARG_STRUCT: { if (!this_param_obj || !this_param_obj->IsOfType(param_proto)) { aResultToken.symbol = SYM_STRING; // Set default for Invoke. aResultToken.marker = _T(""); auto obj = Object::Create(); if (!obj->New(aResultToken, aParam + i, 1)) return; // New releases obj on failure. pObj[nObj++] = this_param_obj = obj; aResultToken.symbol = SYM_STRING; // Set default for Invoke (New set aResultToken to obj without calling AddRef). aResultToken.marker = _T(""); auto result = obj->Invoke(aResultToken, IT_SET | IF_BYPASS_METAFUNC | IF_NO_NEW_PROPS , _T("__Value"), ExprTokenType(obj), aParam + i + 1, 1); if (result == INVOKE_NOT_HANDLED) { if (this_param.symbol == SYM_MISSING) _f_throw(ERR_PARAM_REQUIRED); auto classname = param_proto->GetOwnPropString(_T("__Class")); _f_throw_type(classname ? classname : _T("Object"), *aParam[i + 1]); } if (aResultToken.Exited()) return; aResultToken.Free(); // It shouldn't have returned anything, but it could. aResultToken.symbol = SYM_INTEGER; // Revert to the BIF default in case return type is integer, and to ensure Free() won't Release(). aResultToken.mem_to_free = nullptr; } // The parameter size is based on the struct itself, so there's little sense // in querying a Ptr property; we always want the struct's own address. this_dyna_param.value_uintptr = ((Object*)this_param_obj)->DataPtr(); int& size = this_dyna_param.struct_size; #ifdef _WIN64 this_dyna_param.type = DLL_ARG_INT64; if (size <= 8) this_dyna_param.value_int64 = *(__int64*)this_dyna_param.ptr; size = 0; #else size = (size + sizeof(void*) - 1) & -(int)sizeof(void*); if (size > 8) struct_extra_size += size - 8; else if (size > 4) { this_dyna_param.type = DLL_ARG_INT64; this_dyna_param.value_int64 = *(__int64*)this_dyna_param.ptr; size = 0; } else { this_dyna_param.type = DLL_ARG_INT; this_dyna_param.value_int = *(int*)this_dyna_param.ptr; size = 0; } #endif // _WIN64 break; } default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (!TokenIsNumeric(this_param)) _f_throw_type(_T("Number"), this_param); // Note that since v2.0-a083-97803aeb, TokenToInt64 supports conversion of large unsigned 64-bit // numbers from strings (producing a negative value, but with the right bit representation). // This allows large unsigned literals and numeric strings to be passed to DllCall (regardless // of whether Int64 or UInt64 is used), but the script itself will interpret the value as signed // if greater than _I64_MAX. Any UInt64 values returned by DllCall can be safely passed back // without loss, and can be operated upon by the bitwise operators, although arithmetic and // string conversion will treat the value as Int64. this_dyna_param.value_int64 = TokenToInt64(this_param); } // switch (this_dyna_param.type) } // for() each arg. if (vf_index >= 0) // ComCall { if ((UINT_PTR)dyna_param[0].ptr < 65536) // Basic sanity check to catch null pointers and small numbers. On Win32, the first 64KB of address space is always invalid. _f_throw_param(1); LPVOID *vftbl = *(LPVOID **)dyna_param[0].ptr; function = vftbl[vf_index]; } else if (!function) // The function's address hasn't yet been determined. { function = GetDllProcAddress(function_name, &free_after_exit.hmodule_to_free); if (!function) { // GetDllProcAddress has thrown the appropriate exception. aResultToken.SetExitResult(FAIL); return; } } //////////////////////// // Call the DLL function //////////////////////// DWORD exception_occurred; // Must not be named "exception_code" to avoid interfering with MSVC macros. DYNARESULT return_value; // Doing assignment (below) as separate step avoids compiler warning about "goto end" skipping it. #ifdef WIN32_PLATFORM DynaCall(dll_call_mode, function, dyna_param, arg_count, exception_occurred , return_struct_size ? return_struct_ptr : &return_value, return_struct_size, struct_extra_size + (return_struct_ptr ? 4 : 0)); #endif #ifdef _WIN64 DynaCall(function, dyna_param, arg_count, exception_occurred, return_struct_size ? return_struct_ptr : &return_value, return_struct_size); #endif if (*Var::sEmptyString) { // v1.0.45.01 Above has detected that a variable of zero capacity was passed to the called function // and the function wrote to it (assuming sEmptyString wasn't already trashed some other way even // before the call). So patch up the empty string to stabilize a little; but it's too late to // salvage this instance of the program because there's no knowing how much static data adjacent to // sEmptyString has been overwritten and corrupted. *Var::sEmptyString = '\0'; // Don't bother with freeing hmodule_to_free since a critical error like this calls for minimal cleanup. // The OS almost certainly frees it upon termination anyway. // Call CriticalError() so that the user knows *which* DllCall is at fault: g_script.CriticalError(_T("An invalid write to an empty variable was detected.")); // CriticalError always terminates the process. } if (g->ThrownToken || return_attrib.is_hresult && FAILED((HRESULT)return_value.Int)) { if (!g->ThrownToken) // "Error values (as defined by the FAILED macro) are never returned"; so FAIL, not FAIL_OR_OK. g_script.Win32Error((DWORD)return_value.Int, FAIL); // If a script exception was thrown by DynaCall(), it was either because the called function threw // a SEH exception or because the stdcall parameter list was the wrong size. In any of these cases, // set FAIL result to ensure control is transferred as expected (exiting the thread or TRY block). aResultToken.SetExitResult(FAIL); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. They might be of some use in debugging the // issue, though the script would have to catch the exception to be able to inspect them. } else // The call was successful. Interpret and store the return value. { // If the return value is passed by address, dereference it here. if (return_attrib.passed_by_address) { return_attrib.passed_by_address = false; // Because the address is about to be dereferenced/resolved. switch(return_attrib.type) { case DLL_ARG_INT64: case DLL_ARG_DOUBLE: #ifdef _WIN64 // fincs: pointers are 64-bit on x64. case DLL_ARG_WSTR: case DLL_ARG_ASTR: #endif // Same as next section but for eight bytes: return_value.Int64 = *(__int64 *)return_value.Pointer; break; default: // Namely: //case DLL_ARG_STR: // Even strings can be passed by address, which is equivalent to "char **". //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_FLOAT: // All the above are stored in four bytes, so a straight dereference will copy the value // over unchanged, even if it's a float. return_value.Int = *(int *)return_value.Pointer; } } #ifdef _WIN64 else { switch(return_attrib.type) { // Floating-point values are returned via the xmm0 register. Copy it for use in the next section: case DLL_ARG_FLOAT: return_value.Float = GetFloatRetval(); break; case DLL_ARG_DOUBLE: return_value.Double = GetDoubleRetval(); break; } } #endif switch(return_attrib.type) { case DLL_ARG_INT: // Listed first for performance. If the function has a void return value (formerly DLL_ARG_NONE), the value assigned here is undefined and inconsequential since the script should be designed to ignore it. ASSERT(aResultToken.symbol == SYM_INTEGER); if (return_attrib.is_unsigned) aResultToken.value_int64 = (UINT)return_value.Int; // Preserve unsigned nature upon promotion to signed 64-bit. else // Signed. aResultToken.value_int64 = return_value.Int; break; case DLL_ARG_STR: // The contents of the string returned from the function must not reside in our stack memory since // that will vanish when we return to our caller. As long as every string that went into the // function isn't on our stack (which is the case), there should be no way for what comes out to be // on the stack either. aResultToken.symbol = SYM_STRING; aResultToken.marker = (LPTSTR)(return_value.Pointer ? return_value.Pointer : _T("")); // Above: Fix for v1.0.33.01: Don't allow marker to be set to NULL, which prevents crash // with something like the following, which in this case probably happens because the inner // call produces a non-numeric string, which "int" then sees as zero, which CharLower() then // sees as NULL, which causes CharLower to return NULL rather than a real string: //result := DllCall("CharLower", "int", DllCall("CharUpper", "str", MyVar, "str"), "str") break; case DLL_ARG_xSTR: { // String needing translation: ASTR on Unicode build, WSTR on ANSI build. #ifdef UNICODE LPCSTR result = (LPCSTR)return_value.Pointer; #else LPCWSTR result = (LPCWSTR)return_value.Pointer; #endif if (result && *result) { #ifdef UNICODE // Perform the translation: CStringWCharFromChar result_buf(result); #else CStringCharFromWChar result_buf(result); #endif // Store the length of the translated string first since DetachBuffer() clears it. aResultToken.marker_length = result_buf.GetLength(); // Now attempt to take ownership of the malloc'd memory, to return to our caller. if (aResultToken.mem_to_free = result_buf.DetachBuffer()) aResultToken.marker = aResultToken.mem_to_free; else aResultToken.marker = _T(""); } else aResultToken.marker = _T(""); aResultToken.symbol = SYM_STRING; } break; case DLL_ARG_SHORT: ASSERT(aResultToken.symbol == SYM_INTEGER); if (return_attrib.is_unsigned) aResultToken.value_int64 = return_value.Int & 0x0000FFFF; // This also forces the value into the unsigned domain of a signed int. else // Signed. aResultToken.value_int64 = (SHORT)(WORD)return_value.Int; // These casts properly preserve negatives. break; case DLL_ARG_CHAR: ASSERT(aResultToken.symbol == SYM_INTEGER); if (return_attrib.is_unsigned) aResultToken.value_int64 = return_value.Int & 0x000000FF; // This also forces the value into the unsigned domain of a signed int. else // Signed. aResultToken.value_int64 = (char)(BYTE)return_value.Int; // These casts properly preserve negatives. break; case DLL_ARG_INT64: // Even for unsigned 64-bit values, it seems best both for simplicity and consistency to write // them back out to the script as signed values because script internals are not currently // equipped to handle unsigned 64-bit values. This has been documented. ASSERT(aResultToken.symbol == SYM_INTEGER); aResultToken.value_int64 = return_value.Int64; break; case DLL_ARG_FLOAT: aResultToken.symbol = SYM_FLOAT; aResultToken.value_double = return_value.Float; break; case DLL_ARG_DOUBLE: aResultToken.symbol = SYM_FLOAT; // There is no SYM_DOUBLE since all floats are stored as doubles. aResultToken.value_double = return_value.Double; break; //case DLL_ARG_STRUCT: // This case is handled once successful return is certain. // aResultToken.SetValue(pObj[0]); // break; //default: // Should never be reached unless there's a bug. // aResultToken.symbol = SYM_STRING; // aResultToken.marker = ""; } // switch(return_attrib.type) } // Storing the return value when no exception occurred. // Store any output parameters back into the input variables. This allows a function to change the // contents of a variable for the following arg types: String and Pointer to <various number types>. int nxStr = -1; for (arg_count = 0, i = 0; i < aParamCount; ++arg_count, i += 2) // Same loop as used above, so maintain them together. { ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; if (IObject * obj = TokenToObject(this_param)) // Implies the type is "Ptr" or "Ptr*". { if (this_dyna_param.passed_by_address) SetObjectIntProperty(obj, _T("Ptr"), this_dyna_param.value_int64, aResultToken); continue; } if (this_dyna_param.type == DLL_ARG_xSTR) ++nxStr; // Must be done for all args of this type in case a later arg needs its index. if (this_param.symbol != SYM_VAR) continue; Var &output_var = *this_param.var; if (!this_dyna_param.passed_by_address) { if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { // Update the variable's length and check for null termination. This could be skipped // when a naked variable (not VarRef) is passed since that's supposed to be input-only, // but seems better to do this unconditionally since the function can in fact modify // the variable's contents, and detecting buffer overrun errors seems more important // than any performance gain from skipping this. output_var.SetLengthFromContents(); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. } // Nothing is done for xSTR since 1) we didn't pass the variable's contents to the function // so its length doesn't need updating, and 2) the buffer that was passed was only as large // as the input string, so has very little practical use for output. // No other types can be output parameters when !passed_by_address. continue; } if (VARREF_IS_READ(this_param.var_usage)) continue; // Output parameters are copied back only if provided with a VarRef (&variable). ResultType result = OK; switch (this_dyna_param.type) { case DLL_ARG_INT: if (this_dyna_param.is_unsigned) result = output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. result = output_var.Assign(this_dyna_param.value_int); break; case DLL_ARG_SHORT: if (this_dyna_param.is_unsigned) // Force omission of the high-order word in case it is non-zero from a parameter that was originally and erroneously larger than a short. result = output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. result = output_var.Assign((int)(SHORT)(WORD)this_dyna_param.value_int); // These casts properly preserve negatives. break; case DLL_ARG_CHAR: if (this_dyna_param.is_unsigned) // Force omission of the high-order bits in case it is non-zero from a parameter that was originally and erroneously larger than a char. result = output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. result = output_var.Assign((int)(char)(BYTE)this_dyna_param.value_int); // These casts properly preserve negatives. break; case DLL_ARG_INT64: // Unsigned and signed are both written as signed for the reasons described elsewhere above. result = output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: result = output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: result = output_var.Assign(this_dyna_param.value_double); break; case DLL_ARG_STR: // Str* // The use of LPWSTR* vs. LPWSTR typically means the function will pass back the // address of a string, not modify the string itself. This is also consistent with // passed_by_address for all other types. However, it must be used carefully since // there's no way for Str* to know how or whether the function requires the string // to be freed (e.g. by calling CoTaskMemFree()). if (this_dyna_param.ptr != output_var.Contents(FALSE)) result = output_var.AssignString((LPTSTR)this_dyna_param.ptr); break; case DLL_ARG_xSTR: // AStr* on Unicode builds and WStr* on ANSI builds. if (this_dyna_param.ptr != pStr[nxStr]->GetString()) result = output_var.AssignStringFromCodePage(UorA(LPSTR,LPWSTR)this_dyna_param.ptr); } if (!result) { aResultToken.SetExitResult(FAIL); break; } } if (return_struct_size && !aResultToken.Exited()) { aResultToken.symbol = SYM_STRING; // Set default for Invoke. aResultToken.marker = _T(""); auto result = pObj[0]->Invoke(aResultToken, IT_GET | IF_BYPASS_METAFUNC, _T("__value"), ExprTokenType(pObj[0]), nullptr, 0); if (result == INVOKE_NOT_HANDLED) { aResultToken.SetValue(pObj[0]); pObj[0]->AddRef(); } } } #endif
50,584
C++
.cpp
1,072
43.959888
302
0.711322
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,112
script_object.h
AutoHotkey_AutoHotkey/source/script_object.h
#pragma once #include "MdType.h" #define INVOKE_TYPE (aFlags & IT_BITMASK) #define IS_INVOKE_SET (aFlags & IT_SET) #define IS_INVOKE_GET (INVOKE_TYPE == IT_GET) #define IS_INVOKE_CALL (aFlags & IT_CALL) #define INVOKE_NOT_HANDLED CONDITION_FALSE // // ObjectBase - Common base class, implements reference counting. // class DECLSPEC_NOVTABLE ObjectBase : public IObjectComCompatible { protected: ULONG mRefCount; #ifdef _WIN64 // Used by Object, but defined here on (x64 builds only) to utilize the space // that would otherwise just be padding, due to alignment requirements. UINT mFlags; #endif virtual bool Delete() { delete this; // Derived classes MUST be instantiated with 'new' or override this function. return true; // See Release() for comments. } public: ULONG STDMETHODCALLTYPE AddRef() { return ++mRefCount; } ULONG STDMETHODCALLTYPE Release() { if (mRefCount == 1) { // If an object is implemented by script, it may need to run cleanup code before the object // is deleted. This introduces the possibility that before it is deleted, the object ref // is copied to another variable (AddRef() is called). To gracefully handle this, let // implementors decide when to delete and just decrement mRefCount if it doesn't happen. if (Delete()) return 0; // Object was deleted, so cannot check or decrement --mRefCount. // If the object is implemented correctly, false was returned because: // a) mRefCount > 1; e.g. __delete has "resurrected" the object by storing a reference. // b) There are no more counted references to this object, but its lifetime is tied to // another object, which can "resurrect" this one. The other object must have some // way to delete this one when appropriate, such as by calling AddRef() & Release(). // Implementor has ensured Delete() returns false only if delete wasn't called (due to // remaining references to this), so we must assume mRefCount > 1. If Delete() really // deletes the object and (erroneously) returns false, checking if mRefCount is still // 1 may be just as unsafe as decrementing mRefCount as per usual. } return --mRefCount; } ULONG RefCount() { return mRefCount; } ObjectBase() : mRefCount(1) {} // Declare a virtual destructor for correct 'delete this' behaviour in Delete(), // and because it is likely to be more convenient and reliable than overriding // Delete(), especially with a chain of derived types. virtual ~ObjectBase() {} bool IsOfType(Object *aPrototype) override; ResultType Invoke(IObject_Invoke_PARAMS_DECL); }; // // Helpers for IObject::Invoke implementations. // typedef BuiltInFunctionType ObjectCtor; typedef void (IObject::*ObjectMethod)(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); struct ObjectMember { LPTSTR name; ObjectMethod method; UCHAR id, invokeType, minParams, maxParams; }; #define Object_Member(name, impl, id, invokeType, ...) \ { _T(#name), static_cast<ObjectMethod>(&impl), id, invokeType, __VA_ARGS__ } #define Object_Method_(name, minP, maxP, impl, id) Object_Member(name, impl, id, IT_CALL, minP, maxP) #define Object_Method(name, minP, maxP) Object_Member(name, Invoke, M_##name, IT_CALL, minP, maxP) #define Object_Method1(name, minP, maxP) Object_Member(name, name, 0, IT_CALL, minP, maxP) #define Object_Property_get(name, ...) Object_Member(name, Invoke, P_##name, IT_GET, __VA_ARGS__) #define Object_Property_get_set(name, ...) Object_Member(name, Invoke, P_##name, IT_SET, __VA_ARGS__) #define MAXP_VARIADIC 255 struct ObjectMemberMd { LPCTSTR name; void *method; UCHAR invokeType; MdType argtype[23]; }; struct ObjectMemberListType { ObjectMember *duck = nullptr; // Duck-typed members. ObjectMemberMd *meta = nullptr; // Metadata-based members. ObjectMemberListType() {} ObjectMemberListType(ObjectMember *aList) : duck(aList) {} ObjectMemberListType(ObjectMemberMd *aList) : meta(aList) {} }; // Helper for predefined classes struct ClassFactoryDef { BuiltInFunctionType call; UCHAR min_params, max_params, is_variadic; ClassFactoryDef(BuiltInFunctionType aCall, int aMin, int aMax, bool aVariadic = false) : call(aCall), min_params(aMin), max_params(aMax), is_variadic(aVariadic) {} ClassFactoryDef(BuiltInFunctionType aCall = nullptr) : ClassFactoryDef(aCall, 1, 1, true) {} }; // // FlatVector - utility class. // template <typename T, typename index_t = ::size_t> class FlatVector { struct Data { index_t size; index_t length; }; Data *data; struct OneT : public Data { char zero_buf[sizeof(T)]; }; // zero_buf guarantees zero-termination when used for strings (fixes an issue observed in debug mode). static OneT Empty; void FreeRange(index_t i, index_t count) { auto v = Value(); for (auto j = i + count; i < j; ++i) v[i].~T(); } public: FlatVector<T, index_t>() { data = &Empty; } ~FlatVector<T, index_t>() { Free(); } void Free() { if (data->size) { FreeRange(0, data->length); free(data); data = &Empty; } } bool SetCapacity(index_t new_size) { index_t length = data->length; ASSERT(new_size > 0 && new_size >= length); Data *d = data->size ? data : nullptr; if ( !(d = (Data *)realloc(d, new_size * sizeof(T) + sizeof(Data))) ) return false; data = d; data->size = new_size; data->length = length; // Only strictly necessary if NULL was passed to realloc. return true; } T *InsertUninitialized(index_t i, index_t count) { ASSERT(i >= 0 && i <= data->length && count + data->length <= data->size); auto p = Value() + i; if (i < data->length) memmove(p + count, p, (data->length - i) * sizeof(T)); data->length += count; return p; } void Remove(index_t i, index_t count) { auto v = Value(); ASSERT(i >= 0 && i + count <= data->length); FreeRange(i, count); memmove(v + i, v + i + count, (data->length - i - count) * sizeof(T)); data->length -= count; } index_t &Length() { return data->length; } index_t Capacity() { return data->size; } T *Value() { return (T *)(data + 1); } operator T *() { return Value(); } }; template <typename T, typename index_t> typename FlatVector<T, index_t>::OneT FlatVector<T, index_t>::Empty; // // Property: Invoked when a derived object gets/sets the corresponding key. // class Property { IObject *mGet = nullptr, *mSet = nullptr, *mCall = nullptr; void SetEtter(IObject *&aMemb, IObject *aFunc) { if (aFunc) aFunc->AddRef(); if (aMemb) aMemb->Release(); aMemb = aFunc; } public: // Whether the property should be skipped by OwnProps two-param mode; i.e. because it requires parameters. // Should be false if MinParams is non-zero or undetermined. bool NoEnumGet = false; // Whether to invoke the getter without parameters first, then invoke the returned value with parameters. // Should be false if MaxParams is non-zero or undetermined, or IsVariadic is true. bool NoParamSet = false, NoParamGet = false; Property() {} ~Property() { if (mGet) mGet->Release(); if (mSet) mSet->Release(); if (mCall) mCall->Release(); } IObject *Getter() { return mGet; } IObject *Setter() { return mSet; } IObject *Method() { return mCall; } void SetGetter(IObject *aFunc) { SetEtter(mGet, aFunc); } void SetSetter(IObject *aFunc) { SetEtter(mSet, aFunc); } void SetMethod(IObject *aFunc) { SetEtter(mCall, aFunc); } }; struct TypedProperty { MdType type; Object *class_object; size_t data_offset; size_t object_index; size_t item_count; ~TypedProperty(); }; // // Object - Scriptable associative array. // //#define ObjParseIntKey(s, endptr) Exp32or64(UorA(wcstol,strtol),UorA(_wcstoi64,_strtoi64))(s, endptr, 10) // Convert string to IntKeyType, setting errno = ERANGE if overflow occurs. #define ObjParseIntKey(s, endptr) UorA(_wcstoi64,_strtoi64)(s, endptr, 10) // Convert string to IntKeyType, setting errno = ERANGE if overflow occurs. class Array; class Object : public ObjectBase { public: // The type of an array element index or count. // Use unsigned to avoid the need to check for negatives. typedef UINT index_t; protected: typedef LPTSTR name_t; typedef FlatVector<TCHAR> String; struct Variant { union { // Which of its members is used depends on the value of symbol, below. __int64 n_int64; // for SYM_INTEGER double n_double; // for SYM_FLOAT IObject *object; // for SYM_OBJECT String string; // for SYM_STRING Property *prop; // for SYM_DYNAMIC TypedProperty *tprop; // SYM_TYPED_FIELD }; SymbolType symbol; // key_c contains the first character of key.s. This utilizes space that would // otherwise be unused due to 8-byte alignment. See FindField() for explanation. TCHAR key_c; bool enumerable; Variant() = delete; ~Variant() { Free(); } void Minit(); // Perform minimum initialization. bool Assign(LPTSTR str, size_t len = -1, bool exact_size = false); void AssignEmptyString(); void AssignMissing(); bool Assign(ExprTokenType &val); bool Assign(ExprTokenType *val) { return Assign(*val); } bool InitCopy(Variant &val); void ReturnRef(ResultToken &result); void ReturnMove(ResultToken &result); void Free(); inline void ToToken(ExprTokenType &aToken); // Used when we want the value as is, in a token. Does not AddRef() or copy strings. }; struct FieldType : Variant { name_t name; FieldType() = delete; ~FieldType() { free(name); } }; struct StructInfo { size_t size; size_t align; size_t nested_count; }; enum EnumeratorType { Enum_Properties, Enum_Methods }; ResultType GetEnumProp(UINT &aIndex, Var *aName, Var *aVal, int aVarCount); class PropEnum; #ifndef _WIN64 // This is defined in ObjectBase on x64 builds to save space (due to alignment requirements). UINT mFlags; #endif enum Flags : decltype(mFlags) { ClassPrototype = 0x01, NativeClassPrototype = 0x02, DataIsSetFlag = 0x04, DataIsAllocatedFlag = 0x08, DataIsStructInfo = 0x10, StructInfoLocked = 0x20, NoCallDelete = 0x40, LastObjectFlag = 0x40 }; Object *CloneTo(Object &aTo); Object() { mFlags = 0; } ~Object(); bool Delete() override; private: Object *mBase = nullptr; FlatVector<FieldType, index_t> mFields; void *mData = nullptr; Object **mNested = nullptr; FieldType *FindField(name_t name, index_t &insert_pos); FieldType *FindField(name_t name) { index_t insert_pos; return FindField(name, insert_pos); } FieldType *Insert(name_t name, index_t at); bool SetInternalCapacity(index_t new_capacity); bool Expand() // Expands mFields by at least one field. { return SetInternalCapacity(mFields.Capacity() ? mFields.Capacity() * 2 : 4); } StructInfo *GetStructInfo(bool aDefine = false); protected: ResultType GetProperty(ResultToken &aResultToken, int aFlags, name_t aName, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount); ResultType SetProperty(ResultToken &aResultToken, int aFlags, name_t aName, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount); ResultType CallProperty(ResultToken &aResultToken, int aFlags, name_t aName, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount); ResultType GetFieldValue(ResultToken &aResultToken, int aFlags, FieldType &aField, ExprTokenType &aThisToken); ResultType GetMethodValue(ResultToken &aResultToken, int aFlags, name_t aName, ExprTokenType &aThisToken); Object *GetThisForTypedValue(ResultToken &aResultToken, int aFlags, name_t aName, ExprTokenType &aThisToken); ResultType GetTypedValue(ResultToken &aResultToken, int aFlags, TypedProperty &aProp); ResultType SetTypedValue(ResultToken &aResultToken, int aFlags, name_t aName, TypedProperty &aProp, ExprTokenType &aValue); ResultType CallEtter(ResultToken &aResultToken, int aFlags, IObject *aEtter, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount); ResultType CallAsMethod(ExprTokenType &aFunc, ResultToken &aResultToken, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount); ResultType CallMeta(LPTSTR aName, ResultToken &aResultToken, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount); ResultType CallMetaVarg(int aFlags, LPTSTR aName, ResultToken &aResultToken, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount); void CallNestedDelete(); ResultType NestedNew(ResultToken &aResultToken, StructInfo *si); public: static Object *Create(); static Object *Create(ExprTokenType *aParam[], int aParamCount, ResultToken *apResultToken = nullptr); static Object *CreateStructPtr(UINT_PTR aPtr, Object *aBase, ResultToken &aResultToken); static ResultType ApplyParams(ResultToken &aThisResultToken, int aFlags, ExprTokenType *aParam[], int aParamCount); ResultType New(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount, Object *aOuter = nullptr); ResultType Construct(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType ConstructNoInit(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount, ExprTokenType &aThisToken); bool HasProp(name_t aName); bool HasMethod(name_t aName); IObject *GetMethod(name_t name); bool HasOwnProps() { return mFields.Length(); } bool HasOwnProp(name_t aName) { return FindField(aName) != nullptr; } enum class PropType { None = 0, Value, Object, Typed, DynamicValue, DynamicMethod, DynamicMixed }; PropType GetOwnPropType(name_t aName) { auto field = FindField(aName); if (!field) return PropType::None; switch (field->symbol) { case SYM_DYNAMIC: if (field->prop->Getter() || field->prop->Getter()) return field->prop->Method() ? PropType::DynamicMixed : PropType::DynamicValue; return field->prop->Method() ? PropType::DynamicMethod : PropType::None; case SYM_OBJECT: return PropType::Object; case SYM_TYPED_FIELD: return PropType::Typed; default: return PropType::Value; } } bool GetOwnProp(ExprTokenType &aToken, name_t aName) { auto field = FindField(aName); if (!field) return false; field->ToToken(aToken); return true; } LPTSTR GetOwnPropString(name_t aName) { auto field = FindField(aName); if (!field || field->symbol != SYM_STRING) return nullptr; return field->string.Value(); } __int64 GetOwnPropInt64(name_t aName) { auto field = FindField(aName); if (!field) return 0; switch (field->symbol) { case SYM_INTEGER: return field->n_int64; case SYM_FLOAT: return (__int64)field->n_double; case SYM_STRING: return ATOI(field->string); } return 0; } IObject *GetOwnPropObj(name_t aName) { auto field = FindField(aName); return field && field->symbol == SYM_OBJECT ? field->object : nullptr; } IObject *GetOwnPropMethod(name_t name) { auto field = FindField(name); return field && field->symbol == SYM_DYNAMIC ? field->prop->Method() : nullptr; } IObject *GetOwnPropGetter(name_t name) { auto field = FindField(name); return field && field->symbol == SYM_DYNAMIC ? field->prop->Getter() : nullptr; } bool SetOwnProp(name_t aName, ExprTokenType &aValue, bool aEnumerable = true) { index_t insert_pos; auto field = FindField(aName, insert_pos); if (!field && !(field = Insert(aName, insert_pos))) return false; field->enumerable = aEnumerable; return field->Assign(aValue); } bool SetOwnProp(name_t aName, __int64 aValue) { return SetOwnProp(aName, ExprTokenType(aValue)); } bool SetOwnProp(name_t aName, IObject *aValue) { return SetOwnProp(aName, ExprTokenType(aValue)); } bool SetOwnProp(name_t aName, LPCTSTR aValue) { return SetOwnProp(aName, ExprTokenType(const_cast<LPTSTR>(aValue))); } void DeleteOwnProp(name_t aName) { auto field = FindField(aName); if (field) mFields.Remove((index_t)(field - mFields), 1); } Property *DefineProperty(name_t aName, bool aEnumerable = true); TypedProperty *DefineTypedProperty(name_t aName); FResult DefineTypedProperty(name_t aName, MdType aType, Object *aClass, size_t aCount); bool DefineMethod(name_t aName, IObject *aFunc); void DefineClass(name_t aName, Object *aClass); bool CanSetBase(Object *aNewBase); ResultType SetBase(Object *aNewBase, ResultToken &aResultToken); void SetBase(Object *aNewBase) { if (aNewBase) aNewBase->AddRef(); if (mBase) mBase->Release(); mBase = aNewBase; } bool IsClassPrototype() { return mFlags & ClassPrototype; } bool IsNativeClassPrototype() { return mFlags & NativeClassPrototype; } Object *GetNativeBase(); Object *Base() { return mBase; // Callers only want to call Invoke(), so no AddRef is done. } LPTSTR Type() override; bool IsOfType(Object *aPrototype) override; bool IsDerivedFrom(IObject *aBase); // Always false for non-Object objects, but IObject* allows dynamic_cast to be avoided. void EndClassDefinition(); void RemoveMissingProperties(); ResultType Invoke(IObject_Invoke_PARAMS_DECL); static ObjectMember sMembers[]; static ObjectMember sClassMembers[]; static ObjectMember sErrorMembers[], sOSErrorMembers[]; static Object *sPrototype, *sClass, *sClassPrototype; static IObject *sObjectCall; static void CreateRootPrototypes(); static Object *CreateClass(Object *aPrototype, Object *aBase = Object::sClassPrototype); static Object *CreatePrototype(LPTSTR aClassName, Object *aBase = nullptr); static Object *CreatePrototype(LPTSTR aClassName, Object *aBase, ObjectMember aMember[], int aMemberCount); static Object *CreatePrototype(LPTSTR aClassName, Object *aBase, ObjectMemberMd aMember[], int aMemberCount); static Object *CreatePrototype(LPTSTR aClassName, Object *aBase, ObjectMemberListType aMember, int aMemberCount); static Object *DefineMembers(Object *aObject, LPTSTR aClassName, ObjectMember aMember[], int aMemberCount); static Object *DefineMetadataMembers(Object *obj, LPCTSTR aClassName, ObjectMemberMd aMember[], int aMemberCount); static Object *CreateClass(LPTSTR aClassName, Object *aBase, Object *aPrototype, ClassFactoryDef aFactory); void CallBuiltin(int aID, ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount); // Only available as functions: void GetCapacity(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void SetCapacity(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void PropCount(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void SetDataPtr(UINT_PTR aPtr); FResult GetDataPtr(UINT_PTR &aPtr); FResult AllocDataPtr(UINT_PTR aSize); #ifdef ENABLE_OBJALLOCDATA FResult FreeDataPtr(); #endif UINT_PTR DataPtr() { return (UINT_PTR)mData + ((mFlags & DataIsAllocatedFlag) ? sizeof(UINT_PTR) : 0); } UINT_PTR DataSize() { return (mFlags & DataIsAllocatedFlag) ? *(UINT_PTR*)mData : 0; } UINT_PTR StructSize() { return (mFlags & DataIsStructInfo) ? ((StructInfo*)mData)->size : mBase ? mBase->StructSize() : 0; } UINT_PTR LockStructSize() { auto si = GetStructInfo(); return si ? si->size : 0; } // Methods and functions: void DeleteProp(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void DefineProp(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void GetOwnPropDesc(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void HasOwnProp(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void OwnProps(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Props(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Clone(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void __Ref(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); enum { M_Error__New, M_OSError__New }; void Error__New(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Error_Show(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); // For pseudo-objects: static Object *sAnyPrototype, *sPrimitivePrototype, *sStringPrototype , *sNumberPrototype, *sIntegerPrototype, *sFloatPrototype; static Object *sVarRefPrototype; // For COM object wrappers: static Object *sComObjectPrototype, *sComValuePrototype, *sComArrayPrototype, *sComRefPrototype; static Object *ValueBase(ExprTokenType &aValue); static bool HasBase(ExprTokenType &aValue, IObject *aBase); static LPTSTR sMetaFuncName[]; #ifdef CONFIG_DEBUGGER void DebugWriteProperty(IDebugProperties *, int aPage, int aPageSize, int aMaxDepth); friend class Debugger; #endif }; // This has some overlap with BoundFunc, but is separate since we don't want the extra Func members. class PropRef : public ObjectBase { IObject *mThat; LPTSTR mMember; public: static Object *sPrototype; static ObjectMember sMembers[]; PropRef(IObject *that, LPTSTR member) : mThat(that), mMember(member) {} ~PropRef() { mThat->Release(); free(mMember); } IObject_Type_Impl("PropRef"); Object *Base() { return sPrototype; } void __Value(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); }; // // Array // class Array : public Object { private: Variant *mItem = nullptr; index_t mLength = 0, mCapacity = 0; ResultType SetCapacity(index_t aNewCapacity); ResultType EnsureCapacity(index_t aRequired); index_t ParamToZeroIndex(ExprTokenType &aParam); Array() {} public: enum : index_t { BadIndex = UINT_MAX, // Always >= mLength. MaxIndex = INT_MAX // This would need 32GB RAM just for mItem, assuming 16 bytes per element. Not exceeding INT_MAX might avoid some issues. }; index_t Length() { return mLength; } index_t Capacity() { return mCapacity; } ResultType SetLength(index_t aNewLength); template<typename TokenT> ResultType InsertAt(index_t aIndex, TokenT aValue[], index_t aCount); void RemoveAt(index_t aIndex, index_t aCount); bool Append(ExprTokenType &aValue); bool Append(LPCTSTR aValue, size_t aValueLength = -1) { return Append(const_cast<LPTSTR>(aValue), aValueLength); } bool Append(LPTSTR aValue, size_t aValueLength = -1) { return Append(ExprTokenType(aValue, aValueLength)); } bool Append(__int64 aValue) { return Append(ExprTokenType(aValue)); } Array *Clone(); bool ItemToToken(index_t aIndex, ExprTokenType &aToken); ResultType GetEnumItem(UINT &aIndex, Var *, Var *, int); ~Array(); static Array *Create(ExprTokenType *aValue[] = nullptr, index_t aCount = 0); static Array *FromArgV(LPTSTR *aArgV, int aArgC); static Array *FromEnumerable(ExprTokenType &aEnum); ResultType ToStrings(LPTSTR *aStrings, int &aStringCount, int aStringsMax); void ToParams(ExprTokenType *token, ExprTokenType **param_list, ExprTokenType **aParam, int aParamCount); enum MemberID { P___Item, M_Get, P_Length, P_Capacity, M_InsertAt, M_Push, M_RemoveAt, M_Pop, M_Has, M_Delete, M_Clone, M___Enum }; static ObjectMember sMembers[]; static Object *sPrototype; void Invoke(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); }; // // Map // class Map : public Object { union Key // Which of its members is used depends on the field's position in the mItem array. { LPTSTR s; IntKeyType i; IObject *p; }; struct Pair : Variant { Key key; Pair() = delete; ~Pair() = delete; }; enum MapOption : decltype(mFlags) { MapCaseless = LastObjectFlag << 1, MapUseLocale = MapCaseless << 1 }; Pair *mItem = nullptr; index_t mCount = 0, mCapacity = 0; // Holds the index of the first key of a given type within mItem. Must be in the order: int, object, string. // Compared to storing the key-type with each key-value pair, this approach saves 4 bytes per key (excluding // the 8 bytes taken by the two fields below) and speeds up lookups since only the section within mItem // with the appropriate type of key needs to be searched (and no need to check the type of each key). // mKeyOffsetObject should be set to mKeyOffsetInt + the number of int keys. // mKeyOffsetString should be set to mKeyOffsetObject + the number of object keys. // mKeyOffsetObject-1, mKeyOffsetString-1 and mFieldCount-1 indicate the last index of each prior type. static const index_t mKeyOffsetInt = 0; index_t mKeyOffsetObject = 0, mKeyOffsetString = 0; Map() {} void Clear(); ~Map() { Clear(); free(mItem); } Pair *FindItem(LPTSTR val, index_t left, index_t right, index_t &insert_pos); Pair *FindItem(IntKeyType val, index_t left, index_t right, index_t &insert_pos); Pair *FindItem(SymbolType key_type, Key key, index_t &insert_pos); Pair *FindItem(ExprTokenType &key_token, LPTSTR aBuf, SymbolType &key_type, Key &key, index_t &insert_pos); void ConvertKey(ExprTokenType &key_token, LPTSTR buf, SymbolType &key_type, Key &key); Pair *Insert(SymbolType key_type, Key key, index_t at); bool SetInternalCapacity(index_t new_capacity); // Expands mItem by at least one field. bool Expand() { return SetInternalCapacity(mCapacity ? mCapacity * 2 : 4); } Map *CloneTo(Map &aTo); ResultType GetEnumItem(UINT &aIndex, Var *, Var *, int); public: static Map *Create(ExprTokenType *aParam[] = NULL, int aParamCount = 0); bool HasItem(ExprTokenType &aKey) { return GetItem(ExprTokenType(), aKey); // Conserves code size vs. calling FindItem() directly and is unlikely to perform worse. } bool GetItem(ExprTokenType &aToken, ExprTokenType &aKey) { index_t insert_pos; TCHAR buf[MAX_NUMBER_SIZE]; SymbolType key_type; Key key; auto item = FindItem(aKey, buf, key_type, key, insert_pos); if (!item) return false; item->ToToken(aToken); return true; } bool GetItem(ExprTokenType &aToken, LPTSTR aKey) { ExprTokenType key; key.symbol = SYM_STRING; key.marker = aKey; return GetItem(aToken, key); } bool SetItem(ExprTokenType &aKey, ExprTokenType &aValue) { index_t insert_pos; TCHAR buf[MAX_NUMBER_SIZE]; SymbolType key_type; Key key; auto item = FindItem(aKey, buf, key_type, key, insert_pos); if (!item && !(item = Insert(key_type, key, insert_pos))) // Relies on short-circuit boolean evaluation. return false; return item->Assign(aValue); } bool SetItem(LPTSTR aKey, ExprTokenType &aValue) { return SetItem(ExprTokenType(aKey), aValue); } bool SetItem(LPTSTR aKey, __int64 aValue) { return SetItem(aKey, ExprTokenType(aValue)); } bool SetItem(LPTSTR aKey, IObject *aValue) { return SetItem(aKey, ExprTokenType(aValue)); } ResultType SetItems(ExprTokenType *aParam[], int aParamCount); // Methods callable by script. void __Item(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Set(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Capacity(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Count(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void CaseSense(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Clear(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Delete(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void __Enum(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Has(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); void Clone(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); static ObjectMember sMembers[]; static Object *sPrototype; }; // // RegExMatchObject: Returned by RegExMatch via UnquotedOutputVar. // class RegExMatchObject : public Object { LPTSTR mHaystack; int mHaystackStart; int *mOffset; LPTSTR *mPatternName; int mPatternCount; LPTSTR mMark; ResultType GetEnumItem(UINT &aIndex, Var *, Var *, int); RegExMatchObject() : mHaystack(NULL), mOffset(NULL), mPatternName(NULL), mPatternCount(0), mMark(NULL) {} ~RegExMatchObject() { if (mHaystack) free(mHaystack); if (mOffset) free(mOffset); if (mPatternName) { // Free the strings: for (int p = 1; p < mPatternCount; ++p) // Start at 1 since 0 never has a name. if (mPatternName[p]) free(mPatternName[p]); // Free the array: free(mPatternName); } if (mMark) free(mMark); } public: static ResultType Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark, IObject *&aNewObject); enum MemberID { M___Get, M_Value, M_Pos, M_Len, M_Name, M_Count, M_Mark, M___Enum }; static ObjectMember sMembers[]; static Object *sPrototype; void Invoke(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); }; // // Buffer // class BufferObject : public Object { private: static void *getVTable() { BufferObject sBuffer(0, 0); return *(void **)&sBuffer; } protected: void *mData; size_t mSize; BufferObject(void *aData = nullptr, size_t aSize = 0) : mData(aData), mSize(aSize) {} public: void *Data() { return mData; } size_t Size() { return mSize; } ResultType Resize(size_t aNewSize); ~BufferObject() { free(mData); } enum MemberID { P_Ptr, P_Size, M___New = P_Size, }; static ObjectMember sMembers[]; static Object *sPrototype; static BufferObject *Create(void *aData = nullptr, size_t aSize = 0); void Invoke(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); static void *sVTable; static bool IsInstanceExact(IObject *aObj) { return *(void **)aObj == sVTable; } // Benchmarked a little faster than aObj->IsOfType(BufferObject::sPrototype); }; // // ClipboardAll: Represents a blob of clipboard data (all formats retrieved from clipboard). // class ClipboardAll : public BufferObject { private: ClipboardAll() : BufferObject() {} public: static ObjectMember sMembers[]; static Object *sPrototype; static Object *Create(); void __New(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); }; void DefineComPrototypeMembers(); void DefineFileClass(); namespace ErrorPrototype { extern Object *Error, *Memory, *Type, *Value, *OS, *ZeroDivision; extern Object *Target, *Unset, *Member, *Property, *Method, *Index, *UnsetItem; extern Object *Timeout; } ResultType GetEnumerator(IObject *&aEnumerator, ExprTokenType &aEnumerable, int aVarCount, bool aDisplayError); ResultType CallEnumerator(IObject *aEnumerator, ExprTokenType *aParam[], int aParamCount, bool aDisplayError); struct NestedClassInfo { Object *class_object; bool constructed; }; BIF_DECL(Class_GetNestedClass); BIF_DECL(Class_CallNestedClass); BIF_DECL(Class_New); BIF_DECL(Any___Init); BIF_DECL(PropRef_Call);
31,172
C++
.h
823
35.413123
183
0.744276
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,113
StringConv.h
AutoHotkey_AutoHotkey/source/StringConv.h
#pragma once #ifdef _WIN32 #define IsValidUTF8(str, cch) MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, (str), (cch), NULL, 0) #define IsValidACP(str, cch) MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, (str), (cch), NULL, 0) LPCWSTR StringUTF8ToWChar(LPCSTR sUTF8, CStringW &sWChar, int iChars = -1); LPCWSTR StringCharToWChar(LPCSTR sChar, CStringW &sWChar, int iChars = -1, UINT codepage = CP_ACP); LPCSTR StringWCharToUTF8(LPCWSTR sWChar, CStringA &sUTF8, int iChars = -1); LPCSTR StringCharToUTF8(LPCSTR sChar, CStringA &sUTF8, int iChars = -1, UINT codepage = CP_ACP); LPCSTR StringWCharToChar(LPCWSTR sWChar, CStringA &sChar, int iChars = -1, char chDef = '?', UINT codepage = CP_ACP); LPCSTR StringUTF8ToChar(LPCSTR sUTF8, CStringA &sChar, int iChars = -1, char chDef = '?', UINT codepage = CP_ACP); LPCWSTR _StringDummyConvW(LPCWSTR sSrc, CStringW &sDest, int iChars = -1); LPCSTR _StringDummyConvA(LPCSTR sSrc, CStringA &sDest, int iChars = -1); #ifdef UNICODE #define StringTCharToWChar _StringDummyConvW #define StringTCharToUTF8 StringWCharToUTF8 #define StringTCharToChar StringWCharToChar inline LPCWSTR StringWCharToTChar(LPCWSTR sWChar, CStringW &sTChar, int iChars = -1, char chDef = '?') { return _StringDummyConvW(sWChar, sTChar, iChars); } inline LPCWSTR StringUTF8ToTChar(LPCSTR sUTF8, CStringW &sTChar, int iChars = -1, char chDef = '?') { return StringUTF8ToWChar(sUTF8, sTChar, iChars); } #define StringCharToTChar StringCharToWChar #else // ! _UNICODE #define StringTCharToWChar StringCharToWChar #define StringTCharToUTF8 StringCharToUTF8 #define StringTCharToChar _StringDummyConvA #define StringWCharToTChar StringWCharToChar #define StringUTF8ToTChar StringUTF8ToChar #define StringCharToTChar _StringDummyConvA #endif // _UNICODE class CStringWCharFromUTF8 : public CStringW { public: CStringWCharFromUTF8(LPCSTR sUTF8, int iChars = -1) { StringUTF8ToWChar(sUTF8, *this, iChars); } }; class CStringWCharFromChar : public CStringW { public: CStringWCharFromChar(LPCSTR sChar, int iChars = -1, UINT codepage = CP_ACP) { StringCharToWChar(sChar, *this, iChars, codepage); } }; class CStringUTF8FromWChar : public CStringA { public: CStringUTF8FromWChar(LPCWSTR sWChar, int iChars = -1) { StringWCharToUTF8(sWChar, *this, iChars); } }; class CStringUTF8FromChar : public CStringA { public: CStringUTF8FromChar(LPCSTR sChar, int iChars = -1, UINT codepage = CP_ACP) { StringCharToUTF8(sChar, *this, iChars, codepage); } }; class CStringCharFromWChar : public CStringA { public: CStringCharFromWChar(LPCWSTR sWChar, int iChars = -1, char chDef = '?', UINT codepage = CP_ACP) { StringWCharToChar(sWChar, *this, iChars, chDef, codepage); } }; class CStringCharFromUTF8 : public CStringA { public: CStringCharFromUTF8(LPCSTR sUTF8, int iChars = -1, char chDef = '?', UINT codepage = CP_ACP) { StringUTF8ToChar(sUTF8, *this, iChars, chDef, codepage); } }; #ifdef UNICODE #define CStringTCharFromWCharIfNeeded(s, ...) (s) #define CStringWCharFromTCharIfNeeded(s, ...) (s) #define CStringTCharFromCharIfNeeded(s, ...) CStringTCharFromChar((s), __VA_ARGS__) #define CStringCharFromTCharIfNeeded(s, ...) CStringCharFromTChar((s), __VA_ARGS__) class CStringTCharFromWChar : public CStringW { public: CStringTCharFromWChar(LPCWSTR sWChar, int iChars = -1, char chDef = '?') { _StringDummyConvW(sWChar, *this, iChars); } }; class CStringTCharFromUTF8 : public CStringW { public: CStringTCharFromUTF8(LPCSTR sUTF8, int iChars = -1, char chDef = '?') { StringUTF8ToWChar(sUTF8, *this, iChars); } }; typedef CStringWCharFromChar CStringTCharFromChar; typedef CStringW CStringWCharFromTChar; typedef CStringUTF8FromWChar CStringUTF8FromTChar; typedef CStringCharFromWChar CStringCharFromTChar; #else // ! _UNICODE #define CStringTCharFromWCharIfNeeded(s, ...) CStringTCharFromWChar((s), __VA_ARGS__) #define CStringWCharFromTCharIfNeeded(s, ...) CStringWCharFromTChar((s), __VA_ARGS__) #define CStringTCharFromCharIfNeeded(s, ...) (s) #define CStringCharFromTCharIfNeeded(s, ...) (s) typedef CStringCharFromWChar CStringTCharFromWChar; typedef CStringCharFromUTF8 CStringTCharFromUTF8; typedef CStringA CStringTCharFromChar; typedef CStringWCharFromChar CStringWCharFromTChar; typedef CStringUTF8FromChar CStringUTF8FromTChar; typedef CStringA CStringCharFromTChar; #endif // _UNICODE typedef CStringTCharFromWChar CStringFromWChar; typedef CStringTCharFromUTF8 CStringFromUTF8; typedef CStringTCharFromChar CStringFromChar; #endif // _WIN32 template <typename CHAR_T> void CharConvEndian(CHAR_T *pChar) { BYTE *pCh = (BYTE *) pChar, chTemp; int i, j; for (i = 0, j = sizeof(CHAR_T) - 1;i < (sizeof(CHAR_T) >> 1);i++, j--) { chTemp = pCh[i]; pCh[i] = pCh[j]; pCh[j] = chTemp; } } // uChars = 0 ==> treat 'sSrc' as NULL-terminal template <typename CHAR_T> unsigned long StringConvEndian(CHAR_T *sSrc, ULONG_PTR uChars = 0) { ULONG_PTR i; for (i = 0;sSrc[i] && (uChars == 0 || i < uChars);i++) CharConvEndian(sSrc + i); return i; }
5,014
C++
.h
124
38.983871
117
0.776978
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,116
ahkversion.h
AutoHotkey_AutoHotkey/source/ahkversion.h
#define AHK_NAME "AutoHotkey" #define T_AHK_NAME _T(AHK_NAME) #ifndef RAW_AHK_VERSION // Fallback version string for when `git describe` fails during build. #define RAW_AHK_VERSION "2.0" #endif #ifdef RC_INVOKED #define AHK_VERSION RAW_AHK_VERSION #ifndef AHK_VERSION_N #define AHK_VERSION_N 2,0,0,0 #endif #else // Use global variables rather than macros so only ahkversion.cpp needs to be recompiled // whenever GITDESC changes. extern LPSTR AHK_VERSION; extern LPTSTR T_AHK_VERSION; extern LPTSTR T_AHK_NAME_VERSION; #endif
540
C++
.h
18
28.277778
89
0.778846
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,117
hotkey.h
AutoHotkey_AutoHotkey/source/hotkey.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #ifndef hotkey_h #define hotkey_h #include "keyboard_mouse.h" #include "script.h" // For which label (and in turn which line) in the script to jump to. EXTERN_SCRIPT; // For g_script. // Due to control/alt/shift modifiers, quite a lot of hotkey combinations are possible, so support any // conceivable use. This value is used for initial sizing of the shk array, which doubles in size each // time its capacity is reached (making the need for expansion rare). #define INITIAL_MAX_HOTKEYS 256 // Note: 0xBFFF is the largest ID that can be used with RegisterHotkey(). // But further limit this to 0x7FFF (32,767) so that the highest order bit // is reserved for our other use: #define HOTKEY_KEY_UP 0x8000 #define HOTKEY_ID_MASK 0x7FFF #define HOTKEY_ID_INVALID HOTKEY_ID_MASK #define HOTKEY_ID_ALT_TAB 0x7FFE #define HOTKEY_ID_ALT_TAB_SHIFT 0x7FFD #define HOTKEY_ID_ALT_TAB_MENU 0x7FFC #define HOTKEY_ID_ALT_TAB_AND_MENU 0x7FFB #define HOTKEY_ID_ALT_TAB_MENU_DISMISS 0x7FFA #define HOTKEY_ID_MAX 0x7FF9 // 32762 hotkeys #define HOTKEY_ID_ON 0x01 // This and the next 2 are used only for convenience by ConvertAltTab(). #define HOTKEY_ID_OFF 0x02 #define HOTKEY_ID_TOGGLE 0x03 #define IS_ALT_TAB(id) (id > HOTKEY_ID_MAX && id < HOTKEY_ID_INVALID) // Below: Use double-colon as delimiter to set these apart from normal labels. // The main reason for this is that otherwise the user would have to worry // about a normal label being unintentionally valid as a hotkey, e.g. "Shift:" // might be a legitimate label that the user forgot is also a valid hotkey: #define HOTKEY_FLAG _T("::") #define HOTKEY_FLAG_LENGTH 2 #define COMPOSITE_DELIMITER _T(" & ") #define COMPOSITE_DELIMITER_LENGTH 3 // Smallest workable size: to save mem in some large arrays that use this: typedef USHORT HotkeyIDType; // This is relied upon to be unsigned; e.g. many places omit a check for ID < 0. typedef HotkeyIDType HookActionType; typedef UCHAR HotkeyTypeType; enum HotkeyTypeEnum {HK_NORMAL, HK_KEYBD_HOOK, HK_MOUSE_HOOK, HK_BOTH_HOOKS, HK_JOYSTICK}; // If above numbers are ever changed/reshuffled, update the macros below. #define HK_TYPE_CAN_BECOME_KEYBD_HOOK(type) (type == HK_NORMAL) #define HK_TYPE_IS_HOOK(type) (type > HK_NORMAL && type < HK_JOYSTICK) HWND HotCriterionAllowsFiring(HotkeyCriterion *aCriterion, LPTSTR aHotkeyName); // Used by hotkeys and hotstrings. bool HotInputLevelAllowsFiring(SendLevelType inputLevel, ULONG_PTR aEventExtraInfo, LPTSTR aKeyHistoryChar); FResult SetHotkeyCriterion(HotCriterionType aType, LPCTSTR aWinTitle, LPCTSTR aWinText, ResultToken &aResultToken); HotkeyCriterion *AddHotkeyCriterion(HotkeyCriterion *aCriterion); HotkeyCriterion *AddHotkeyCriterion(HotCriterionType aType, LPCTSTR aWinTitle, LPCTSTR aWinText); HotkeyCriterion *AddHotkeyIfExpr(); HotkeyCriterion *FindHotkeyCriterion(HotCriterionType aType, LPCTSTR aWinTitle, LPCTSTR aWinText); HotkeyCriterion *FindHotkeyIfExpr(LPCTSTR aExpr); inline int InputLevelFromInfo(ULONG_PTR aExtraInfo) { if (aExtraInfo >= KEY_IGNORE_MIN && aExtraInfo <= KEY_IGNORE_MAX) return (int)(KEY_IGNORE_LEVEL(0) - aExtraInfo); return SendLevelMax + 1; } struct HotkeyVariant { IObjectRef mCallback; IObjectPtr mOriginalCallback; // This is the callback set at load time. // Keep it to allow restoring it via hotkey() function if changed // during run time. HotkeyCriterion *mHotCriterion; HotkeyVariant *mNextVariant; DWORD mRunAgainTime; int mPriority; // Keep members that are less than 32-bit adjacent to each other to conserve memory in with the default // 4-byte alignment: USHORT mIndex; UCHAR mExistingThreads, mMaxThreads; SendLevelType mInputLevel; UCHAR mNoSuppress; // v1.0.44: This became a per-variant attribute because it's more useful/flexible that way. bool mMaxThreadsBuffer; bool mRunAgainAfterFinished; bool mEnabled; // Whether this variant has been disabled via the Hotkey command. bool mSuspendExempt; }; class Hotkey { private: // These are done as static, rather than having an outer-class to contain all the hotkeys, because // the hotkey ID is used as the array index for performance reasons. Having an outer class implies // the potential future use of more than one set of hotkeys, which could still be implemented // within static data and methods to retain the indexing/performance method: static HookType sWhichHookNeeded; static HookType sWhichHookAlways; static DWORD sTimePrev; static DWORD sTimeNow; static HotkeyIDType sNextID; bool Enable(HotkeyVariant &aVariant) // Returns true if the variant needed to be disabled, in which case caller should generally call ManifestAllHotkeysHotstringsHooks(). { if (aVariant.mEnabled) // Added for v1.0.23 to greatly improve performance when hotkey is already in the right state. return false; // Indicate that it's already enabled. aVariant.mEnabled = true; return true; } bool Disable(HotkeyVariant &aVariant) // Returns true if the variant needed to be disabled, in which case caller should generally call ManifestAllHotkeysHotstringsHooks(). { if (!aVariant.mEnabled) // Added for v1.0.23 to greatly improve performance when hotkey is already in the right state. return false; // Indicate that it's already disabled. aVariant.mEnabled = false; aVariant.mRunAgainAfterFinished = false; // ManifestAllHotkeysHotstringsHooks() won't do this unless the entire hotkey is disabled/unregistered. return true; } bool EnableParent() // Returns true if the hotkey needed to be disabled, in which case caller should generally call ManifestAllHotkeysHotstringsHooks(). { if (mParentEnabled) return false; // Indicate that it's already enabled. mParentEnabled = true; return true; } bool DisableParent() // Returns true if the hotkey needed to be disabled, in which case caller should generally call ManifestAllHotkeysHotstringsHooks(). { if (!mParentEnabled) return false; // Indicate that it's already disabled. mParentEnabled = false; return true; } ResultType Register(); ResultType Unregister(); void *operator new(size_t aBytes) {return SimpleHeap::Malloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Malloc(aBytes);} void operator delete(void *aPtr) {SimpleHeap::Delete(aPtr);} // Deletes aPtr if it was the most recently allocated. void operator delete[](void *aPtr) {SimpleHeap::Delete(aPtr);} // For now, constructor & destructor are private so that only static methods can create new // objects. This allow proper tracking of which OS hotkey IDs have been used. Hotkey(HotkeyIDType aID, IObject *aCallback, HookActionType aHookAction, LPCTSTR aName, UCHAR aNoSuppress); ~Hotkey() {if (mIsRegistered) Unregister();} public: static Hotkey **shk; static int shkMax; // 32-bit members: mod_type mModifiers; // MOD_ALT, MOD_CONTROL, MOD_SHIFT, MOD_WIN, or some additive or bitwise-or combination of these. // 16-bit members: HotkeyIDType mID; // Must be unique for each hotkey of a given thread. HookActionType mHookAction; sc_type mSC; // Scan code. All vk's have a scan code, but not vice versa. sc_type mModifierSC; // If mModifierVK is zero, this scan code, if non-zero, will be used as the modifier. HotkeyIDType mNextHotkey; // ID of the next hotkey with the same suffix as this one (initialized by the hook). // Keep single-byte attributes adjacent to each other to conserve memory within byte-aligned class/struct: modLR_type mModifiersLR; // Left-right centric versions of the above. modLR_type mModifiersConsolidatedLR; // The combination of mModifierVK, mModifierSC, mModifiersLR, modifiers vk_type mVK; // virtual-key code, e.g. VK_TAB, VK_LWIN, VK_LMENU, VK_APPS, VK_F10. If zero, use sc below. vk_type mModifierVK; // Any other virtual key that must be pressed down in order to activate "vk" itself. HotkeyTypeType mType; #define NO_SUPPRESS_PREFIX 0x01 // Bitwise: Bit #1 #define AT_LEAST_ONE_VARIANT_HAS_TILDE 0x02 // Bitwise: Bit #2 #define AT_LEAST_ONE_VARIANT_LACKS_TILDE 0x04 // Bitwise: Bit #3 #define NO_SUPPRESS_NEXT_UP_EVENT 0x08 // Bitwise: Bit #4 #define AT_LEAST_ONE_COMBO_HAS_TILDE 0x10 #define NO_SUPPRESS_SUFFIX_VARIES (AT_LEAST_ONE_VARIANT_HAS_TILDE | AT_LEAST_ONE_VARIANT_LACKS_TILDE) // i.e. a hotkey that has variants of both types. #define NO_SUPPRESS_STATES NO_SUPPRESS_NEXT_UP_EVENT // This is a bitwise union (currently only one item) of those of the above that represent a the key's dynamically changing state as the user types. UCHAR mNoSuppress; // Uses the flags above. Normally 0, but can be overridden by using the hotkey tilde (~) prefix). bool mKeybdHookMandatory; bool mAllowExtraModifiers; // False if the hotkey should not fire when extraneous modifiers are held down. bool mKeyUp; // A hotkey that should fire on key-up. bool mVK_WasSpecifiedByNumber; // A hotkey defined by something like "VK24::" or "Hotkey, VK24, ..." bool mIsRegistered; // Whether this hotkey has been successfully registered. bool mParentEnabled; // When true, the individual variants' mEnabled flags matter. When false, the entire hotkey is disabled. bool mConstructedOK; // 64- or 32-bit members: LPTSTR mName; // Points to the label name for static hotkeys, or a dynamically-allocated string for dynamic hotkeys. HotkeyVariant *mFirstVariant, *mLastVariant; // v1.0.42: Linked list of variant hotkeys created via #HotIf directives. // Make sHotkeyCount an alias for sNextID. Make it const to enforce modifying the value in only one way: static const HotkeyIDType &sHotkeyCount; static bool sJoystickHasHotkeys[MAX_JOYSTICKS]; static DWORD sJoyHotkeyCount; static void AllDestruct(); static FResult IfExpr(IObject *aExprObj); static FResult IfExpr(LPCTSTR aExpr); static FResult Dynamic(LPCTSTR aHotkeyName, LPCTSTR aOptions, IObject *aCallback, HookActionType aHookAction); static Hotkey *AddHotkey(IObject *aCallback, HookActionType aHookAction, LPCTSTR aName, UCHAR aNoSuppress); HotkeyVariant *FindVariant(); HotkeyVariant *AddVariant(IObject *aCallback, UCHAR aNoSuppress); static bool PrefixHasNoEnabledSuffixes(int aVKorSC, bool aIsSC, bool &aSuppress); HotkeyVariant *CriterionAllowsFiring(HWND *aFoundHWND = NULL, ULONG_PTR aExtraInfo = 0, LPTSTR aSingleChar = NULL); static HotkeyVariant *CriterionFiringIsCertain(HotkeyIDType &aHotkeyIDwithFlags, bool aKeyUp, ULONG_PTR aExtraInfo , bool &aFireWithNoSuppress, LPTSTR aSingleChar); static modLR_type HotkeyRequiresModLR(HotkeyIDType aHotkeyIDwithoutflags, modLR_type aModLR); static void TriggerJoyHotkeys(int aJoystickID, DWORD aButtonsNewlyDown); void PerformInNewThreadMadeByCaller(HotkeyVariant &aVariant); static void ManifestAllHotkeysHotstringsHooks(); static void RequireHook(HookType aWhichHook, bool aRequire = true) { aRequire ? sWhichHookAlways |= aWhichHook : sWhichHookAlways &= ~aWhichHook; } static void MaybeUninstallHook(); static ResultType TextInterpret(LPCTSTR aName, Hotkey *aThisHotkey, bool aSyntaxCheckOnly = false); static constexpr int KEY_NAME_BUF_SIZE = 24; // Large enough to hold the largest key name in g_key_to_vk, which is probably "Browser_Favorites" (17). struct HotkeyProperties // Struct used by TextToModifiers() and its callers. { mod_type modifiers; modLR_type modifiersLR; TCHAR prefix_text[KEY_NAME_BUF_SIZE]; TCHAR suffix_text[KEY_NAME_BUF_SIZE]; bool prefix_has_tilde; bool suffix_has_tilde; // As opposed to "prefix has tilde". bool has_asterisk; bool is_key_up; bool hook_is_mandatory; }; static LPCTSTR TextToModifiers(LPCTSTR aText, Hotkey *aThisHotkey, HotkeyProperties *aProperties = NULL); static ResultType TextToKey(LPCTSTR aText, bool aIsModifier, Hotkey *aThisHotkey, bool aSyntaxCheckOnly); static void InstallKeybdHook(); static void InstallMouseHook(); bool PerformIsAllowed(HotkeyVariant &aVariant) { // For now, attempts to launch another simultaneous instance of this subroutine // are ignored if MaxThreadsPerHotkey (for this particular hotkey) has been reached. // In the future, it might be better to have this user-configurable, i.e. to devise // some way for the hotkeys to be kept queued up so that they take effect only when // the number of currently active threads drops below the max. But doing such // might make "infinite key loops" harder to catch because the rate of incoming hotkeys // would be slowed down to prevent the subroutines from running concurrently: return aVariant.mExistingThreads < aVariant.mMaxThreads; } bool IsExemptFromSuspend() // A hotkey is considered exempt if even one of its variants is exempt. { // It's the caller's responsibility to check vp->mEnabled; that isn't done here. if (mHookAction) // An alt-tab hotkey (which overrides all its variants) is never exempt. return false; for (HotkeyVariant *vp = mFirstVariant; vp; vp = vp->mNextVariant) if (vp->mSuspendExempt) return true; // Even a single exempt variant makes the entire hotkey exempt. // Otherwise, since the above didn't find any exempt variants, the entire hotkey is non-exempt: return false; } bool IsCompletelyDisabled() { if (mHookAction) // Alt tab hotkeys are disabled completely if and only if the parent is disabled. return !mParentEnabled; for (HotkeyVariant *vp = mFirstVariant; vp; vp = vp->mNextVariant) if (vp->mEnabled) return false; return true; } static void RunAgainAfterFinished(HotkeyVariant &aVariant) { if (aVariant.mMaxThreadsBuffer) aVariant.mRunAgainAfterFinished = true; aVariant.mRunAgainTime = GetTickCount(); // Above: The time this event was buffered, to make sure it doesn't get too old. } static void ResetRunAgainAfterFinished() // For all hotkeys and all variants of each. { HotkeyVariant *vp; for (int i = 0; i < sHotkeyCount; ++i) for (vp = shk[i]->mFirstVariant; vp; vp = vp->mNextVariant) vp->mRunAgainAfterFinished = false; } static HookActionType ConvertAltTab(LPCTSTR aBuf, bool aAllowOnOff) { if (!aBuf || !*aBuf) return 0; if (!_tcsicmp(aBuf, _T("AltTab"))) return HOTKEY_ID_ALT_TAB; if (!_tcsicmp(aBuf, _T("ShiftAltTab"))) return HOTKEY_ID_ALT_TAB_SHIFT; if (!_tcsicmp(aBuf, _T("AltTabMenu"))) return HOTKEY_ID_ALT_TAB_MENU; if (!_tcsicmp(aBuf, _T("AltTabAndMenu"))) return HOTKEY_ID_ALT_TAB_AND_MENU; if (!_tcsicmp(aBuf, _T("AltTabMenuDismiss"))) return HOTKEY_ID_ALT_TAB_MENU_DISMISS; if (aAllowOnOff) { if (!_tcsicmp(aBuf, _T("On"))) return HOTKEY_ID_ON; if (!_tcsicmp(aBuf, _T("Off"))) return HOTKEY_ID_OFF; if (!_tcsicmp(aBuf, _T("Toggle"))) return HOTKEY_ID_TOGGLE; } return 0; } static Hotkey *FindHotkeyByTrueNature(LPCTSTR aName, UCHAR &aNoSuppress, bool &aHookIsMandatory); static Hotkey *FindHotkeyContainingModLR(modLR_type aModifiersLR); //, HotkeyIDType hotkey_id_to_omit); //static Hotkey *FindHotkeyWithThisModifier(vk_type aVK, sc_type aSC); //static Hotkey *FindHotkeyBySC(sc2_type aSC2, mod_type aModifiers, modLR_type aModifiersLR); static HotkeyIDType FindPairedHotkey(HotkeyIDType aFirstID, modLR_type aModsLR, bool aKeyUp); static LPTSTR ListHotkeys(LPTSTR aBuf, int aBufSize); LPTSTR ToText(LPTSTR aBuf, int aBufSize, bool aAppendNewline); private: static HotkeyVariant *CriterionFiringIsCertainHelper(HotkeyIDType &aHotkeyIDwithFlags, bool aKeyUp, UCHAR &aNoSuppress , bool &aFireWithNoSuppress, LPTSTR aSingleChar); }; /////////////////////////////////////////////////////////////////////////////////// #define MAX_HOTSTRING_LENGTH 40 // Hard to imagine a need for more than this, and most are only a few chars long. #define MAX_HOTSTRING_LENGTH_STR _T("40") // Keep in sync with the above. #define HOTSTRING_BLOCK_SIZE 1024 typedef UINT HotstringIDType; enum CaseConformModes {CASE_CONFORM_NONE, CASE_CONFORM_ALL_CAPS, CASE_CONFORM_FIRST_CAP}; class Hotstring { public: static Hotstring **shs; // An array to be allocated on first use (performs better than linked list). static HotstringIDType sHotstringCount; static HotstringIDType sHotstringCountMax; static UINT sEnabledCount; // v1.1.28.00: For performance, such as avoiding calling ToAsciiEx() in the hook. IObjectRef mCallback; LPTSTR mName; LPTSTR mString, mReplacement; HotkeyCriterion *mHotCriterion; int mPriority, mKeyDelay; // Keep members that are smaller than 32-bit adjacent with each other to conserve memory (due to 4-byte alignment). SendModes mSendMode; SendRawType mSendRaw; SendLevelType mInputLevel; UCHAR mStringLength; UCHAR mSuspended; // FALSE or a combination of one of the following: #define HS_SUSPENDED 0x01 #define HS_TURNED_OFF 0x02 #define HS_TEMPORARILY_DISABLED 0x04 UCHAR mExistingThreads, mMaxThreads; bool mCaseSensitive, mConformToCase, mDoBackspace, mOmitEndChar, mEndCharRequired , mDetectWhenInsideWord, mDoReset, mSuspendExempt, mConstructedOK; static void SuspendAll(bool aSuspend); ResultType PerformInNewThreadMadeByCaller(); void DoReplace(LPARAM alParam); static Hotstring *FindHotstring(LPCTSTR aHotstring, bool aCaseSensitive, bool aDetectWhenInsideWord, HotkeyCriterion *aHotCriterion); static ResultType AddHotstring(LPCTSTR aName, IObjectPtr aCallback, LPCTSTR aOptions, LPCTSTR aHotstring , LPCTSTR aReplacement, bool aHasContinuationSection, UCHAR aSuspend = FALSE); static void ParseOptions(LPCTSTR aOptions, int &aPriority, int &aKeyDelay, SendModes &aSendMode , bool &aCaseSensitive, bool &aConformToCase, bool &aDoBackspace, bool &aOmitEndChar, SendRawType &aSendRaw , bool &aEndCharRequired, bool &aDetectWhenInsideWord, bool &aDoReset, bool &aExecuteAction, bool &aSuspendExempt); void ParseOptions(LPCTSTR aOptions); // Constructor & destructor: Hotstring(LPCTSTR aName, IObjectPtr aCallback, LPCTSTR aOptions, LPCTSTR aHotstring, LPCTSTR aReplacement , bool aHasContinuationSection, UCHAR aSuspend); ~Hotstring() {} // Note that mReplacement is sometimes malloc'd, sometimes from SimpleHeap, and sometimes the empty string. void *operator new(size_t aBytes) {return SimpleHeap::Malloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Malloc(aBytes);} void operator delete(void *aPtr) {SimpleHeap::Delete(aPtr);} // Deletes aPtr if it was the most recently allocated. void operator delete[](void *aPtr) {SimpleHeap::Delete(aPtr);} }; #endif
19,025
C++
.h
335
54.519403
202
0.773274
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,118
MdType.h
AutoHotkey_AutoHotkey/source/MdType.h
#pragma once #include "abi.h" struct ExprTokenType; struct ResultToken; struct IObject; enum class MdType : UINT8 { Void = 0, Int8 = 1, UInt8 = 2, Int16 = 3, UInt16 = 4, Int32 = 5, UInt32 = 6, Int64 = 7, UInt64 = 8, Float64 = 9, Float32 = 10, String, Object, Variant, // Currently only for input (ExprTokenType) or retval (ResultToken). Bool32, ResultType, FResult, //NzIntWin32, // BOOL result where FALSE means failure and GetLastError() is applicable. Params, #ifdef ENABLE_MD_BITS BitsBase = 99, // For encoding a small literal value to insert into the parameter list. #endif Optional = 0x80, RetVal, Out, #ifdef ENABLE_MD_THISCALL ThisCall, // Only valid at the beginning of the args. #endif // Only aliases from here on FirstNumberType = Int8, LastNumberType = Float32, FirstIntType = Int8, LastIntType = UInt64, First64bitNumType = Int64, Last64bitNumType = Float64, FirstModifier = Optional, BitsUpperBound = Optional, UIntPtr = Exp32or64(UInt32, UInt64), IntPtr = Exp32or64(Int32, Int64) }; #define MDTYPE_NAMES nullptr, _T("i8"), _T("u8"), _T("i16"), _T("u16"), _T("i32"), _T("u32"), _T("i64"), _T("u64"), _T("f64"), _T("f32") #define MdType_IsInt(t) ((t) <= MdType::LastIntType && (t) >= MdType::FirstIntType) #define MdType_IsNum(t) ((t) <= MdType::LastNumberType && (t) >= MdType::FirstNumberType) #define MdType_Is64bit(t) ((t) >= MdType::First64bitNumType && (t) <= MdType::Last64bitNumType) #define MdType_IsMod(t) ((t) >= MdType::FirstModifier) #define MdType_IsOut(t) ((t) == MdType::Out) // Macro supports the future addition of other Out modifiers. #ifdef ENABLE_MD_BITS #define MdType_IsBits(t) ((t) >= MdType::BitsBase && (t) < MdType::BitsUpperBound) #define MdType_Bits(t) ((MdType)(static_cast<int>(t) + ((int)MdType::BitsBase + 1))) #define MdType_BitsValue(t) (static_cast<int>(t) - ((int)MdType::BitsBase + 1)) // t100 = 0 #else #define MdType_IsBits(t) false #endif template<MdType T> struct md_argtype; template<> struct md_argtype<MdType::Int8> { typedef INT8 t; }; template<> struct md_argtype<MdType::UInt8> { typedef UINT8 t; }; template<> struct md_argtype<MdType::Int16> { typedef INT16 t; }; template<> struct md_argtype<MdType::UInt16> { typedef UINT16 t; }; template<> struct md_argtype<MdType::Int32> { typedef int t; }; template<> struct md_argtype<MdType::UInt32> { typedef UINT t; }; template<> struct md_argtype<MdType::Float32> { typedef float t; }; template<> struct md_argtype<MdType::Float64> { typedef double t; }; template<> struct md_argtype<MdType::Int64> { typedef __int64 t; }; template<> struct md_argtype<MdType::UInt64> { typedef UINT64 t; }; template<> struct md_argtype<MdType::String> { typedef StrArg t; }; template<> struct md_argtype<MdType::Object> { typedef IObject *t; }; template<> struct md_argtype<MdType::Void> { typedef void t; }; template<> struct md_argtype<MdType::Variant> { typedef ExprTokenType &t; }; template<> struct md_argtype<MdType::Bool32> { typedef BOOL t; }; template<> struct md_argtype<MdType::Params> { typedef VariantParams &t; }; template<MdType T = MdType::Int32> struct md_outtype { typedef typename md_argtype<T>::t &t; }; template<> struct md_outtype<MdType::String> { typedef StrRet &t; }; template<> struct md_outtype<MdType::Variant> { typedef ResultToken &t; }; template<MdType T> struct md_optout { typedef typename md_argtype<T>::t *t; }; template<> struct md_optout<MdType::String> { typedef StrRet *t; }; template<> struct md_optout<MdType::Variant> { typedef ResultToken *t; }; template<MdType T> struct md_optional { typedef typename optl<typename md_argtype<T>::t> t; }; template<> struct md_optional<MdType::Variant> { typedef ExprTokenType *t; }; //template<MdType T> struct md_retval { typedef typename md_argtype<T>::t t; }; template<MdType T> struct md_retval { }; // All return types except those defined below are currently disabled in MdFunc. template<> struct md_retval<MdType::Void> { typedef void t; }; template<> struct md_retval<MdType::Int32> { typedef int t; }; template<> struct md_retval<MdType::UInt32> { typedef UINT t; }; template<> struct md_retval<MdType::Int64> { typedef __int64 t; }; template<> struct md_retval<MdType::UInt64> { typedef UINT64 t; }; template<> struct md_retval<MdType::Bool32> { typedef BOOL t; }; template<> struct md_retval<MdType::FResult> { typedef FResult t; }; template<> struct md_retval<MdType::ResultType> { typedef ResultType t; }; //template<> struct md_retval<MdType::NzIntWin32> { typedef BOOL t; }; #include "map.h" #define md_cat(a, ...) a ## __VA_ARGS__ #define md_arg_decl_type_In(type) md_argtype<MdType::type>::t #define md_arg_decl_type_In_Opt(type) md_optional<MdType::type>::t #define md_arg_decl_type_Out(type) md_outtype<MdType::type>::t #define md_arg_decl_type_Out_Opt(type) md_optout<MdType::type>::t #define md_arg_decl_type_Ret(type) md_arg_decl_type_Out(type) #define md_arg_decl_(mod, type, name) md_arg_decl_type_##mod(type) name #define md_arg_decl(p) md_arg_decl_ p #define md_arg_decl_type(mod, type) md_arg_decl_type_##mod(type) #define md_arg_none (In, Void, ) //#define md_opt_arg(type, name) md_optional<MdType::type>::t name //#define md_retval_StrRet StrRet aRetVal #define md_arg_data_In #define md_arg_data_In_Opt MdType::Optional, #define md_arg_data_Out MdType::Out, #define md_arg_data_Out_Opt MdType::Out, MdType::Optional, #define md_arg_data_Ret MdType::Out, MdType::RetVal, #define md_arg_data_(mod, type, name) md_arg_data_##mod MdType::type #define md_arg_data(p) md_arg_data_ p #define md_func_decl(script_name, native_name, retcode, ...) \ md_retval<MdType::retcode>::t native_name( \ MAP_LIST(md_arg_decl, __VA_ARGS__) ); // md_func_cast(...)(functionName) is used for overload resolution. #define md_func_cast(retcode, ...) \ static_cast<md_retval<MdType::retcode>::t (*)( MAP_LIST(md_arg_decl, __VA_ARGS__) )> #define md_func_data(script_name, native_name, retcode, ...) \ { \ _T(#script_name), \ md_func_cast(retcode, __VA_ARGS__)(native_name), \ MdType::retcode, \ { MAP_LIST(md_arg_data, __VA_ARGS__) } \ }, #define md_func_x(script_name, native_name, retcode, ...) \ md_cat(md_func_,md_mode)(script_name, native_name, retcode, __VA_ARGS__) #define md_func(name, ...) \ md_func_x(name, name, FResult, __VA_ARGS__) #define md_func_v(name, ...) \ md_func_x(name, name, Void, __VA_ARGS__) #ifdef __INTELLISENSE__ #undef md_func_x #define md_func_x(...) md_func_decl(__VA_ARGS__) //#define md_func_x(...) md_func_data(__VA_ARGS__) #endif // For use reinterpreting member function pointers (not standard C++). template<typename T> constexpr void* cast_into_voidp(T in) { union { T in; void *out; } u { in }; return u.out; } #define md_member_name_GET(base_name) get_##base_name #define md_member_name_SET(base_name) set_##base_name #define md_member_name_CALL(base_name) base_name // The member function pointer type can be inferred by the template, but we don't want that; // md_member_type() is used below to ensure the signature matches the metadata. #define md_member_type(class_name, ...) FResult (class_name::*)( MAP_LIST(md_arg_decl, __VA_ARGS__) ) #define md_member(class_name, member_name, invoke_type, ...) \ md_member_x(class_name, member_name, member_name, invoke_type, __VA_ARGS__) #define md_member_x(class_name, member_name, impl, invoke_type, ...) \ { _T(#member_name), \ cast_into_voidp<md_member_type(class_name, __VA_ARGS__)>(&class_name::md_cat(md_member_name_,invoke_type)(impl)), \ IT_##invoke_type, \ { MAP_LIST(md_arg_data, __VA_ARGS__) } } #define md_property_get(class_name, member_name, arg_type) \ md_member(class_name, member_name, GET, (Ret, arg_type, RetVal)) #define md_property_set(class_name, member_name, arg_type) \ md_member(class_name, member_name, SET, (In, arg_type, Value)) #define md_property(class_name, member_name, arg_type) \ md_property_get(class_name, member_name, arg_type), \ md_property_set(class_name, member_name, arg_type) void TypedPtrToToken(MdType aType, void *aPtr, ExprTokenType &aToken); ResultType SetValueOfTypeAtPtr(MdType aType, void *aPtr, ExprTokenType &aValue, ResultToken &aResultToken); size_t TypeSize(MdType aType); MdType TypeCode(LPCTSTR aName); LPCTSTR TypeName(MdType aType);
8,273
C++
.h
171
46.760234
136
0.711894
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,119
script_com.h
AutoHotkey_AutoHotkey/source/script_com.h
#pragma once extern bool g_ComErrorNotify; class ComObject; class ComEvent : public ObjectBase { DWORD mCookie = 0; ComObject *mObject; ITypeInfo *mTypeInfo = nullptr; IID mIID; IObject *mAhkObject = nullptr; ScriptModule *mModule = nullptr; TCHAR mPrefix[64]; public: STDMETHODIMP QueryInterface(REFIID riid, void **ppv); STDMETHODIMP GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); STDMETHODIMP Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); // IObject::Invoke() and Type() are unlikely to be called, since that would mean // the script has a reference to the object, which means either that the script // itself has implemented IConnectionPoint (and why would it?), or has used the // IEnumConnections interface to retrieve its own object (unlikely). //ResultType Invoke(IObject_Invoke_PARAMS_DECL); // ObjectBase::Invoke is sufficient. IObject_Type_Impl("ComEvent") // Unlikely to be called; see above. Object *Base() { return nullptr; } HRESULT Connect(ITypeInfo *tinfo = nullptr, IID *iid = nullptr); void SetPrefixOrSink(LPCTSTR pfx, IObject *ahkObject); ComEvent(ComObject *obj) : mObject(obj) { } ~ComEvent(); friend class ComObject; }; class ComObject : public ObjectBase { public: union { IDispatch *mDispatch; IUnknown *mUnknown; SAFEARRAY *mArray; void *mValPtr; __int64 mVal64; // Allow 64-bit values when ComObject is used as a VARIANT in 32-bit builds. }; ComEvent *mEventSink; VARTYPE mVarType; enum { F_OWNVALUE = 1 }; USHORT mFlags; enum { P_Ptr, // ComValueRef P___Item, // v2.0: Allows accessing a VT_BYREF value via comobj[]. P___Value = P___Item, // v2.1: Alias to allow use with VAR_VIRTUAL_OBJ (ByRef parameters). }; static ObjectMember sRefMembers[], sValueMembers[]; static ObjectMemberMd sArrayMembers[]; FResult SafeArray_Item(VariantParams &aParam, ExprTokenType *aNewValue, ResultToken *aResultToken); FResult set_SafeArray_Item(ExprTokenType &aNewValue, VariantParams &aParam) { return SafeArray_Item(aParam, &aNewValue, nullptr); } FResult get_SafeArray_Item(ResultToken &aResultToken, VariantParams &aParam) { return SafeArray_Item(aParam, nullptr, &aResultToken); } FResult SafeArray_Clone(IObject *&aRetVal); FResult SafeArray_Enum(optl<int>, IObject *&aRetVal); FResult SafeArray_MaxIndex(optl<UINT> aDims, int &aRetVal); FResult SafeArray_MinIndex(optl<UINT> aDims, int &aRetVal); ResultType Invoke(IObject_Invoke_PARAMS_DECL); void Invoke(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); LPTSTR Type(); Object *Base(); void ToVariant(VARIANT &aVar) { aVar.vt = mVarType; aVar.llVal = mVal64; // Caller handles this if needed: //if (VT_DISPATCH == mVarType && mDispatch) // mDispatch->AddRef(); } ComObject(IDispatch *pdisp) : mVal64((__int64)pdisp), mVarType(VT_DISPATCH), mEventSink(NULL), mFlags(0) { } ComObject(__int64 llVal, VARTYPE vt, USHORT flags = 0) : mVal64(llVal), mVarType(vt), mEventSink(NULL), mFlags(flags) { } ~ComObject() { if ((VT_DISPATCH == mVarType || VT_UNKNOWN == mVarType) && mUnknown) { if (mEventSink) { mEventSink->Connect(FALSE); if (mEventSink) // i.e. it wasn't fully released as a result of calling Unadvise(). mEventSink->mObject = nullptr; } mUnknown->Release(); } else if ((mVarType & (VT_BYREF|VT_ARRAY)) == VT_ARRAY && (mFlags & F_OWNVALUE)) { SafeArrayDestroy(mArray); } else if (mVarType == VT_BSTR && (mFlags & F_OWNVALUE)) { SysFreeString((BSTR)mValPtr); } } }; class ComEnum : public EnumBase { IEnumVARIANT *penum; bool cheat; public: ResultType Next(Var *aOutput, Var *aOutputType); ComEnum(IEnumVARIANT *enm); ~ComEnum() { penum->Release(); } }; class ComArrayEnum : public EnumBase { ComObject *mArrayObject; void *mData; long mLBound, mUBound; UINT mElemSize; VARTYPE mType; bool mIndexMode; long mOffset = -1; ComArrayEnum(ComObject *aObj, void *aData, long aLBound, long aUBound, UINT aElemSize, VARTYPE aType, bool aIndexMode) : mArrayObject(aObj), mData(aData), mLBound(aLBound), mUBound(aUBound), mElemSize(aElemSize), mType(aType), mIndexMode(aIndexMode) { } public: static HRESULT Begin(ComObject *aArrayObject, ComArrayEnum *&aOutput, int aMode); ResultType Next(Var *aVar1, Var *aVar2); ~ComArrayEnum(); }; // Adapts an AutoHotkey enumerator object to the IEnumVARIANT COM interface. class EnumComCompat : public IEnumVARIANT, public IServiceProvider { IObject *mEnum; int mRefCount; bool mCheat; public: EnumComCompat(IObject *enumObj) : mEnum(enumObj), mRefCount(1), mCheat(false) {} ~EnumComCompat() { mEnum->Release(); } STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); STDMETHODIMP Next(ULONG celt, /*out*/ VARIANT *rgVar, /*out*/ ULONG *pCeltFetched); STDMETHODIMP Skip(ULONG celt); STDMETHODIMP Reset(); STDMETHODIMP Clone(/*out*/ IEnumVARIANT **ppEnum); STDMETHODIMP QueryService(REFGUID guidService, REFIID riid, void **ppvObject); }; enum TTVArgType { VariantIsValue, VariantIsAllocatedString, VariantIsVarRef }; void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar, TTVArgType *aVarIsArg = FALSE); HRESULT TokenToVarType(ExprTokenType &aToken, VARTYPE aVarType, void *apValue, bool aCallerIsComValue = false); void ComError(HRESULT, ResultToken &, LPTSTR = _T(""), EXCEPINFO* = NULL); bool SafeSetTokenObject(ExprTokenType &aToken, IObject *aObject);
5,640
C++
.h
156
33.769231
164
0.753032
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,120
StrRet.h
AutoHotkey_AutoHotkey/source/StrRet.h
#pragma once #include "util.h" class StrRet { LPCTSTR mValue = nullptr; LPTSTR mCallerBuf = nullptr, mAllocated = nullptr; size_t mLength = -1; public: static constexpr size_t CallerBufSize = 256; StrRet(LPTSTR aBuf) : mCallerBuf(aBuf) {} // Allocate a buffer large enough for n characters plus a null-terminator, // and sets it as the return value. Must be called only once. LPTSTR Alloc(size_t n) { ASSERT(!mAllocated && !mValue && n); LPTSTR buf; if (n < CallerBufSize) buf = mCallerBuf; else buf = mAllocated = tmalloc(n + 1); mValue = buf; return buf; } // Set value to a copy of the string in memory that can be returned to the caller. bool Copy(LPCTSTR s, size_t n) { ASSERT(!mAllocated && !mValue); if (!n) return true; LPTSTR buf = Alloc(n); if (buf) { tmemcpy(buf, s, n); buf[n] = '\0'; } return buf; } // Set value to a copy of the string in memory that can be returned to the caller. bool Copy(LPCTSTR s) { return Copy(s, _tcslen(s)); } // Returns a buffer of size StrRet::CallerBufSize allocated by the caller for use by the callee. LPTSTR CallerBuf() { return mCallerBuf; } bool UsedMalloc() { ASSERT(!mAllocated || mAllocated == mValue); return mAllocated != nullptr; } LPCTSTR Value() { ASSERT(!mAllocated || mAllocated == mValue); return mValue; } size_t Length() { return mLength; } // Used by callee to declare that the value should be empty, for clarity and // in case the default state is ever interpreted as something other than "". void SetEmpty() { ASSERT(!mValue); } // Set the return value. // s must be in static memory, such as a literal string. void SetStatic(LPCTSTR s) { ASSERT(!mValue); mValue = s; } // Set the return value and length. // s must be in static memory, such as a literal string. void SetStatic(LPCTSTR s, size_t n) { ASSERT(!mValue); mValue = s; mLength = n; } // Set the return value. // s must be in memory that will persist until the caller has an opportunity to // copy it, such as in CallerBuf(). // Alias of SetStatic(), used to show that retaining the pointer indefinitely // wouldn't be safe. void SetTemp(LPCTSTR s) { SetStatic(s); } void SetTemp(LPCTSTR s, size_t n) { SetStatic(s, n); } // Set the length of the string which has been written into the buffer returned by Alloc(). // Calling this is optional. void SetLength(size_t n) { ASSERT(mValue); mLength = n; } };
2,482
C++
.h
103
21.601942
97
0.699407
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,121
script_module.h
AutoHotkey_AutoHotkey/source/script_module.h
#pragma once struct ScriptImport { LPTSTR names = nullptr; ScriptModule *mod = nullptr; ScriptImport *next = nullptr; LineNumberType line_number = 0; FileIndexType file_index = 0; ScriptImport() {} ScriptImport(ScriptModule *aMod) : mod(aMod), names(_T("*")) {} void *operator new(size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void operator delete(void *aPtr) {} void operator delete[](void *aPtr) {} }; class ScriptModule : public ObjectBase { public: LPCTSTR mName = nullptr; Line *mFirstLine = nullptr; Label *mFirstLabel = nullptr; ScriptImport *mImports = nullptr; ScriptModule *mPrev = nullptr; VarList mVars; Var *mSelf = nullptr; UnresolvedBaseClass *mUnresolvedBaseClass = nullptr; FileIndexType *mFiles = nullptr, mFilesCount = 0, mFilesCountMax = 0; bool mExecuted = false; bool mIsBuiltinModule = false; // #Warn settings WarnMode Warn_LocalSameAsGlobal = WARNMODE_OFF; WarnMode Warn_Unreachable = WARNMODE_ON; WarnMode Warn_VarUnset = WARNMODE_ON; bool HasFileIndex(FileIndexType aFile); ResultType AddFileIndex(FileIndexType aFile); IObject *FindGlobalObject(LPCTSTR aName); ScriptModule() {} ScriptModule(LPCTSTR aName) : mName(aName) {} void *operator new(size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void operator delete(void *aPtr) {} void operator delete[](void *aPtr) {} IObject_Type_Impl("Module"); ResultType Invoke(IObject_Invoke_PARAMS_DECL) override; Object *Base() override { return sPrototype; } static Object *sPrototype; }; typedef ScriptItemList<ScriptModule, 16> ScriptModuleList;
1,719
C++
.h
48
33.729167
72
0.768999
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,123
globaldata.h
AutoHotkey_AutoHotkey/source/globaldata.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #ifndef globaldata_h #define globaldata_h #include "hook.h" // For KeyHistoryItem and probably other things. #include "clipboard.h" // For the global clipboard object #include "script.h" // For the global script object #include "os_version.h" // For the global OS_Version object #include "Debugger.h" extern HINSTANCE g_hInstance; extern DWORD g_MainThreadID; extern DWORD g_HookThreadID; extern CRITICAL_SECTION g_CriticalRegExCache; extern UINT g_DefaultScriptCodepage; extern bool g_DestroyWindowCalled; extern HWND g_hWnd; // The main window extern HWND g_hWndEdit; // The edit window, child of main. extern HFONT g_hFontEdit; extern HACCEL g_hAccelTable; // Accelerator table for main menu shortcut keys. extern MSG *g_CalledByIsDialogMessageOrDispatch; // Helps avoid launching a monitor function twice for the same message. typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); extern StrCmpLogicalW_type g_StrCmpLogicalW; extern WNDPROC g_TabClassProc; extern modLR_type g_modifiersLR_logical; // Tracked by hook (if hook is active). extern modLR_type g_modifiersLR_logical_non_ignored; extern modLR_type g_modifiersLR_physical; // Same as above except it's which modifiers are PHYSICALLY down. extern modLR_type g_modifiersLR_numpad_mask; // Shift keys temporarily released by Numpad. extern modLR_type g_modifiersLR_ctrlaltdel_mask; // For excluding AltGr from Ctrl+Alt+Del handling. extern modLR_type g_modifiersLR_last_pressed; extern DWORD g_modifiersLR_last_pressed_time; extern key_type *pPrefixKey; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL extern WORD g_mouse_buttons_logical; // A bitwise combination of MK_LBUTTON, etc. #endif #define STATE_DOWN 0x80 #define STATE_ON 0x01 extern BYTE g_PhysicalKeyState[VK_ARRAY_COUNT]; extern bool g_BlockWinKeys; extern DWORD g_AltGrExtraInfo; extern BYTE g_MenuMaskKeyVK; // For #MenuMaskKey. extern USHORT g_MenuMaskKeySC; // If a SendKeys() operation takes longer than this, hotkey's modifiers won't be pressed back down: extern int g_HotkeyModifierTimeout; extern int g_ClipboardTimeout; extern HHOOK g_KeybdHook; extern HHOOK g_MouseHook; extern HHOOK g_PlaybackHook; extern bool g_ForceLaunch; extern bool g_WinActivateForce; extern WarnMode g_WarnMode; extern SingleInstanceType g_AllowOnlyOneInstance; extern bool g_persistent; extern bool g_NoTrayIcon; extern bool g_AllowMainWindow; extern bool g_DeferMessagesForUnderlyingPump; extern bool g_MainTimerExists; extern bool g_InputTimerExists; extern bool g_DerefTimerExists; extern bool g_SoundWasPlayed; extern bool g_IsSuspended; extern bool g_OnExitIsRunning; extern BOOL g_AllowInterruption; extern int g_nLayersNeedingTimer; extern int g_nThreads; extern int g_nPausedThreads; extern int g_MaxHistoryKeys; extern DWORD g_InputTimeoutAt; extern UCHAR g_MaxThreadsPerHotkey; extern int g_MaxThreadsTotal; extern UINT g_MaxHotkeysPerInterval; extern UINT g_HotkeyThrottleInterval; extern bool g_MaxThreadsBuffer; extern bool g_SuspendExempt; extern bool g_SuspendExemptHS; extern SendLevelType g_InputLevel; extern HotkeyCriterion *g_FirstHotCriterion, *g_LastHotCriterion; // Global variables for #HotIf (expression). See globaldata.cpp for comments. extern UINT g_HotExprTimeout; extern HWND g_HotExprLFW; extern HotkeyCriterion *g_FirstHotExpr, *g_LastHotExpr; extern int g_ScreenDPI; extern bool g_MenuIsVisible; extern HMENU g_MenuIsTempModeless; extern bool g_MenuIsTempTopmost; extern int g_nMessageBoxes; extern int g_nFileDialogs; extern int g_nFolderDialogs; extern GuiType *g_firstGui, *g_lastGui; extern HWND g_hWndToolTip[MAX_TOOLTIPS]; extern MsgMonitorList g_MsgMonitor; extern UCHAR g_SortCaseSensitive; extern bool g_SortNumeric; extern bool g_SortReverse; extern int g_SortColumnOffset; extern IObject *g_SortFunc; extern ResultType g_SortFuncResult; #define g_DerefChar '%' // As of v2 these are constant, so even more parts of the code assume they #define g_EscapeChar '`' // are at their usual default values to reduce code size/complexity. #define g_delimiter ',' // Also, g_delimiter was never used in expressions (i.e. for SYM_COMMA). #define g_CommentChar ';' // Hot-string vars: extern TCHAR g_HSBuf[HS_BUF_SIZE]; extern int g_HSBufLength; extern HWND g_HShwnd; // Hot-string global settings: extern int g_HSPriority; extern int g_HSKeyDelay; extern SendModes g_HSSendMode; extern SendRawType g_HSSendRaw; extern bool g_HSCaseSensitive; extern bool g_HSConformToCase; extern bool g_HSDoBackspace; extern bool g_HSOmitEndChar; extern bool g_HSEndCharRequired; extern bool g_HSDetectWhenInsideWord; extern bool g_HSDoReset; extern bool g_HSResetUponMouseClick; extern bool g_HSSameLineAction; extern TCHAR g_EndChars[HS_MAX_END_CHARS + 1]; // Global objects: extern input_type *g_input; extern int g_inputBeforeHotkeysCount; EXTERN_SCRIPT; EXTERN_CLIPBOARD; EXTERN_OSVER; extern HICON g_IconSmall; extern HICON g_IconLarge; EXTERN_G; extern global_struct *g_array; #define g_default g_array[0] extern CString g_WorkingDir; extern LPTSTR g_WorkingDirOrig; extern bool g_ForceKeybdHook; extern ToggleValueType g_ForceNumLock; extern ToggleValueType g_ForceCapsLock; extern ToggleValueType g_ForceScrollLock; extern ToggleValueType g_BlockInputMode; extern bool g_BlockInput; // Whether input blocking is currently enabled. extern bool g_BlockMouseMove; // Whether physical mouse movement is currently blocked via the mouse hook. extern Action g_act[]; extern int g_ActionCount; extern Action g_old_act[]; extern int g_OldActionCount; extern key_to_vk_type g_key_to_vk[]; extern key_to_sc_type g_key_to_sc[]; extern int g_key_to_vk_count; extern int g_key_to_sc_count; extern KeyHistoryItem *g_KeyHistory; extern int g_KeyHistoryNext; extern DWORD g_HistoryTickNow; extern DWORD g_HistoryTickPrev; extern HWND g_HistoryHwndPrev; extern DWORD g_TimeLastInputPhysical; extern DWORD g_TimeLastInputKeyboard; extern DWORD g_TimeLastInputMouse; // 9 might be better than 10 because if the granularity/timer is a little // off on certain systems, a Sleep(10) might really result in a Sleep(20), // whereas a Sleep(9) is almost certainly a Sleep(10) on OS's such as // NT/2k/XP. UPDATE: Roundoff issues with scripts having // even multiples of 10 in them, such as "Sleep,300", shouldn't be hurt // by this because they use GetTickCount() to verify how long the // sleep duration actually was. UPDATE again: Decided to go back to 10 // because I'm pretty confident that that always sleeps 10 on NT/2k/XP // unless the system is under load, in which case any Sleep between 0 // and 20 inclusive seems to sleep for exactly(?) one timeslice. // A timeslice appears to be 20ms in duration. Anyway, using 10 // allows "SetKeyDelay, 10" to be really 10 rather than getting // rounded up to 20 due to doing first a Sleep(10) and then a Sleep(1). // For now, I'm avoiding using timeBeginPeriod to improve the resolution // of Sleep() because of possible incompatibilities on some systems, // and also because it may degrade overall system performance. // UPDATE: Will get rounded up to 10 anyway by SetTimer(). However, // future OSs might support timer intervals of less than 10. #define SLEEP_INTERVAL 10 #define SLEEP_INTERVAL_HALF (int)(SLEEP_INTERVAL / 2) enum OurTimers {TIMER_ID_MAIN = MAX_MSGBOXES + 2 // The first timers in the series are used by the MessageBoxes. Start at +2 to give an extra margin of safety. , TIMER_ID_UNINTERRUPTIBLE // Obsolete but kept as a a placeholder for backward compatibility, so that this and the other the timer-ID's stay the same, and so that obsolete IDs aren't reused for new things (in case anyone is interfacing these OnMessage() or with external applications). , TIMER_ID_AUTOEXEC, TIMER_ID_INPUT, TIMER_ID_DEREF, TIMER_ID_REFRESH_INTERRUPTIBILITY}; // MUST MAKE main timer and uninterruptible timers associated with our main window so that // MainWindowProc() will be able to process them when it is called by the DispatchMessage() // of a non-standard message pump such as MessageBox(). In other words, don't let the fact // that the script is displaying a dialog interfere with the timely receipt and processing // of the WM_TIMER messages, including those "hidden messages" which cause DefWindowProc() // (I think) to call the TimerProc() of timers that use that method. // Realistically, SetTimer() called this way should never fail? But the event loop can't // function properly without it, at least when there are suspended subroutines. // MSDN docs for SetTimer(): "Windows 2000/XP: If uElapse is less than 10, // the timeout is set to 10." TO GET CONSISTENT RESULTS across all operating systems, // it may be necessary never to pass an uElapse parameter outside the range USER_TIMER_MINIMUM // (0xA) to USER_TIMER_MAXIMUM (0x7FFFFFFF). #define SET_MAIN_TIMER \ if (!g_MainTimerExists)\ g_MainTimerExists = SetTimer(g_hWnd, TIMER_ID_MAIN, SLEEP_INTERVAL, (TIMERPROC)NULL); // v1.0.39 for above: Apparently, one of the few times SetTimer fails is after the thread has done // PostQuitMessage. That particular failure was causing an unwanted recursive call to ExitApp(), // which is why the above no longer calls ExitApp on failure. Here's the sequence: // Someone called ExitApp (such as the max-hotkeys-per-interval warning dialog). // ExitApp() removes the hooks. // The hook-removal function calls MsgSleep() while waiting for the hook-thread to finish. // MsgSleep attempts to set the main timer so that it can judge how long to wait. // The timer fails and calls ExitApp even though a previous call to ExitApp is currently underway. // See AutoExecSectionTimeout() for why g->AllowThreadToBeInterrupted is used rather than the other var. // The below also sets g->ThreadStartTime and g->UninterruptibleDuration. Notes about this: // In case the AutoExecute section takes a long time (or never completes), allow interruptions // such as hotkeys and timed subroutines after a short time. Use g->AllowThreadToBeInterrupted // vs. g_AllowInterruption in case commands in the AutoExecute section need exclusive use of // g_AllowInterruption (i.e. they might change its value to false and then back to true, // which would interfere with our use of that var). // From MSDN: "When you specify a TimerProc callback function, the default window procedure calls the // callback function when it processes WM_TIMER. Therefore, you need to dispatch messages in the calling thread, // even when you use TimerProc instead of processing WM_TIMER." My: This is why all TimerProc type timers // should probably have an associated window rather than passing NULL as first param of SetTimer(). // // UPDATE v1.0.48: g->ThreadStartTime and g->UninterruptibleDuration were added so that IsInterruptible() // won't make the AutoExec section interruptible prematurely. In prior versions, KILL_AUTOEXEC_TIMER() did this, // but with the new IsInterruptible() function, doing it in KILL_AUTOEXEC_TIMER() wouldn't be reliable because // it might already have been done by IsInterruptible() [or vice versa], which might provide a window of // opportunity in which any use of Critical by the AutoExec section would be undone by the second timeout. // More info: Since AutoExecSection() never calls InitNewThread(), it never used to set the uninterruptible // timer. Instead, it had its own timer. But now that IsInterruptible() checks for the timeout of // "Thread Interrupt", AutoExec might become interruptible prematurely unless it uses the new method below. // // v2.0: There's no longer an AutoExec timer, so this just sets the uninterruptible duration. #define SET_AUTOEXEC_TIMER(aTimeoutValue) \ {\ g->AllowThreadToBeInterrupted = false;\ g->ThreadStartTime = GetTickCount();\ g->UninterruptibleDuration = aTimeoutValue;\ } #define SET_INPUT_TIMER(aTimeoutValue, aTimeoutAt) \ { \ g_InputTimeoutAt = aTimeoutAt; \ g_InputTimerExists = SetTimer(g_hWnd, TIMER_ID_INPUT, aTimeoutValue, InputTimeout); \ } // For this one, SetTimer() is called unconditionally because our caller wants the timer reset // (as though it were killed and recreated) unconditionally. MSDN's comments are a little vague // about this, but testing shows that calling SetTimer() against an existing timer does completely // reset it as though it were killed and recreated. Note also that g_hWnd is used vs. NULL so that // the timer will fire even when a msg pump other than our own is running, such as that of a MsgBox. #define SET_DEREF_TIMER(aTimeoutValue) g_DerefTimerExists = SetTimer(g_hWnd, TIMER_ID_DEREF, aTimeoutValue, DerefTimeout); #define LARGE_DEREF_BUF_SIZE (4*1024*1024) #define KILL_MAIN_TIMER \ if (g_MainTimerExists && KillTimer(g_hWnd, TIMER_ID_MAIN))\ g_MainTimerExists = false; #define KILL_INPUT_TIMER \ if (g_InputTimerExists && KillTimer(g_hWnd, TIMER_ID_INPUT))\ g_InputTimerExists = false; #define KILL_DEREF_TIMER \ if (g_DerefTimerExists && KillTimer(g_hWnd, TIMER_ID_DEREF))\ g_DerefTimerExists = false; #endif
13,511
C++
.h
261
50.547893
287
0.799879
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,124
os_version.h
AutoHotkey_AutoHotkey/source/os_version.h
#ifndef __OS_VERSION_H #define __OS_VERSION_H /////////////////////////////////////////////////////////////////////////////// // // AutoIt // // Copyright (C)1999-2003: // - Jonathan Bennett <jon@hiddensoft.com> // - Others listed at http://www.autoitscript.com/autoit3/docs/credits.htm // // This program 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 2 of the License, or // (at your option) any later version. // /////////////////////////////////////////////////////////////////////////////// // // os_version.h // // A standalone class for easy checking of the OS version. // /////////////////////////////////////////////////////////////////////////////// // Includes #include <windows.h> class OS_Version { public: // Functions OS_Version() { Init(); } // Constructor void Init(void); // Call first before use bool IsWinVista(void) {return m_bWinVista;} // Returns true if WinVista (v1.0.44.13) bool IsWin7(void) {return m_bWin7; } // Returns true if Win7 bool IsWin8(void) {return m_bWin8; } // Returns true if Win8 bool IsWin8orLater() {return m_dwMajorVersion > 6 || m_dwMinorVersion > 1;} bool IsWin8_1(void) {return m_bWin8_1; } // Returns true if Win8.1 bool IsWin7OrLater(void) {return m_bWin7OrLater; } // Returns true if Win7+ bool IsWin10OrLater(void) {return m_dwMajorVersion >= 10;} // Excludes early pre-release builds. DWORD BuildNumber(void) {return m_dwBuildNumber;} //LPCTSTR CSD(void) {return m_szCSDVersion;} LPCTSTR Version() {return m_szVersion;} private: // Variables OSVERSIONINFOW m_OSvi; // OS Version data DWORD m_dwMajorVersion; // Major OS version DWORD m_dwMinorVersion; // Minor OS version DWORD m_dwBuildNumber; // Build number //TCHAR m_szCSDVersion[128]; TCHAR m_szVersion[32]; // "Major.Minor.Build" -- longest known number is 9 chars (plus terminator), but 32 should be future-proof. #ifdef CONFIG_WIN9X bool m_bWinNT; bool m_bWin9x; bool m_bWin95; bool m_bWin95orLater; bool m_bWin98; bool m_bWin98orLater; bool m_bWinMe; bool m_bWinMeorLater; #endif #ifdef CONFIG_WINNT4 bool m_bWinNT4; bool m_bWinNT4orLater; #endif #ifdef CONFIG_WIN2K bool m_bWin2000; bool m_bWin2000orLater; // For simplicity, this is always left in even though it is not used when !(CONFIG_WIN9X || CONFIG_WINNT4). bool m_bWinXPorLater; #endif bool m_bWinXP; bool m_bWin2003; bool m_bWinVista; bool m_bWinVistaOrLater; bool m_bWin7; bool m_bWin7OrLater; bool m_bWin8; bool m_bWin8_1; }; /////////////////////////////////////////////////////////////////////////////// #endif
2,776
C++
.h
78
33.858974
135
0.629754
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,125
var.h
AutoHotkey_AutoHotkey/source/var.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #ifndef var_h #define var_h #include "defines.h" #include "SimpleHeap.h" #include "clipboard.h" #include "util.h" // for strlcpy() & snprintf() EXTERN_CLIPBOARD; #define MAX_ALLOC_SIMPLE 64 // Do not decrease this much since it is used for the sizing of some built-in variables. #define SMALL_STRING_LENGTH (MAX_ALLOC_SIMPLE - 1) // The largest string that can fit in the above. #define DEREF_BUF_EXPAND_INCREMENT (16 * 1024) // Reduced from 32 to 16 in v1.0.46.07 to reduce the memory utilization of deeply recursive UDFs. enum AllocMethod {ALLOC_NONE, ALLOC_SIMPLE, ALLOC_MALLOC, ALLOC_DISABLED}; enum VarTypes { // The following must all be LOW numbers to avoid any realistic chance of them matching the address of // any function (namely a BIV_* function). VAR_ALIAS // VAR_ALIAS must always have a non-NULL mAliasFor. In other ways it's the same as VAR_NORMAL. VAR_ALIAS is never seen because external users call Var::Type(), which automatically resolves ALIAS to some other type. , VAR_NORMAL // Most variables, such as those created by the user, are this type. , VAR_CONSTANT // or as I like to say, not variable. , VAR_VIRTUAL , VAR_VIRTUAL_OBJ // If adding to this enum, ensure range checks and VAR_LAST_TYPE remain valid. , VAR_LAST_TYPE = VAR_VIRTUAL_OBJ }; // Returns true if the given var type should be evaluated by calling Var::Get(ResultToken&). inline bool VarTypeIsVirtual(int type) { return type >= VAR_VIRTUAL; } typedef UCHAR VarTypeType; // UCHAR vs. VarTypes to save memory. typedef UCHAR AllocMethodType; // UCHAR vs. AllocMethod to save memory. typedef UCHAR VarAttribType; // Same. typedef UINT_PTR VarSizeType; // jackieku(2009-10-23): Change this to UINT_PTR to ensure its size is the same with a pointer. #define VARSIZE_MAX ((VarSizeType) ~0) #define VARSIZE_ERROR VARSIZE_MAX class Var; // Forward declaration. // #pragma pack(4) not used here because although it would currently save 4 bytes per VarBkp struct (28 vs. 32), // it would probably reduce performance since VarBkp items are stored in contiguous array rather than a // linked list (which would cause every other struct in the array to have an 8-byte member than stretches // across two 8-byte regions in memory). struct VarBkp // This should be kept in sync with any changes to the Var class. See Var for comments. { union { __int64 mContentsInt64; // 64-bit members kept at the top of the struct to reduce the chance that they'll span 2 vs. 1 64-bit regions. double mContentsDouble; IObject *mObject; }; Var *mVar; // Used to save the target var to which these backed up contents will later be restored. union { char *mByteContents; TCHAR *mCharContents; }; union { VarSizeType mByteLength; Var *mAliasFor; }; VarSizeType mByteCapacity; AllocMethodType mHowAllocated; VarAttribType mAttrib; VarTypeType mType; // Not needed in the backup: //bool mIsLocal; //TCHAR *mName; void ToToken(ExprTokenType &aValue); }; #define BIV_DECL_R(name) void name(ResultToken &aResultToken, LPTSTR aVarName) #define BIV_DECL_W(name) void name(ResultToken &aResultToken, LPTSTR aVarName, ExprTokenType &aValue) #define BIV_DECL_RW(name) BIV_DECL_R(name); BIV_DECL_W(name##_Set) struct VirtualVar { typedef BIV_DECL_R((* Getter)); typedef BIV_DECL_W((* Setter)); Getter Get; Setter Set; }; struct VarEntry { LPTSTR name; VirtualVar type; }; class VarRef; #pragma warning(push) #pragma warning(disable: 4995 4996) // Concerning "#pragma pack" below: // Default pack would otherwise be 8, which would cause the 64-bit mContentsInt64 member to increase the size // of the struct from 20 to 32 (instead of 28). Benchmarking indicates that there's no significant performance // loss from doing this, perhaps because variables are currently stored in a linked list rather than an // array. (In an array, having the struct size be a multiple of 8 would prevent every other struct in the array // from having its 64-bit members span more than one 64-bit region in memory, which might reduce performance.) #ifdef _WIN64 #pragma pack(push, 8) #else #pragma pack(push, 4) // 32-bit vs. 64-bit. See above. #endif class Var { private: // Keep VarBkp (above) in sync with any changes made to the members here. union // 64-bit members kept at the top of the struct to reduce the chance that they'll span 2 64-bit regions. { // Although the 8-byte members mContentsInt64 and mContentsDouble could be hung onto the struct // via a 4-byte-pointer, thus saving 4 bytes for each variable that never uses a binary number, // it doesn't seem worth it because the percentage of variables in typical scripts that will // acquire a cached binary number at some point seems likely to be high. A percentage of only // 50% would be enough to negate the savings because half the variables would consume 12 bytes // more than the version of AutoHotkey that has no binary-number caching, and the other half // would consume 4 more (due to the unused/empty pointer). That would be an average of 8 bytes // extra; i.e. exactly the same as the 8 bytes used by putting the numbers directly into the struct. // In addition, there are the following advantages: // 1) Code less complicated, more maintainable, faster. // 2) Caching of binary numbers works even in recursive script functions. By contrast, if the // binary number were allocated on demand, recursive functions couldn't use caching because the // memory from SimpleHeap could never be freed, thus producing a memory leak. // The main drawback is that some scripts are known to create a million variables or more, so the // extra 8 bytes per variable would increase memory load by 8+ MB (possibly with a boost in // performance if those variables are ever numeric). __int64 mContentsInt64; double mContentsDouble; IObject *mObject; // L31 VirtualVar *mVV; // VAR_VIRTUAL }; union { LPTSTR mCharContents = sEmptyString; // Invariant: Anyone setting mByteCapacity to 0 must also set mCharContents to the empty string. char *mByteContents; }; union { Var *mAliasFor = nullptr; // The variable for which this variable is an alias. VarSizeType mByteLength; // How much is actually stored in it currently, excluding the zero terminator. }; VarSizeType mByteCapacity = 0; // In bytes. Includes the space for the zero terminator. AllocMethodType mHowAllocated = ALLOC_NONE; // Keep adjacent/contiguous with the below to save memory. #define VAR_ATTRIB_CONTENTS_OUT_OF_DATE 0x01 // Combined with VAR_ATTRIB_IS_INT64/DOUBLE/OBJECT to indicate mContents is not current. #define VAR_ATTRIB_ALREADY_WARNED 0x01 // Combined with VAR_ATTRIB_UNINITIALIZED to limit VarUnset warnings to 1 MsgBox per var. See WarnUnassignedVar. #define VAR_ATTRIB_UNINITIALIZED 0x02 // Var requires initialization before use. #define VAR_ATTRIB_HAS_ASSIGNMENT 0x04 // Used during load time to detect vars that are not assigned anywhere. #define VAR_ATTRIB_NOT_NUMERIC 0x08 // A prior call to IsNumeric() determined the var's value is PURE_NOT_NUMERIC. #define VAR_ATTRIB_IS_INT64 0x10 // Var's proper value is in mContentsInt64. #define VAR_ATTRIB_IS_DOUBLE 0x20 // Var's proper value is in mContentsDouble. #define VAR_ATTRIB_IS_OBJECT 0x40 // Var's proper value is in mObject. #define VAR_ATTRIB_VIRTUAL_OPEN 0x80 // Virtual var is open for writing. #define VAR_ATTRIB_CACHE (VAR_ATTRIB_IS_INT64 | VAR_ATTRIB_IS_DOUBLE | VAR_ATTRIB_NOT_NUMERIC) // These three are mutually exclusive. #define VAR_ATTRIB_TYPES (VAR_ATTRIB_IS_INT64 | VAR_ATTRIB_IS_DOUBLE | VAR_ATTRIB_IS_OBJECT) // These are mutually exclusive (but NOT_NUMERIC may be combined with OBJECT). #define VAR_ATTRIB_OFTEN_REMOVED (VAR_ATTRIB_CACHE | VAR_ATTRIB_CONTENTS_OUT_OF_DATE | VAR_ATTRIB_UNINITIALIZED) VarAttribType mAttrib; // Bitwise combination of the above flags (but many of them may be mutually exclusive). #define VAR_GLOBAL 0x01 #define VAR_LOCAL 0x02 #define VAR_VARREF 0x04 // This is a VarRef (used to determine whether the ToReturnValue optimization is safe). #define VAR_DOWNVAR 0x08 // This var is captured by a nested function/closure (it's in Func::mDownVar). #define VAR_LOCAL_FUNCPARAM 0x10 // Indicates this local var is a function's parameter. VAR_LOCAL_DECLARED should also be set. #define VAR_LOCAL_STATIC 0x20 // Indicates this local var retains its value between function calls. #define VAR_DECLARED 0x40 // Indicates this var was declared somehow, not automatic. #define VAR_EXPORTED 0x80 // Exported from a module. UCHAR mScope; // Bitwise combination of the above flags. VarTypeType mType; // Keep adjacent/contiguous with the above due to struct alignment, to save memory. // Performance: Rearranging mType and the other byte-sized members with respect to each other didn't seem // to help performance. However, changing VarTypeType from UCHAR to int did boost performance a few percent, // but even if it's not a fluke, it doesn't seem worth the increase in memory for scripts with many // thousands of variables. #ifdef CONFIG_DEBUGGER friend class Debugger; #endif // Caller has verified mType == VAR_VIRTUAL. bool HasSetter() { return mVV->Set; } // Caller has verified VarTypeIsVirtual(mType). ResultType AssignVirtual(ExprTokenType &aValue); // Unconditionally accepts new memory, bypassing the usual redirection to Assign() for VAR_VIRTUAL. void _AcceptNewMem(LPTSTR aNewMem, VarSizeType aLength); ResultType AssignBinaryNumber(__int64 aNumberAsInt64, VarAttribType aAttrib = VAR_ATTRIB_IS_INT64); void UpdateContents() { ASSERT(mType != VAR_ALIAS); // Caller has already resolved aliases. if (mAttrib & VAR_ATTRIB_CONTENTS_OUT_OF_DATE) { // THE FOLLOWING ISN'T NECESSARY BECAUSE THE ASSIGN() CALLS BELOW DO IT: //mAttrib &= ~VAR_ATTRIB_CONTENTS_OUT_OF_DATE; TCHAR value_string[MAX_NUMBER_SIZE]; if (mAttrib & VAR_ATTRIB_IS_INT64) { Assign(ITOA64(mContentsInt64, value_string)); // Return value currently not checked for this or the below. mAttrib |= VAR_ATTRIB_IS_INT64; // Re-enable the cache because Assign() disables it (since all other callers want that). } else if (mAttrib & VAR_ATTRIB_IS_DOUBLE) { Assign(value_string, FTOA(mContentsDouble, value_string, _countof(value_string))); mAttrib |= VAR_ATTRIB_IS_DOUBLE; // Re-enable the cache because Assign() disables it (since all other callers want that). } //else nothing to update, which shouldn't happen in this block unless there's a flaw or bug somewhere. } } void _SetObject(IObject *aObject) { mObject = aObject; // Mark this variable to indicate it contains an object (objects are never considered numeric). mAttrib |= VAR_ATTRIB_IS_OBJECT | VAR_ATTRIB_NOT_NUMERIC; } VarSizeType _CharLength() { return mByteLength / sizeof(TCHAR); } VarSizeType _CharCapacity() { return mByteCapacity / sizeof(TCHAR); } public: // Testing shows that due to data alignment, keeping mType adjacent to the other less-than-4-size member // above it reduces size of each object by 4 bytes. TCHAR *mName; // The name of the var. // sEmptyString is a special *writable* memory area for empty variables (those with zero capacity). // Although making it writable does make buffer overflows difficult to detect and analyze (since they // tend to corrupt the program's static memory pool), the advantages in maintainability and robustness // seem to far outweigh that. For example, it avoids having to constantly think about whether // *Contents()='\0' is safe. The sheer number of places that's avoided is a great relief, and it also // cuts down on code size due to not having to always check Capacity() and/or create more functions to // protect from writing to read-only strings, which would hurt performance. // The biggest offender of buffer overflow in sEmptyString is DllCall, which happens most frequently // when a script forgets to call VarSetStrCapacity before passing a buffer to some function that writes a // string to it. There is now some code there that tries to detect when that happens. static TCHAR sEmptyString[1]; // See above. void Get(ResultToken &aResultToken); ResultType AssignHWND(HWND aWnd); ResultType Assign(Var &aVar); ResultType Assign(ExprTokenType &aToken); static void AssignVirtualObj(IObject *aObj, ExprTokenType &aValue, ResultToken &aResultToken); static ResultType GetClipboardAll(void **aData, size_t *aDataSize); static ResultType SetClipboardAll(void *aData, size_t aDataSize); // Assign(char *, ...) has been break into four methods below. // This should prevent some mistakes, as characters and bytes are not interchangeable in the Unicode build. // Callers must make sure which one is the right method to call. ResultType AssignString(LPCTSTR aBuf = NULL, VarSizeType aLength = VARSIZE_MAX, bool aExactSize = false); inline ResultType Assign(LPCTSTR aBuf, VarSizeType aLength = VARSIZE_MAX, bool aExactSize = false) { ASSERT(aBuf); // aBuf shouldn't be NULL, use SetCapacity([length in bytes]) or AssignString(NULL, [length in characters]) instead. return AssignString(aBuf, aLength, aExactSize); } inline ResultType Assign() { return AssignString(); } ResultType SetCapacity(VarSizeType aByteLength, bool aExactSize = false) { #ifdef UNICODE return AssignString(NULL, (aByteLength >> 1) + (aByteLength & 1), aExactSize); #else return AssignString(NULL, aByteLength, aExactSize); #endif } ResultType AssignStringFromCodePage(LPCSTR aBuf, int aLength = -1, UINT aCodePage = CP_ACP); ResultType AssignStringToCodePage(LPCWSTR aBuf, int aLength = -1, UINT aCodePage = CP_ACP, DWORD aFlags = WC_NO_BEST_FIT_CHARS, char aDefChar = '?'); inline ResultType AssignStringW(LPCWSTR aBuf, int aLength = -1) { #ifdef UNICODE // Pass aExactSize=true for consistency with AssignStringTo/FromCodePage/UTF8. return AssignString(aBuf, aLength, true); #else return AssignStringToCodePage(aBuf, aLength); #endif } inline ResultType Assign(DWORD aValueToAssign) { return AssignBinaryNumber(aValueToAssign, VAR_ATTRIB_CONTENTS_OUT_OF_DATE|VAR_ATTRIB_IS_INT64); } inline ResultType Assign(int aValueToAssign) { return AssignBinaryNumber(aValueToAssign, VAR_ATTRIB_CONTENTS_OUT_OF_DATE|VAR_ATTRIB_IS_INT64); } inline ResultType Assign(__int64 aValueToAssign) { return AssignBinaryNumber(aValueToAssign, VAR_ATTRIB_CONTENTS_OUT_OF_DATE|VAR_ATTRIB_IS_INT64); } inline ResultType Assign(VarSizeType aValueToAssign) { return AssignBinaryNumber(aValueToAssign, VAR_ATTRIB_CONTENTS_OUT_OF_DATE|VAR_ATTRIB_IS_INT64); } inline ResultType Assign(double aValueToAssign) { // The type-casting below interprets the contents of aValueToAssign as an __int64 without actually // converting from double to __int64. Although the generated code isn't measurably smaller, hopefully // the compiler resolves it into something that performs better than a memcpy into a temporary variable. // Benchmarks show that the performance is at most a few percent worse than having code similar to // AssignBinaryNumber() in here. return AssignBinaryNumber(*(__int64 *)&aValueToAssign, VAR_ATTRIB_CONTENTS_OUT_OF_DATE|VAR_ATTRIB_IS_DOUBLE); } ResultType AssignSkipAddRef(IObject *aValueToAssign); ResultType Assign(IObject *aValueToAssign) { aValueToAssign->AddRef(); // Must be done before Release() in case the only other reference to this object is already in var. Such a case seems too rare to be worth optimizing by returning early. return AssignSkipAddRef(aValueToAssign); } IObject *Object() { Var &var = *ResolveAlias(); return var.mObject; } IObject *ToObject() { Var &var = *ResolveAlias(); return var.IsObject() ? var.mObject : nullptr; } void ReleaseObject() // Caller has ensured that IsObject() == true, not just HasObject(). { ASSERT(IsObject()); // Remove the attributes applied by AssignSkipAddRef(). mAttrib &= ~(VAR_ATTRIB_IS_OBJECT | VAR_ATTRIB_NOT_NUMERIC); // Mark the variable as uninitialized so that any attempt to access it from __Delete // causes an error (but our caller can assign a new value and remove the attribute). mAttrib |= VAR_ATTRIB_UNINITIALIZED; // MUST BE DONE AFTER THE ABOVE IN CASE IT TRIGGERS __Delete: // Release this variable's object. Setting mObject = NULL is not necessary // since the value of mObject, mContentsInt64 and mContentsDouble is never used // unless an attribute is present which indicates which one is valid. mObject->Release(); } SymbolType IsNumeric() { Var &var = *ResolveAlias(); switch (var.mAttrib & VAR_ATTRIB_CACHE) // This switch() method should squeeze a little more performance out of it compared to doing "&" for every attribute. Only works for attributes that are mutually-exclusive, which these are. { case VAR_ATTRIB_IS_INT64: return PURE_INTEGER; case VAR_ATTRIB_IS_DOUBLE: return PURE_FLOAT; case VAR_ATTRIB_NOT_NUMERIC: return PURE_NOT_NUMERIC; } // Since above didn't return, its numeric status isn't yet known, so determine it. For simplicity // (and because Length() doesn't support VAR_VIRTUAL), the following doesn't check MAX_NUMBER_LENGTH. // So any string of digits that is too long to be a legitimate number is still treated as a number // anyway (overflow). Most of our callers are expressions anyway, in which case any unquoted // series of digits would've been assigned as a pure number and handled above. // Below passes FALSE for aUpdateContents because we've already confirmed this var doesn't contain // a cached number (so can't need updating) and to suppress an "uninitialized variable" warning. // The majority of our callers will call ToInt64/Double() or Contents() after we return, which would // trigger a second warning if we didn't suppress ours and StdOut/OutputDebug warn mode is in effect. // IF-IS is the only caller that wouldn't cause a warning, but in that case ExpandArgs() would have // already caused one. SymbolType is_pure_numeric = ::IsNumeric(var.Contents(), true, false, true); // Contents() vs. mContents to support VAR_VIRTUAL lvalue in a pure expression such as "a_clipboard:=1,a_clipboard+=5" if (is_pure_numeric == PURE_NOT_NUMERIC && !VarTypeIsVirtual(var.mType)) var.mAttrib |= VAR_ATTRIB_NOT_NUMERIC; return is_pure_numeric; } SymbolType IsPureNumeric() // Unlike IsNumeric(), this is purely based on whether a pure number was assigned to this variable. // Implicitly supports all types of variables, since these attributes are used only by VAR_NORMAL. { Var &var = *ResolveAlias(); switch (var.mAttrib & VAR_ATTRIB_CACHE) { case VAR_ATTRIB_IS_INT64: return PURE_INTEGER; case VAR_ATTRIB_IS_DOUBLE: return PURE_FLOAT; } return PURE_NOT_NUMERIC; } int IsPureNumericOrObject() { Var &var = *ResolveAlias(); return var.mAttrib & (VAR_ATTRIB_IS_INT64 | VAR_ATTRIB_IS_DOUBLE | VAR_ATTRIB_IS_OBJECT); } __int64 ToInt64() { Var &var = *ResolveAlias(); if (var.mAttrib & VAR_ATTRIB_IS_INT64) return var.mContentsInt64; if (var.mAttrib & VAR_ATTRIB_IS_DOUBLE) // Since mContentsDouble is the true value of this var, cast it to __int64 rather than // calling ATOI64(Contents()), which might produce a different result in some cases. return (__int64)var.mContentsDouble; // Otherwise, this var does not contain a pure number. return ATOI64(var.Contents()); // Call Contents() vs. using mContents in case of VAR_VIRTUAL or VAR_ATTRIB_IS_DOUBLE, and also for maintainability. } double ToDouble() { Var &var = *ResolveAlias(); if (var.mAttrib & VAR_ATTRIB_IS_DOUBLE) return var.mContentsDouble; if (var.mAttrib & VAR_ATTRIB_IS_INT64) return (double)var.mContentsInt64; // As expected, testing shows that casting an int64 to a double is at least 100 times faster than calling ATOF() on the text version of that integer. // Otherwise, this var does not contain a pure number. return ATOF(var.Contents()); // Call Contents() vs. using mContents in case of VAR_VIRTUAL, and also for maintainability and consistency with ToInt64(). } ResultType ToDoubleOrInt64(ExprTokenType &aToken) // aToken.var is the same as the "this" var. Converts var into a number and stores it numerically in aToken. { Var &var = *ResolveAlias(); switch (aToken.symbol = var.IsNumeric()) { case PURE_INTEGER: aToken.value_int64 = var.ToInt64(); break; case PURE_FLOAT: aToken.value_double = var.ToDouble(); break; default: // Not a pure number. return FAIL; } return OK; // Since above didn't return, indicate success. } void ToTokenSkipAddRef(ExprTokenType &aToken) // See ToDoubleOrInt64 for comments. { Var &var = *ResolveAlias(); switch (var.mAttrib & VAR_ATTRIB_TYPES) { case VAR_ATTRIB_IS_INT64: aToken.SetValue(var.mContentsInt64); return; case VAR_ATTRIB_IS_DOUBLE: aToken.SetValue(var.mContentsDouble); return; case VAR_ATTRIB_IS_OBJECT: aToken.SetValue(var.mObject); return; default: if (var.mAttrib & VAR_ATTRIB_UNINITIALIZED) // This is relied upon by callers of CallEnumerator to permit an unset output arg // to indicate a missing array item. It should not be translated to a parameter's // default value, because an unset var in that context would have raised an error. // Some other callers may use this in place of IsUninitialized(). aToken.symbol = SYM_MISSING; else aToken.SetValue(var.Contents(), var.Length()); } } void ToToken(ExprTokenType &aToken) { ToTokenSkipAddRef(aToken); if (aToken.symbol == SYM_OBJECT) aToken.object->AddRef(); } // Not an enum so that it can be global more easily: #define VAR_NEVER_FREE 0 #define VAR_ALWAYS_FREE 1 #define VAR_FREE_IF_LARGE 2 #define VAR_CLEAR_ALIASES 4 #define VAR_REQUIRE_INIT 8 void Free(int aWhenToFree = VAR_ALWAYS_FREE); ResultType Append(LPTSTR aStr, VarSizeType aLength); ResultType AppendIfRoom(LPTSTR aStr, VarSizeType aLength); ResultType AcceptNewMem(LPTSTR aNewMem, VarSizeType aLength); void SetLengthFromContents(); static ResultType BackupFunctionVars(UserFunc &aFunc, VarBkp *&aVarBackup, int &aVarBackupCount); void Backup(VarBkp &aVarBkp); void Restore(VarBkp &aVarBkp); static void FreeAndRestoreFunctionVars(UserFunc &aFunc, VarBkp *&aVarBackup, int &aVarBackupCount); #define DISPLAY_NO_ERROR 0 // Must be zero. #define DISPLAY_VAR_ERROR 1 #define DISPLAY_FUNC_ERROR 2 #define DISPLAY_CLASS_ERROR 3 #define DISPLAY_GROUP_ERROR 4 #define DISPLAY_METHOD_ERROR 5 #define VALIDATENAME_SUBJECT_INDEX(n) (n-1) #define VALIDATENAME_SUBJECTS { _T("variable"), _T("function"), _T("class"), _T("group"), _T("method") } static ResultType ValidateName(LPCTSTR aName, int aDisplayError = DISPLAY_VAR_ERROR); LPTSTR ObjectToText(LPTSTR aName, LPTSTR aBuf, int aBufSize); LPTSTR ToText(LPTSTR aBuf, int aBufSize, bool aAppendNewline) // Caller must ensure that Type() == VAR_NORMAL. // aBufSize is an int so that any negative values passed in from caller are not lost. // Caller has ensured that aBuf isn't NULL. // Translates this var into its text equivalent, putting the result into aBuf and // returning the position in aBuf of its new string terminator. { Var &var = *ResolveAlias(); // v1.0.44.14: Changed it so that ByRef/Aliases report their own name rather than the target's/caller's // (it seems more useful and intuitive). var.Contents(); // Update mContents and mLength for use below. LPTSTR aBuf_orig = aBuf; switch (var.IsPureNumericOrObject()) { case VAR_ATTRIB_IS_INT64: case VAR_ATTRIB_IS_DOUBLE: // Dont display [len of cap] since it's not relevant for pure numbers. // This also makes it obvious that the var contains a pure number: aBuf += sntprintf(aBuf, aBufSize, _T("%s: %s"), mName, var.mCharContents); break; case VAR_ATTRIB_IS_OBJECT: if (var.mType == VAR_VIRTUAL_OBJ) { aBuf += sntprintf(aBuf, aBufSize, _T("%s[%s]: %s"), mName, mObject->Type(), var.mCharContents); break; } aBuf = var.ObjectToText(this->mName, aBuf, aBufSize); break; default: if (var.IsUninitialized()) { aBuf += sntprintf(aBuf, aBufSize, _T("%s: unset"), mName); break; } aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s[%Iu of %Iu]: %-1.60s%s"), mName // mName not var.mName (see comment above). , var._CharLength(), var._CharCapacity() ? (var._CharCapacity() - 1) : 0 // Use -1 since it makes more sense to exclude the terminator. , var.mCharContents, var._CharLength() > 60 ? _T("...") : _T("")); } if (aAppendNewline && BUF_SPACE_REMAINING >= 2) { *aBuf++ = '\r'; *aBuf++ = '\n'; *aBuf = '\0'; } return aBuf; } VarTypeType Type() { Var &var = *ResolveAlias(); return var.mType; } bool IsVirtual() { return VarTypeIsVirtual(Type()); } bool IsAlias() { return mType == VAR_ALIAS; } bool IsDirectConstant() // Is a constant and not an alias (i.e. downvar/upvar) for a constant. { return mType == VAR_CONSTANT; } // Convert VAR_NORMAL to VAR_CONSTANT. void MakeReadOnly() { ASSERT(mType == VAR_NORMAL || mType == VAR_CONSTANT); // Should never be called on VAR_ALIAS or VAR_VIRTUAL. ASSERT(!(mAttrib & VAR_ATTRIB_UNINITIALIZED)); mType = VAR_CONSTANT; } #define VAR_IS_READONLY(var) ((var).IsReadOnly()) // This used to rely on var.Type(), which is no longer enough. bool IsReadOnly() { auto &var = *ResolveAlias(); return var.mType == VAR_CONSTANT || (var.mType == VAR_VIRTUAL && !var.HasSetter()); } bool IsStatic() { return (mScope & VAR_LOCAL_STATIC); } bool IsLocal() { // Since callers want to know whether this variable is local, even if it's a local alias for a // global, don't use the method below: // return (mType == VAR_ALIAS) ? mAliasFor->mIsLocal : mIsLocal; return (mScope & VAR_LOCAL); } bool IsNonStaticLocal() { // Since callers want to know whether this variable is local, even if it's a local alias for a // global, don't resolve VAR_ALIAS. // Even a ByRef local is considered local here because callers are interested in whether this // variable can vary from call to call to the same function (and a ByRef can vary in what it // points to). Variables that vary can thus be altered by the backup/restore process. return (mScope & (VAR_LOCAL|VAR_LOCAL_STATIC)) == VAR_LOCAL; } bool IsFuncParam() { return (mScope & VAR_LOCAL_FUNCPARAM); } bool IsDeclared() // Returns true if this is a declared var, such as "local var", "static var" or a func param. { return (mScope & VAR_DECLARED); } bool IsExported() { return (mScope & VAR_EXPORTED); } UCHAR &Scope() { return mScope; } static LPCTSTR DeclarationType(int aDeclType) { if (aDeclType & VAR_LOCAL) { if (aDeclType & VAR_LOCAL_STATIC) return _T("static variable"); if (aDeclType & VAR_LOCAL_FUNCPARAM) return _T("parameter"); return _T("local variable"); } if (aDeclType & VAR_GLOBAL) return _T("global variable"); return _T("variable"); } bool IsAssignedSomewhere() { //return mAttrib & VAR_ATTRIB_HAS_ASSIGNMENT; return (mAttrib & ~VAR_ATTRIB_ALREADY_WARNED) != VAR_ATTRIB_UNINITIALIZED; // When this function is called (at load time), any of the other attributes // would mean that this var has a value, which means that it doesn't require // an assignment. If it lacks all attributes, it's presumably a built-in var. } void MarkAssignedSomewhere() { mAttrib |= VAR_ATTRIB_HAS_ASSIGNMENT; if (mType == VAR_ALIAS) mAliasFor->MarkAssignedSomewhere(); } bool HasAlreadyWarned() { return mAttrib & VAR_ATTRIB_ALREADY_WARNED; } void MarkAlreadyWarned() { mAttrib |= VAR_ATTRIB_ALREADY_WARNED; } bool IsObject() // L31: Indicates this var contains an object reference which must be released if the var is emptied. { return (mAttrib & VAR_ATTRIB_IS_OBJECT); } bool HasObject() // L31: Indicates this var's effective value is an object reference. { Var &var = *ResolveAlias(); return var.IsObject(); } VarSizeType ByteCapacity() // Capacity includes the zero terminator (though if capacity is zero, there will also be a zero terminator in mContents due to it being ""). { Var &var = *ResolveAlias(); return var.mByteCapacity; } VarSizeType CharCapacity() { return ByteCapacity() / sizeof(TCHAR); } UNICODE_CHECK VarSizeType Capacity() { return CharCapacity(); } BOOL HasContents() // A fast alternative to Length() that avoids updating mContents. // Caller must ensure that Type() is VAR_NORMAL. { Var &var = *ResolveAlias(); // mAttrib is checked because mByteLength isn't applicable when the var contains // a pure number or an object. return (var.mAttrib & VAR_ATTRIB_TYPES) ? TRUE : var.mByteLength != 0; } VarSizeType &ByteLength() // This should not be called to discover a non-NORMAL var's length (nor that of an environment variable) // because their lengths aren't knowable without calling Get(). // Returns a reference so that caller can use this function as an lvalue. { Var &var = *ResolveAlias(); // There's no apparent reason to avoid using mByteLength for VAR_VIRTUAL, // so it's used temporarily despite the comments below. Even if mByteLength // isn't always accurate, it's no less accurate than a static variable would be. //if (mType == VAR_NORMAL) { if (var.mAttrib & VAR_ATTRIB_CONTENTS_OUT_OF_DATE) var.UpdateContents(); // Update mContents (and indirectly, mByteLength). return var.mByteLength; } // Since the length of the clipboard isn't normally tracked, we just return a // temporary storage area for the caller to use. Note: This approach is probably // not thread-safe, but currently there's only one thread so it's not an issue. // For reserved vars do the same thing as above, but this function should never // be called for them: //static VarSizeType length; // Must be static so that caller can use its contents. See above. //return length; } VarSizeType SetCharLength(VarSizeType len) { ByteLength() = len * sizeof(TCHAR); return len; } VarSizeType CharLength() { return ByteLength() / sizeof(TCHAR); } UNICODE_CHECK VarSizeType Length() { return CharLength(); } //BYTE *ByteContents(BOOL aAllowUpdate = TRUE) //{ // return (BYTE *) CharContents(aAllowUpdate); //} TCHAR *Contents(BOOL aAllowUpdate = TRUE) // Callers should almost always pass TRUE for aAllowUpdate because any caller who wants to READ from // mContents would almost always want it up-to-date. Any caller who wants to WRITE to mContents would // would almost always have called Assign(NULL, ...) prior to calling Contents(), which would have // cleared the VAR_ATTRIB_CONTENTS_OUT_OF_DATE flag. // UPDATE: If the variable is known to already be "up to date", passing FALSE reduces code size, // as the compiler often inlines the function and is able to optimize out the aAllowUpdate branches // (although the final result can be larger if it allows the compiler to inline more functions). { if (mType == VAR_ALIAS) return mAliasFor->Contents(aAllowUpdate); if ((mAttrib & VAR_ATTRIB_CONTENTS_OUT_OF_DATE) && aAllowUpdate) // VAR_ATTRIB_CONTENTS_OUT_OF_DATE is checked here and in the function below, for performance. UpdateContents(); // This also clears the VAR_ATTRIB_CONTENTS_OUT_OF_DATE. if (VarTypeIsVirtual(mType) && !(mAttrib & VAR_ATTRIB_VIRTUAL_OPEN) && aAllowUpdate) { // This var isn't open for writing, so populate mCharContents with its current value. PopulateVirtualVar(); // The following ensures the contents are updated each time Contents() is called: mAttrib &= ~VAR_ATTRIB_VIRTUAL_OPEN; } return mCharContents; } // Populate a virtual var with its current value, as a string. // Caller has verified this->IsVirtual(). ResultType PopulateVirtualVar(); void ConvertToNonAliasIfNecessary() // __forceinline because it's currently only called from one place. // When this function actually converts an alias into a normal variable, the variable's old // attributes (especially mContents and mCapacity) become dominant again. This prevents a memory // leak in a case where a UDF is defined to provide a default value for a ByRef parameter, and is // called both with and without that parameter. { mAliasFor = NULL; // This also sets its counterpart in the union (mLength) to zero, which is appropriate because mContents should have been set to blank by a previous call to Free(). mType = VAR_NORMAL; // It might already be this type, so this is just in case it's VAR_ALIAS. } Var *GetAliasFor() { ASSERT(mType == VAR_ALIAS); return mAliasFor; } Var *ResolveAlias() { // Return target if it's an alias, or itself if not. return mType == VAR_ALIAS ? mAliasFor->ResolveAlias() : this; } // Makes this var an alias of aTargetVar, or aTargetVar's target if it's an alias. // Copies any internal mObject ref used for managing the lifetime of the alias. void UpdateAlias(Var *aTargetVar); void UpdateAlias(VarRef *aTargetVar); void UpdateVirtualObj(IObject *aTargetRef); // Unconditionally makes this var an alias of aTargetVar, without resolving aliases. // Caller must ensure aTargetVar != nullptr && aTargetVar != this. void SetAliasDirect(Var *aTargetVar) { mAliasFor = aTargetVar; // Should always be non-NULL due to various checks elsewhere. mType = VAR_ALIAS; // It might already be this type, so this is just in case it's VAR_NORMAL. } // Retrieves the IObject interface for managing this var's lifetime, // converting this var to an alias for a new freevar if needed. IObject *GetRef(); ResultType MoveToNewFreeVar(Var &aOther); ResultType Close() { if (mType == VAR_ALIAS) return mAliasFor->Close(); if (VarTypeIsVirtual(mType)) { // Commit the value in our temporary buffer. auto result = AssignVirtual(ExprTokenType(mCharContents, CharLength())); Free(); // Free temporary memory and remove VAR_ATTRIB_VIRTUAL_OPEN. return result; } // VAR_ATTRIB_CONTENTS_OUT_OF_DATE is removed below for maintainability; it shouldn't be // necessary because any caller of Close() should have previously called something that // updates the flags, such as Contents(). mAttrib &= ~VAR_ATTRIB_OFTEN_REMOVED; return OK; // In all other cases. } // Constructor: Var(LPTSTR aVarName, UCHAR aScope) // The caller must ensure that aVarName is non-null. : mScope(aScope) , mAttrib(VAR_ATTRIB_UNINITIALIZED) // Seems best not to init empty vars to VAR_ATTRIB_NOT_NUMERIC because it would reduce maintainability, plus finding out whether an empty var is numeric via IsNumeric() is a very fast operation. , mName(aVarName) // Caller gave us a pointer to dynamic memory for this. , mType(VAR_NORMAL) { } Var(LPTSTR aVarName, VarEntry *aBuiltIn, UCHAR aScope) // The caller must ensure that aVarName is non-null. : mScope(aScope) , mName(aVarName) // Caller gave us a pointer to dynamic memory for this. , mAttrib(0) // Any vars that aren't VAR_NORMAL are considered initialized, by definition. , mType(VAR_VIRTUAL) , mVV(&aBuiltIn->type) { } Var() : Var(_T(""), VAR_VARREF) { // Vars constructed this way are for temporary use, and therefore must have mHowAllocated set // as below to prevent the use of SimpleHeap::Malloc(). Otherwise, each Var could allocate // some memory which cannot be freed until the program exits. mHowAllocated = ALLOC_MALLOC; } Var(IObject *aRef) // The caller must ensure that aVarName is non-null. : mType(VAR_VIRTUAL_OBJ), mObject(aRef) , mScope(0), mName(_T("")), mAttrib(VAR_ATTRIB_IS_OBJECT) , mHowAllocated(ALLOC_DISABLED) { ASSERT(aRef); } void *operator new(size_t aBytes) {return SimpleHeap::Malloc(aBytes);} void *operator new(size_t aBytes, void *p) {return p;} void *operator new[](size_t aBytes) {return SimpleHeap::Malloc(aBytes);} void operator delete(void *aPtr) {} void operator delete(void *aPtr, void *) {} void operator delete[](void *aPtr) {} ResultType InitializeConstant(); bool IsUninitializedNormalVar() { Var &var = *ResolveAlias(); return var.mType == VAR_NORMAL && (var.mAttrib & VAR_ATTRIB_UNINITIALIZED); } bool IsUninitialized() { Var &var = *ResolveAlias(); return var.mAttrib & VAR_ATTRIB_UNINITIALIZED; } void MarkInitialized() { Var &var = *ResolveAlias(); var.mAttrib &= ~VAR_ATTRIB_UNINITIALIZED; } void MarkUninitialized() { Var& var = *ResolveAlias(); var.mAttrib |= VAR_ATTRIB_UNINITIALIZED; } ResultType AssignUnset(int aWhenToFree = VAR_FREE_IF_LARGE) { if (IsVirtual()) { ExprTokenType unset; unset.symbol = SYM_MISSING; return AssignVirtual(unset); } UninitializeNonVirtual(aWhenToFree); return OK; } // Make var unset; IsVirtual() must be false. Calling this rather than AssignUnset() // in cases where IsVirtual() can't be true reduces code size due to inlining. void UninitializeNonVirtual(int aWhenToFree = VAR_FREE_IF_LARGE) { ASSERT(!IsVirtual()); Free(aWhenToFree | VAR_REQUIRE_INIT); } }; // class Var #pragma pack(pop) // Calling pack with no arguments restores the default value (which is 8, but "the alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.") #pragma warning(pop) class VarRef : public ObjectBase, public Var { public: VarRef() {} ~VarRef() { Free(VAR_ALWAYS_FREE | VAR_CLEAR_ALIASES | VAR_REQUIRE_INIT); } IObject_Type_Impl("VarRef"); ::Object *Base() { return ::Object::sVarRefPrototype; } void *operator new(size_t aBytes) { return malloc(aBytes); } // Must override Var::new, which uses SimpleHeap::Malloc. void *operator new[](size_t aBytes) { return malloc(aBytes); } void operator delete(void *aPtr) { free(aPtr); } void operator delete[](void *aPtr) { free(aPtr); } void __Value(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); static ObjectMember sMembers[]; }; #endif
38,612
C++
.h
855
42.580117
240
0.747078
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,126
stdafx.h
AutoHotkey_AutoHotkey/source/stdafx.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #define _CRT_SECURE_NO_DEPRECATE // Avoid compiler warnings in VC++ 8.x/2005 that urge the use of lower-performing C library functions that protect against buffer overruns. #define _CRT_NON_CONFORMING_SWPRINTFS // We don't want ISO version of swprintf, which has similar interface with snwprintf (different from sprintf) #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #define _WINSOCK_DEPRECATED_NO_WARNINGS // Primarily for WSAAsyncSelect, since the recommended replacement is inadequate. #pragma warning (disable:4351) // Suppress spurious warning about "new behavior" for some compilers. // Windows Header Files: // Necessary to do this prior to including windows.h so that NT functions are unlocked: #define _WIN32_WINNT 0x0600 #define _WIN32_IE _WIN32_IE_IE70 // Added for TVN_ITEMCHANGED, which most likely requires Vista. #ifdef _MSC_VER #include "config.h" // compile-time configurations #include "debug.h" // C RunTime Header Files #include <stdio.h> #include <stdlib.h> #include <stdarg.h> // used by snprintfcat() #include <limits.h> // for UINT_MAX, UCHAR_MAX, etc. #include <malloc.h> // For _alloca() //#include <memory.h> #include <windows.h> #include <tchar.h> #include <commctrl.h> // for status bar functions. Must be included after <windows.h>. #include <shellapi.h> // for ShellExecute() #include <shlobj.h> // for SHGetMalloc() #include <mmsystem.h> // for mciSendString() and waveOutSetVolume() #include <commdlg.h> // for OPENFILENAME // ATL alternatives #include "KuString.h" #include "StringConv.h" // It's probably best not to do these, because I think they would then be included // for everything, even modules that don't need it, which might result in undesired // dependencies sneaking in, or subtle naming conflicts: // ... //#include "defines.h" //#include "application.h" //#include "globaldata.h" //#include "window.h" // Not to be confused with "windows.h" //#include "util.h" //#include "SimpleHeap.h" #endif #include <algorithm> using std::swap; // Lexikos: Defining _WIN32_WINNT 0x0600 seems to break TrayTip in non-English Windows, // and possibly other things. Instead, define any Vista constants we need here. #if (_WIN32_WINNT < 0x0600) #define WM_MOUSEHWHEEL 0x020E #define MOUSEEVENTF_HWHEEL 0x01000 /* hwheel button rolled */ #define LWS_NOPREFIX 0x0004 // SysLink control #define LWS_RIGHT 0x0020 // SysLink control #endif
3,187
C++
.h
67
45.880597
172
0.765066
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,127
hook.h
AutoHotkey_AutoHotkey/source/hook.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #ifndef hook_h #define hook_h #include "hotkey.h" // Use here and also by hook.cpp for ChangeHookState(), which reads from static Hotkey class vars. // WM_USER is the lowest number that can be a user-defined message. Anything above that is also valid. // NOTE: Any msg about WM_USER will be kept buffered (unreplied-to) whenever the script is uninterruptible. // If this is a problem, try making the msg have an ID less than WM_USER via a technique such as that used // for AHK_USER_MENU (perhaps WM_COMMNOTIFY can be "overloaded" to contain more than one type of msg). // Also, it has been announced in OnMessage() that message numbers between WM_USER and 0x1000 are earmarked // for possible future use by the program, so don't use a message above 0x1000 without good reason. enum UserMessages {AHK_HOOK_HOTKEY = WM_USER, AHK_HOTSTRING, AHK_USER_MENU, AHK_DIALOG, AHK_NOTIFYICON , AHK_UNUSED_MSG, AHK_EXIT_BY_RELOAD, AHK_EXIT_BY_SINGLEINSTANCE, AHK_CHECK_DEBUGGER // Allow some room here in between for more "exit" type msgs to be added in the future (see below comment). , AHK_GUI_ACTION = WM_USER+20 // Avoid WM_USER+100/101 and vicinity. See below comment. // v1.0.43.05: On second thought, it seems better to stay close to WM_USER because the OnMessage page // documents, "it is best to choose a number greater than 4096 (0x1000) to the extent you have a choice. // This reduces the chance of interfering with messages used internally by current and future versions..." // v1.0.43.03: Changed above msg number because Micha reports that previous number (WM_USER+100) conflicts // with msgs sent by HTML control (AHK_CLIPBOARD_CHANGE) and possibly others (I think WM_USER+100 may be the // start of a range used by other common controls too). So trying a higher number that's (hopefully) very // unlikely to be used by OS features. , AHK_CLIPBOARD_CHANGE, AHK_HOOK_TEST_MSG, AHK_CHANGE_HOOK_STATE, AHK_GETWINDOWTEXT , AHK_HOT_IF_EVAL // HotCriterionAllowsFiring uses this to ensure expressions are evaluated only on the main thread. , AHK_HOOK_SYNC // For WaitHookIdle(). , AHK_INPUT_END, AHK_INPUT_KEYDOWN, AHK_INPUT_CHAR, AHK_INPUT_KEYUP , AHK_HOOK_SET_KEYHISTORY }; // NOTE: TRY NEVER TO CHANGE the specific numbers of the above messages, since some users might be // using the Post/SendMessage commands to automate AutoHotkey itself. Here is the original order // that should be maintained: // AHK_HOOK_HOTKEY = WM_USER, AHK_HOTSTRING, AHK_USER_MENU, AHK_DIALOG, AHK_NOTIFYICON, AHK_RETURN_PID // UPDATE to the below comment: After a careful review, it seems best to buffer a user's selection of // a custom menu item if the current quasi-thread is uninterruptible. This is exactly the same way // hotkeys are buffered. By making a thread truly uninterruptible, behavior is more consistent with // what most users would want, though it should be noted that this also makes it impossible for the // OnExit function to be interrupted by a custom menu item, even one that is designed to simply // exit the script (by means of aborting the on-exit subroutine). Another reason to buffer the // selection of a custom menu item is that we don't want to interrupt the current thread if is // right in the middle of executing a single line, e.g. doing something with the deref buffer // (during which time an interruption might destroy the buffer's contents) or trying to open the // clipboard or save data to it. This particular weakness may be resolved when/if a dedicated // thread is created to maintain the hook(s), thus allowing critical operations such as opening // the clipboard to use a true Sleep() rather than MsgSleep(). // Since WM_COMMNOTIFY is never generated by the Win32 API, and since we want AHK_USER_MENU to be // an ID less than WM_HOTKEY so that it doesn't get filtered out when the script is uninterruptible, // the following trick is used to map our user-defined messages onto WM_COMMNOTIFY by sacrificing the // wParam part of the message (using it as an indicator of what the message really is). // Another reserved msg that might be fairly safe is WM_MDIICONARRANGE, but it's far less preferable: #define TRANSLATE_AHK_MSG(msg, wparam) \ if (msg == WM_COMMNOTIFY)\ {\ msg = (UINT)wparam;\ wparam = 0;\ } // In the above, wparam is made zero to help catch bugs. // And these macros are kept here so that all this trickery is centrally located and thus more maintainable: #define ASK_INSTANCE_TO_CLOSE(hwnd, reason) PostMessage(hwnd, WM_COMMNOTIFY, reason, 0); // POST_AHK_USER_MENU: A gui_hwnd value != 0 is passed with the message if it came from a GUI's menu bar. // This is done because it's good way to pass the info, but also so that its value will be in sync with the // timestamp of the message (in case the message is stuck in the queue for a long time). No pointer is // passed in this case since they might become invalid between the time the msg is posted vs. processed. #define POST_AHK_USER_MENU(hwnd, menu, gui_hwnd) PostMessage(hwnd, AHK_USER_MENU, gui_hwnd, menu); #define POST_AHK_GUI_ACTION(hwnd, control_index, gui_event, event_info) PostMessage(hwnd, AHK_GUI_ACTION \ , (WPARAM)(((control_index) << 16) | (gui_event)), (LPARAM)(event_info)); // Caller must ensure that gui_event is less than 0xFFFF. // POST_AHK_DIALOG: // Post a special msg that will attempt to force it to the foreground after it has been displayed, // since the dialog often will flash in the task bar instead of becoming foreground. // It's enough just to queue up a single message that dialog's message pump will forward to our // main window proc once the dialog window has been displayed. This avoids the overhead of creating // and destroying the timer (although the timer may be needed anyway if any timed subroutines are // enabled). My only concern about this is that on some OS's, or on slower CPUs, the message may be // received too soon (before the dialog window actually exists) resulting in our window proc not // being able to ensure that it's the foreground window. That seems unlikely, however, since // MessageBox() and the other dialog invocating API calls (for FileSelect/DirSelect) likely // ensures its window really exists before dispatching messages. #define POST_AHK_DIALOG(timeout) PostMessage(g_hWnd, WM_COMMNOTIFY, AHK_DIALOG, (LPARAM)timeout); // Some reasoning behind the below data structures: Could build a new array for [sc][sc] and [vk][vk] // (since only two keys are allowed in a ModifierVK/SC combination, only 2 dimensions are needed). // But this would be a 512x512 array of shorts just for the SC part, which is 512K. Instead, what we // do is check whenever a key comes in: if it's a suffix and if a non-standard modifier key of any kind // is currently down: consider action. Most of the time, an action be found because the user isn't // likely to be holding down a ModifierVK/SC, while pressing another key, unless it's modifying that key. // Nor is he likely to have more than one ModifierVK/SC held down at a time. It's still somewhat // inefficient because have to look up the right prefix in a loop. But most suffixes probably won't // have more than one ModifierVK/SC anyway, so the lookup will usually find a match on the first // iteration. struct vk_hotkey { vk_type vk; HotkeyIDType id_with_flags; }; struct sc_hotkey { sc_type sc; HotkeyIDType id_with_flags; }; // Style reminder: Any POD structs (those without any methods) don't use the "m" prefix // for member variables because there's no need: the variables are always prefixed by // the struct that owns them, so there's never any ambiguity: struct key_type { ToggleValueType *pForceToggle; // Pointer to a global variable for toggleable keys only. NULL for others. // Keep sub-32-bit members contiguous to save memory without having to sacrifice performance of // 32-bit alignment: HotkeyIDType hotkey_to_fire_upon_release; // A up-event hotkey queued by a prior down-event. HotkeyIDType first_hotkey; // The first hotkey using this key as a suffix. modLR_type as_modifiersLR; // If this key is a modifier, this will have the corresponding bit(s) for that key. #define PREFIX_ACTUAL 1 // Values for used_as_prefix below, for places that need to distinguish between type of prefix. #define PREFIX_FORCED 2 // v1.0.44: Added so that a neutral hotkey like Control can be forced to fire on key-up even though it isn't actually a prefix key. UCHAR used_as_prefix; // Whether a given virtual key or scan code is even used by a hotkey. bool used_as_suffix; // bool used_as_key_up; // Whether this suffix also has an enabled key-up hotkey. UCHAR no_suppress; // Contains bitwise flags such as NO_SUPPRESS_NEXT_UP_EVENT. bool is_down; // this key is currently down. bool it_put_alt_down; // this key resulted in ALT being pushed down (due to alt-tab). bool it_put_shift_down; // this key resulted in SHIFT being pushed down (due to shift-alt-tab). bool down_performed_action; // the last key-down resulted in an action (modifiers matched those of a valid hotkey) bool hotkey_down_was_suppressed; // Whether the down-event for a key was suppressed (thus its up-event should be too). // The values for "was_just_used" (zero is the initialized default, meaning it wasn't just used): char was_just_used; // a non-modifier key of any kind was pressed while this prefix key was down. // And these are the values for the above (besides 0): #define AS_PREFIX 1 #define AS_PREFIX_FOR_HOTKEY 2 #define AS_PASSTHROUGH_PREFIX -1 // v1.1.34.02: Indicates the suffix key-up hotkey of this prefix key should fire even if a combo was activated. bool sc_takes_precedence; // used only by the scan code array: this scan code should take precedence over vk. }; // Keep the macro below in sync with the above. // Fix for v1.0.43.01: Caller wants item.no_suppress initialized to remove all flags except NO_SUPPRESS_STATES. // Otherwise, a hotkey that removes the mouse hook will cause a non-suppressed key-up to become suppressed, // causing the key to get stuck down. The following two-line script can reproduce this: // ~LCtrl::Hotkey, RButton, Off // RButton::return #define RESET_KEYTYPE_ATTRIB(item) \ {\ item.first_hotkey = HOTKEY_ID_INVALID;\ item.used_as_prefix = 0;\ item.used_as_suffix = false;\ item.used_as_key_up = false;\ item.no_suppress &= NO_SUPPRESS_STATES;\ item.sc_takes_precedence = false;\ } // Since index zero is a placeholder for the invalid virtual key or scan code, add one to each MAX value // to compute the number of elements actually needed to accommodate 0 up to and including VK_MAX or SC_MAX: #define VK_ARRAY_COUNT (VK_MAX + 1) #define SC_ARRAY_COUNT (SC_MAX + 1) #define INPUT_BUFFER_SIZE 16384 // Default buffer size for Input. Used to be the absolute max. #define INPUTHOOK_BUFFER_SIZE 1024 // Default buffer size for InputHook. enum InputStatusType {INPUT_OFF, INPUT_IN_PROGRESS, INPUT_TIMED_OUT, INPUT_TERMINATED_BY_MATCH , INPUT_TERMINATED_BY_ENDKEY, INPUT_LIMIT_REACHED}; // Bitwise flags for the Key arrays: #define END_KEY_WITH_SHIFT 0x01 #define END_KEY_WITHOUT_SHIFT 0x02 #define END_KEY_ENABLED (END_KEY_WITH_SHIFT | END_KEY_WITHOUT_SHIFT) #define INPUT_KEY_SUPPRESS 0x04 #define INPUT_KEY_VISIBLE 0x08 #define INPUT_KEY_VISIBILITY_MASK (INPUT_KEY_SUPPRESS | INPUT_KEY_VISIBLE) #define INPUT_KEY_IGNORE_TEXT 0x10 #define INPUT_KEY_NOTIFY 0x20 #define INPUT_KEY_OPTION_MASK 0x3F #define INPUT_KEY_IS_TEXT 0x40 #define INPUT_KEY_DOWN_SUPPRESSED 0x80 class InputObject; struct input_type { InputStatusType Status = INPUT_OFF; input_type *Prev = nullptr; InputObject *ScriptObject = nullptr; LPTSTR Buffer = nullptr; // Stores the user's actual input. int BufferLength = 0; // The current length of what the user entered. int BufferLengthMax = INPUTHOOK_BUFFER_SIZE - 1; // The maximum allowed length of the input. TCHAR *EndChars = nullptr; // A string of characters that should terminate the input. UINT EndCharsMax = 0; // Current size of EndChars buffer. LPTSTR *match = nullptr; // Array of strings, each string is a match-phrase which if entered, terminates the input. UINT MatchCount; // The number of strings currently in the array. UINT MatchCountMax; // The maximum number of strings that the match array can contain. #define INPUT_ARRAY_BLOCK_SIZE 1024 // The increment by which the above array expands. LPTSTR MatchBuf = nullptr; // The is the buffer whose contents are pointed to by the match array. UINT MatchBufSize = 0; // The capacity of the above buffer. int Timeout = 0; DWORD TimeoutAt; SendLevelType MinSendLevel = 0; // The minimum SendLevel that can be captured by this input (0 allows all). bool BackspaceIsUndo = true; bool CaseSensitive = false; bool TranscribeModifiedKeys = false; // Whether the input command will attempt to transcribe modified keys such as ^c. bool VisibleText = false, VisibleNonText = true; bool NotifyNonText = false; bool FindAnywhere = false; bool EndCharMode = false; bool BeforeHotkeys = false; vk_type EndingVK; // The hook puts the terminating key into one of these if that's how it was terminated. sc_type EndingSC; TCHAR EndingChar; bool EndingBySC; // Whether the Ending key was one handled by VK or SC. bool EndingRequiredShift; // Whether the key that terminated the input was one that needed the SHIFT key. modLR_type EndingMods = 0; UINT EndingMatchIndex; UCHAR KeyVK[VK_ARRAY_COUNT] {}; // A sparse array of key flags by VK. UCHAR KeySC[SC_ARRAY_COUNT] {}; // A sparse array of key flags by SC. input_type::input_type() {} ~input_type() { free(Buffer); free(match); free(MatchBuf); if (EndCharsMax) // If zero, EndChars may point to static memory. free(EndChars); } inline bool InProgress() { return Status == INPUT_IN_PROGRESS; } bool IsEarly() { return BeforeHotkeys; } bool IsInteresting(KBDLLHOOKSTRUCT &aEvent); ResultType Setup(LPCTSTR aOptions, LPCTSTR aEndKeys, LPCTSTR aMatchList); void ParseOptions(LPCTSTR aOptions); void SetTimeoutTimer(); ResultType SetKeyFlags(LPCTSTR aKeys, bool aEndKeyMode = true, UCHAR aFlagsRemove = 0, UCHAR aFlagsAdd = END_KEY_ENABLED); ResultType SetMatchList(LPCTSTR aMatchList); void Start(); void EndByMatch(UINT aMatchIndex); void EndByKey(vk_type aVK, sc_type aSC, bool aBySC, bool aRequiredShift); void EndByChar(TCHAR aChar); void EndByTimeout() { EndByReason(INPUT_TIMED_OUT); } void EndByLimit() { EndByReason(INPUT_LIMIT_REACHED); } void Stop() { EndByReason(INPUT_OFF); } void CollectChar(TCHAR *ch, int char_count); LPTSTR GetEndReason(LPTSTR aKeyBuf, int aKeyBufSize); private: void EndByReason(InputStatusType aReason); }; #include "input_object.h" void InputStart(input_type &input); input_type **InputFindLink(input_type *aInput); input_type *InputUnlinkIfStopped(input_type *aInput); input_type *InputRelease(input_type *aInput); input_type *InputFind(InputObject *object); //------------------------------------------- struct KeyHistoryItem { vk_type vk; sc_type sc; TCHAR event_type; // space=none, i=ignored, s=suppressed, h=hotkey, etc. bool key_up; float elapsed_time; // Time since prior key or mouse button, in seconds. // It seems better to store the foreground window's title rather than its HWND since keystrokes // might result in a window closing (being destroyed), in which case the displayed key history // would not be able to display the title at the time the history is displayed, which would // be undesirable. // To save mem, could point this into a shared buffer instead, but if that buffer were to run // out of space (perhaps due to the target window changing frequently), window logging would // no longer be possible without adding complexity to the logging function. Seems best // to keep it simple: #define KEY_HISTORY_WINDOW_TITLE_SIZE 100 TCHAR target_window[KEY_HISTORY_WINDOW_TITLE_SIZE]; }; struct CollectInputState { bool early_collected, used_dead_key_non_destructively; TCHAR ch[2]; int char_count; HWND active_window; HKL keyboard_layout; }; //------------------------------------------- LRESULT CALLBACK LowLevelKeybdProc(int aCode, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK LowLevelMouseProc(int aCode, WPARAM wParam, LPARAM lParam); LRESULT LowLevelCommon(const HHOOK aHook, int aCode, WPARAM wParam, LPARAM lParam, const vk_type aVK , sc_type aSC, bool aKeyUp, ULONG_PTR aExtraInfo, DWORD aEventFlags); #define HOTSTRING_INDEX_INVALID INT_MAX // Use a signed maximum rather than unsigned, in case indexes ever become signed. #define SuppressThisKey SuppressThisKeyFunc(aHook, lParam, aVK, aSC, aKeyUp, aExtraInfo, pKeyHistoryCurr, hotkey_id_to_post) LRESULT SuppressThisKeyFunc(const HHOOK aHook, LPARAM lParam, const vk_type aVK, const sc_type aSC , bool aKeyUp, ULONG_PTR aExtraInfo, KeyHistoryItem *pKeyHistoryCurr, WPARAM aHotkeyIDToPost , WPARAM aHSwParamToPost = HOTSTRING_INDEX_INVALID, LPARAM aHSlParamToPost = 0); #define AllowKeyToGoToSystem AllowIt(aHook, aCode, wParam, lParam, aVK, aSC, aKeyUp, aExtraInfo, collect_input_state, pKeyHistoryCurr, hotkey_id_to_post) LRESULT AllowIt(const HHOOK aHook, int aCode, WPARAM wParam, LPARAM lParam, const vk_type aVK, const sc_type aSC , bool aKeyUp, ULONG_PTR aExtraInfo, CollectInputState &aState, KeyHistoryItem *pKeyHistoryCurr, WPARAM aHotkeyIDToPost); bool EarlyCollectInput(KBDLLHOOKSTRUCT &aEvent, const vk_type aVK, const sc_type aSC, bool aKeyUp, bool aIsIgnored , CollectInputState &aState, KeyHistoryItem *pKeyHistoryCurr); bool CollectInput(KBDLLHOOKSTRUCT &aEvent, const vk_type aVK, const sc_type aSC, bool aKeyUp, bool aIsIgnored , CollectInputState &aState, KeyHistoryItem *pKeyHistoryCurr, WPARAM &aHotstringWparamToPost, LPARAM &aHotstringLparamToPost); bool CollectHotstring(KBDLLHOOKSTRUCT &aEvent, TCHAR aChar[], int aCharCount, HWND aActiveWindow , KeyHistoryItem *pKeyHistoryCurr, WPARAM &aHotstringWparamToPost, LPARAM &aHotstringLparamToPost); bool CollectInputHook(KBDLLHOOKSTRUCT &aEvent, const vk_type aVK, const sc_type aSC, TCHAR aChar[], int aCharCount, bool aIsIgnored, bool aEarly); bool IsHotstringWordChar(TCHAR aChar); void UpdateKeybdState(KBDLLHOOKSTRUCT &aEvent, const vk_type aVK, const sc_type aSC, bool aKeyUp, bool aIsSuppressed); bool KeybdEventIsPhysical(DWORD aEventFlags, const vk_type aVK, bool aKeyUp); void ChangeHookState(Hotkey *aHK[], int aHK_count, HookType aWhichHook, HookType aWhichHookAlways); void AddRemoveHooks(HookType aHooksToBeActive, bool aChangeIsTemporary = false); bool HookAdjustMaxHotkeys(Hotkey **&aHK, int &aCurrentMax, int aNewMax); bool SystemHasAnotherKeybdHook(); bool SystemHasAnotherMouseHook(); DWORD WINAPI HookThreadProc(LPVOID aUnused); void LinkKeysForCustomCombo(vk_type aNeutral, vk_type aLeft, vk_type aRight); void ResetHook(bool aAllModifiersUp = false, HookType aWhichHook = (HOOK_KEYBD | HOOK_MOUSE) , bool aResetKVKandKSC = false); HookType GetActiveHooks(); void FreeHookMem(); void ResetKeyTypeState(key_type &key); void GetHookStatus(LPTSTR aBuf, int aBufSize); void WaitHookIdle(); #endif
19,619
C++
.h
307
62.28013
156
0.77309
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,128
script_gui.h
AutoHotkey_AutoHotkey/source/script_gui.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #pragma once #include "stdafx.h" // pre-compiled headers #include "script.h" #define GUI_INDEX_TO_ID(index) (index + CONTROL_ID_FIRST) #define GUI_ID_TO_INDEX(id) (id - CONTROL_ID_FIRST) // Returns a small negative if "id" is invalid, such as 0. #define GUI_HWND_TO_INDEX(hwnd) GUI_ID_TO_INDEX(GetDlgCtrlID(hwnd)) // Returns a small negative on failure (e.g. HWND not found). // Notes about above: // 1) Callers should call GuiType::FindControl() instead of GUI_HWND_TO_INDEX() if the hwnd might be a combobox's // edit control. // 2) Testing shows that GetDlgCtrlID() is much faster than looping through a GUI window's control array to find // a matching HWND. #define ERR_GUI_NO_WINDOW _T("Gui has no window.") #define ERR_GUI_NOT_FOR_THIS_TYPE _T("Not supported for this control type.") // Used by GuiControl object and Control functions. INT_PTR CALLBACK TabDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); #define TABDIALOG_ATTRIB_INDEX(a) (TabControlIndexType)(a & 0xFF) #define TABDIALOG_ATTRIB_THEMED 0x100 typedef UCHAR GuiControls; enum GuiControlTypes {GUI_CONTROL_INVALID // GUI_CONTROL_INVALID must be zero due to things like ZeroMemory() on the struct. , GUI_CONTROL_TEXT, GUI_CONTROL_PIC, GUI_CONTROL_GROUPBOX , GUI_CONTROL_BUTTON, GUI_CONTROL_CHECKBOX, GUI_CONTROL_RADIO , GUI_CONTROL_DROPDOWNLIST, GUI_CONTROL_COMBOBOX , GUI_CONTROL_LISTBOX, GUI_CONTROL_LISTVIEW, GUI_CONTROL_TREEVIEW , GUI_CONTROL_EDIT, GUI_CONTROL_DATETIME, GUI_CONTROL_MONTHCAL, GUI_CONTROL_HOTKEY , GUI_CONTROL_UPDOWN, GUI_CONTROL_SLIDER, GUI_CONTROL_PROGRESS, GUI_CONTROL_TAB, GUI_CONTROL_TAB2, GUI_CONTROL_TAB3 , GUI_CONTROL_ACTIVEX, GUI_CONTROL_LINK, GUI_CONTROL_CUSTOM, GUI_CONTROL_STATUSBAR // Kept last to reflect it being bottommost in switch()s (for perf), since not too often used. , GUI_CONTROL_TYPE_COUNT}; #define GUI_CONTROL_TYPE_NAMES _T(""), \ _T("Text"), _T("Pic"), _T("GroupBox"), \ _T("Button"), _T("CheckBox"), _T("Radio"), \ _T("DDL"), _T("ComboBox"), \ _T("ListBox"), _T("ListView"), _T("TreeView"), \ _T("Edit"), _T("DateTime"), _T("MonthCal"), _T("Hotkey"), \ _T("UpDown"), _T("Slider"), _T("Progress"), _T("Tab"), _T("Tab2"), _T("Tab3"), \ _T("ActiveX"), _T("Link"), _T("Custom"), _T("StatusBar") struct FontType : public LOGFONT { HFONT hfont; }; #define LV_TEXT_BUF_SIZE 8192 // Max amount of text in a ListView sub-item. Somewhat arbitrary: not sure what the real limit is, if any. enum LVColTypes {LV_COL_TEXT, LV_COL_INTEGER, LV_COL_FLOAT}; // LV_COL_TEXT must be zero so that it's the default with ZeroMemory. struct lv_col_type { UCHAR type; // UCHAR vs. enum LVColTypes to save memory. bool sort_disabled; // If true, clicking the column will have no automatic sorting effect. UCHAR case_sensitive; // Ignored if type isn't LV_COL_TEXT. SCS_INSENSITIVE is the default. bool unidirectional; // Sorting cannot be reversed/toggled. bool prefer_descending; // Whether this column defaults to descending order (on first click or for unidirectional). }; struct lv_attrib_type { int sorted_by_col; // Index of column by which the control is currently sorted (-1 if none). bool is_now_sorted_ascending; // The direction in which the above column is currently sorted. bool no_auto_sort; // Automatic sorting disabled. #define LV_MAX_COLUMNS 200 lv_col_type col[LV_MAX_COLUMNS]; int col_count; // Number of columns currently in the above array. int row_count_hint; }; typedef UCHAR TabControlIndexType; typedef UCHAR TabIndexType; // Keep the below in sync with the size of the types above: #define MAX_TAB_CONTROLS 255 // i.e. the value 255 itself is reserved to mean "doesn't belong to a tab". #define MAX_TABS_PER_CONTROL 256 struct GuiControlType : public Object { GuiType* gui; HWND hwnd = NULL; LPTSTR name = nullptr; MsgMonitorList events; // Keep any fields that are smaller than 4 bytes adjacent to each other. This conserves memory // due to byte-alignment. It has been verified to save 4 bytes per struct in this case: GuiControls type = GUI_CONTROL_INVALID; // Unused: 0x01 #define GUI_CONTROL_ATTRIB_ALTSUBMIT 0x02 // Unused: 0x04 #define GUI_CONTROL_ATTRIB_EXPLICITLY_HIDDEN 0x08 #define GUI_CONTROL_ATTRIB_EXPLICITLY_DISABLED 0x10 #define GUI_CONTROL_ATTRIB_SUPPRESS_EVENTS 0x20 // Unused: 0x40 #define GUI_CONTROL_ATTRIB_ALTBEHAVIOR 0x80 // Slider +Invert, ListView/TreeView +WantF2, Edit +WantTab UCHAR attrib = 0; // A field of option flags/bits defined above. TabControlIndexType tab_control_index = 0; // Which tab control this control belongs to, if any. TabIndexType tab_index = 0; // For type==TAB, this stores the tab control's index. For other types, it stores the page. #define CLR_TRANSPARENT 0xFF000001L #define IS_AN_ACTUAL_COLOR(color) !((color) & ~0xffffff) // Produces smaller code than checking against CLR_DEFAULT || CLR_INVALID. COLORREF background_color = CLR_INVALID; HBRUSH background_brush = NULL; union { COLORREF union_color; // Color of the control's text. HBITMAP union_hbitmap = NULL; // For PIC controls, stores the bitmap. // Note: Pic controls cannot obey the text color, but they can obey the window's background // color if the picture's background is transparent (at least in the case of icons on XP). lv_attrib_type *union_lv_attrib; // For ListView: Some attributes and an array of columns. IObject *union_object; // For ActiveX. }; GuiControlType() = delete; GuiControlType(GuiType* owner) : gui(owner) {} static LPTSTR sTypeNames[GUI_CONTROL_TYPE_COUNT]; static GuiControls ConvertTypeName(LPCTSTR aTypeName); LPTSTR GetTypeName(); // An array of these attributes is used in place of several long switch() statements, // to reduce code size and possibly improve performance: enum TypeAttribType { TYPE_SUPPORTS_BGTRANS = 0x01, // Supports +BackgroundTrans. TYPE_SUPPORTS_BGCOLOR = 0x02, // Supports +Background followed by a color value. TYPE_REQUIRES_BGBRUSH = 0x04, // Requires a brush to be created to implement background color. TYPE_MSGBKCOLOR = TYPE_SUPPORTS_BGCOLOR | TYPE_REQUIRES_BGBRUSH, // Supports background color by responding to WM_CTLCOLOR, WM_ERASEBKGND or WM_DRAWITEM. TYPE_SETBKCOLOR = TYPE_SUPPORTS_BGCOLOR, // Supports setting a background color by sending it a message. TYPE_NO_SUBMIT = 0x08, // Doesn't accept user input, or is excluded from Submit() for some other reason. TYPE_HAS_NO_TEXT = 0x10, // Has no text and therefore doesn't use the font or text color. TYPE_RESERVE_UNION = 0x20, // Uses the union for some other purpose, so union_color must not be set. TYPE_USES_BGCOLOR = 0x40, // Uses Gui.BackColor. TYPE_HAS_ITEMS = 0x80, // Add() accepts an Array of items rather than text. TYPE_STATICBACK = TYPE_MSGBKCOLOR | TYPE_USES_BGCOLOR, // For brevity in the attrib array. }; typedef UCHAR TypeAttribs; static TypeAttribs TypeHasAttrib(GuiControls aType, TypeAttribs aAttrib); TypeAttribs TypeHasAttrib(TypeAttribs aAttrib) { return TypeHasAttrib(type, aAttrib); } static UCHAR **sRaisesEvents; bool SupportsEvent(GuiEventType aEvent); bool SupportsBackgroundTrans() { return TypeHasAttrib(TYPE_SUPPORTS_BGTRANS); //switch (type) //{ // Supported via WM_CTLCOLORSTATIC: //case GUI_CONTROL_TEXT: //case GUI_CONTROL_PIC: //case GUI_CONTROL_GROUPBOX: //case GUI_CONTROL_BUTTON: // return true; //case GUI_CONTROL_CHECKBOX: Checkbox and radios with trans background have problems with //case GUI_CONTROL_RADIO: their focus rects being drawn incorrectly. //case GUI_CONTROL_LISTBOX: These are also a problem, at least under some theme settings. //case GUI_CONTROL_EDIT: //case GUI_CONTROL_DROPDOWNLIST: //case GUI_CONTROL_SLIDER: These are a problem under both classic and non-classic themes. //case GUI_CONTROL_COMBOBOX: //case GUI_CONTROL_LINK: BackgroundTrans would have no effect. //case GUI_CONTROL_LISTVIEW: Can't reach this point because WM_CTLCOLORxxx is never received for it. //case GUI_CONTROL_TREEVIEW: Same (verified). //case GUI_CONTROL_PROGRESS: Same (verified). //case GUI_CONTROL_UPDOWN: Same (verified). //case GUI_CONTROL_DATETIME: Same (verified). //case GUI_CONTROL_MONTHCAL: Same (verified). //case GUI_CONTROL_HOTKEY: Same (verified). //case GUI_CONTROL_TAB: Same. //case GUI_CONTROL_STATUSBAR: Its text fields (parts) are its children, not ours, so its window proc probably receives WM_CTLCOLORSTATIC, not ours. //default: // return false; // Prohibit the TRANS setting for the above control types. //} } bool SupportsBackgroundColor() { return TypeHasAttrib(TYPE_SUPPORTS_BGCOLOR); } bool RequiresBackgroundBrush() { return TypeHasAttrib(TYPE_REQUIRES_BGBRUSH); } bool HasSubmittableValue() { return !TypeHasAttrib(TYPE_NO_SUBMIT); } bool UsesFontAndTextColor() { return !TypeHasAttrib(TYPE_HAS_NO_TEXT); } bool UsesUnionColor() { // It's easier to exclude those which require the union for some other purpose // than to whitelist all controls which could potentially cause a WM_CTLCOLOR // message (or WM_ERASEBKGND/WM_DRAWITEM in the case of Tab). return !TypeHasAttrib(TYPE_RESERVE_UNION); } bool UsesGuiBgColor() { return TypeHasAttrib(TYPE_USES_BGCOLOR); } static ObjectMemberMd sMembers[]; static ObjectMemberMd sMembersList[]; // Tab, ListBox, ComboBox, DDL static ObjectMemberMd sMembersTab[]; static ObjectMemberMd sMembersDate[]; static ObjectMemberMd sMembersEdit[]; static ObjectMemberMd sMembersLV[]; static ObjectMemberMd sMembersTV[]; static ObjectMemberMd sMembersSB[]; static ObjectMemberMd sMembersCB[]; static Object *sPrototype, *sPrototypeList; static Object *sPrototypes[GUI_CONTROL_TYPE_COUNT]; static void DefineControlClasses(); static Object *GetPrototype(GuiControls aType); FResult Focus(); FResult GetPos(int *aX, int *aY, int *aWidth, int *aHeight); FResult Move(optl<int> aX, optl<int> aY, optl<int> aWidth, optl<int> aHeight); FResult OnCommand(int aNotifyCode, ExprTokenType &aCallback, optl<int> aAddRemove); FResult OnEvent(StrArg aEventName, ExprTokenType &aCallback, optl<int> aAddRemove); FResult OnMessage(UINT aNumber, ExprTokenType &aCallback, optl<int> aAddRemove); FResult OnNotify(int aNotifyCode, ExprTokenType &aCallback, optl<int> aAddRemove); FResult Opt(StrArg aOptions); FResult Redraw(); FResult SetFont(optl<StrArg> aOptions, optl<StrArg> aFontName); FResult get_ClassNN(StrRet &aRetVal); FResult get_Enabled(BOOL &aRetVal); FResult set_Enabled(BOOL aValue); FResult get_Focused(BOOL &aRetVal); FResult get_Gui(IObject *&aRetVal); FResult get_Hwnd(UINT &aRetVal); FResult get_Name(StrRet &aRetVal); FResult set_Name(StrArg aValue); FResult get_Text(ResultToken &aResultToken); FResult set_Text(ExprTokenType &aValue); FResult get_Type(StrRet &aRetVal); FResult get_Value(ResultToken &aResultToken); FResult set_Value(ExprTokenType &aValue); FResult get_Visible(BOOL &aRetVal); FResult set_Visible(BOOL aValue); FResult DT_SetFormat(optl<StrArg> aFormat); FResult Edit_SetCue(StrArg aCueText, optl<BOOL> aActivate); FResult List_Add(ExprTokenType &aItems); FResult List_Choose(ExprTokenType &aValue); FResult List_Delete(optl<int> aIndex); FResult LV_AddInsertModify(optl<int> aRow, optl<StrArg> aOptions, VariantParams &aCol, int *aRetVal, bool aModify); FResult LV_Add(optl<StrArg> aOptions, VariantParams &aCol, int &aRetVal) { return LV_AddInsertModify(nullptr, aOptions, aCol, &aRetVal, false); } FResult LV_Insert(int aRow, optl<StrArg> aOptions, VariantParams &aCol, int &aRetVal) { return LV_AddInsertModify(aRow, aOptions, aCol, &aRetVal, false); } FResult LV_Modify(int aRow, optl<StrArg> aOptions, VariantParams &aCol) { return LV_AddInsertModify(aRow, aOptions, aCol, nullptr, true); } FResult LV_InsertModifyCol(optl<int> aColumn, optl<StrArg> aOptions, optl<StrArg> aTitle, int *aRetVal, bool aModify); FResult LV_InsertCol(optl<int> aColumn, optl<StrArg> aOptions, optl<StrArg> aTitle, int &aRetVal) { return LV_InsertModifyCol(aColumn, aOptions, aTitle, &aRetVal, false); } FResult LV_ModifyCol(optl<int> aColumn, optl<StrArg> aOptions, optl<StrArg> aTitle) { return LV_InsertModifyCol(aColumn, aOptions, aTitle, nullptr, true); } FResult LV_Delete(optl<int> aRow); FResult LV_DeleteCol(int aColumn); FResult LV_GetCount(optl<StrArg> aMode, int &aRetVal); FResult LV_GetNext(optl<int> aStartIndex, optl<StrArg> aRowType, int &aRetVal); FResult LV_GetText(int aRow, optl<int> aColumn, StrRet &aRetVal); FResult LV_SetImageList(UINT_PTR aImageListID, optl<int> aIconType, UINT_PTR &aRetVal); FResult SB_SetIcon(StrArg aFilename, optl<int> aIconNumber, optl<UINT> aPartNumber, UINT_PTR &aRetVal); FResult SB_SetParts(VariantParams &aParam, UINT& aRetVal); FResult SB_SetText(StrArg aNewText, optl<UINT> aPartNumber, optl<UINT> aStyle); FResult CB_SetCue(StrArg aCueText); FResult Tab_UseTab(ExprTokenType *aTab, optl<BOOL> aExact); FResult TV_AddModify(bool aAdd, UINT_PTR aItemID, UINT_PTR aParentItemID, optl<StrArg> aOptions, optl<StrArg> aName, UINT_PTR &aRetVal); FResult TV_Add(StrArg aName, optl<UINT_PTR> aParentItemID, optl<StrArg> aOptions, UINT_PTR &aRetVal) { return TV_AddModify(true, 0, aParentItemID.value_or(0), aOptions, aName, aRetVal); } FResult TV_Modify(UINT_PTR aItemID, optl<StrArg> aOptions, optl<StrArg> aNewName, UINT_PTR &aRetVal) { return TV_AddModify(false, aItemID, 0, aOptions, aNewName, aRetVal); } FResult TV_Delete(optl<UINT_PTR> aItemID); FResult TV_Get(UINT_PTR aItemID, StrArg aAttribute, UINT_PTR &aRetVal); FResult TV_GetChild(UINT_PTR aItemID, UINT_PTR &aRetVal); FResult TV_GetCount(UINT &aRetVal); FResult TV_GetNext(optl<UINT_PTR> aItemID, optl<StrArg> aItemType, UINT_PTR &aRetVal); FResult TV_GetParent(UINT_PTR aItemID, UINT_PTR &aRetVal); FResult TV_GetPrev(UINT_PTR aItemID, UINT_PTR &aRetVal); FResult TV_GetSelection(UINT_PTR &aRetVal); FResult TV_GetText(UINT_PTR aItemID, StrRet &aRetVal); FResult TV_SetImageList(UINT_PTR aImageListID, optl<int> aIconType, UINT_PTR &aRetVal); void Dispose(); // Called by GuiType::Dispose(). }; struct GuiControlOptionsType { DWORD style_add, style_remove, exstyle_add, exstyle_remove, listview_style; int listview_view; // Viewing mode, such as LV_VIEW_ICON, LV_VIEW_DETAILS. Int vs. DWORD to more easily use any negative value as "invalid". HIMAGELIST himagelist; int x, y, width, height; // Position info. float row_count; int choice; // Which item of a DropDownList/ComboBox/ListBox to initially choose. int range_min, range_max; // Allowable range, such as for a slider control. int tick_interval; // The interval at which to draw tickmarks for a slider control. int line_size, page_size; // Also for slider. int thickness; // Thickness of slider's thumb. int tip_side; // Which side of the control to display the tip on (0 to use default side). GuiControlType *buddy1, *buddy2; COLORREF color; // Control's text color. COLORREF color_bk; // Control's background color. int limit; // The max number of characters to permit in an edit or combobox's edit (also used by ListView). int hscroll_pixels; // The number of pixels for a listbox's horizontal scrollbar to be able to scroll. int checked; // When zeroed, struct contains default starting state of checkbox/radio, i.e. BST_UNCHECKED. int icon_number; // Which icon of a multi-icon file to use. Zero means use-default, i.e. the first icon. #define GUI_MAX_TABSTOPS 50 UINT tabstop[GUI_MAX_TABSTOPS]; // Array of tabstops for the interior of a multi-line edit control. UINT tabstop_count; // The number of entries in the above array. SYSTEMTIME sys_time[2]; // Needs to support 2 elements for MONTHCAL's multi/range mode. SYSTEMTIME sys_time_range[2]; DWORD gdtr, gdtr_range; // Used in connection with sys_time and sys_time_range. ResultType redraw; // Whether the state of WM_REDRAW should be changed. TCHAR password_char; // When zeroed, indicates "use default password" for an edit control with the password style. bool range_changed; bool tick_interval_changed, tick_interval_specified; bool start_new_section; bool use_theme; // v1.0.32: Provides the means for the window's current setting of mUseTheme to be overridden. bool listview_no_auto_sort; // v1.0.44: More maintainable and frees up GUI_CONTROL_ATTRIB_ALTBEHAVIOR for other uses. bool tab_control_uses_dialog; #define TAB3_AUTOWIDTH 1 #define TAB3_AUTOHEIGHT 2 CHAR tab_control_autosize; ATOM customClassAtom; }; LRESULT CALLBACK GuiWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK TabWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK ControlWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData); class GuiType : public Object { // The use of 72 and 96 below comes from v1, using the font's point size in the // calculation. It's really just 11.25 * font height in pixels. Could use 12 // or 11 * font height, but keeping the same defaults as v1 seems worthwhile. #define GUI_STANDARD_WIDTH_MULTIPLIER 15 // This times font size = width, if all other means of determining it are exhausted. #define GUI_STANDARD_WIDTH GUI_STANDARD_WIDTH_MULTIPLIER * (MulDiv(sFont[mCurrentFontIndex].lfHeight, -72, 96)) // 96 vs. g_ScreenDPI since lfHeight already accounts for DPI. Don't combine GUI_STANDARD_WIDTH_MULTIPLIER with -72 as it changes the result (due to rounding). // Update for v1.0.21: Reduced it to 8 vs. 9 because 8 causes the height each edit (with the // default style) to exactly match that of a Combo or DropDownList. This type of spacing seems // to be what other apps use too, and seems to make edits stand out a little nicer: #define GUI_CTL_VERTICAL_DEADSPACE DPIScale(8) #define PROGRESS_DEFAULT_THICKNESS MulDiv(sFont[mCurrentFontIndex].lfHeight, -2 * 72, 96) // 96 vs. g_ScreenDPI to preserve DPI scale. public: // Ensure fields of the same size are grouped together to avoid padding between larger types // and smaller types. On last check, this saved 8 bytes per GUI on x64 (where pointers are // of course 64-bit, so a sequence like HBRUSH, COLORREF, HBRUSH would cause padding). // POINTER-SIZED FIELDS: GuiType *mNextGui, *mPrevGui; // For global Gui linked list. HWND mHwnd; LPTSTR mName; HWND mStatusBarHwnd; HWND mOwner; // The window that owns this one, if any. Note that Windows provides no way to change owners after window creation. // Control IDs are higher than their index in the array by +CONTROL_ID_FIRST. This offset is // necessary because windows that behave like dialogs automatically return IDOK and IDCANCEL in // response to certain types of standard actions: GuiControlType **mControl; // Will become an array of controls when the window is first created. HBRUSH mBackgroundBrushWin; // Brush corresponding to mBackgroundColorWin. HDROP mHdrop; // Used for drag and drop operations. HICON mIconEligibleForDestruction; // The window's icon, which can be destroyed when the window is destroyed if nothing else is using it. HICON mIconEligibleForDestructionSmall; // L17: A window may have two icons: ICON_SMALL and ICON_BIG. HACCEL mAccel; // Keyboard accelerator table. UserMenu *mMenu; IObject* mEventSink; MsgMonitorList mEvents; // 32-BIT FIELDS: GuiIndexType mControlCount; GuiIndexType mControlCapacity; // How many controls can fit into the current memory size of mControl. GuiIndexType mDefaultButtonIndex; // Index vs. pointer is needed for some things. DWORD mStyle, mExStyle; // Style of window. int mCurrentFontIndex; COLORREF mCurrentColor; // The default color of text in controls. COLORREF mBackgroundColorWin; // The window's background color itself. int mMarginX, mMarginY, mPrevX, mPrevY, mPrevWidth, mPrevHeight, mMaxExtentRight, mMaxExtentDown , mSectionX, mSectionY, mMaxExtentRightSection, mMaxExtentDownSection; LONG mMinWidth, mMinHeight, mMaxWidth, mMaxHeight; // 8-BIT FIELDS: TabControlIndexType mTabControlCount; TabControlIndexType mCurrentTabControlIndex; // Which tab control of the window. TabIndexType mCurrentTabIndex;// Which tab of a tab control is currently the default for newly added controls. bool mInRadioGroup; // Whether the control currently being created is inside a prior radio-group. bool mUseTheme; // Whether XP theme and styles should be applied to the parent window and subsequently added controls. bool mGuiShowHasNeverBeenDone, mFirstActivation, mShowIsInProgress, mDestroyWindowHasBeenCalled; bool mControlWidthWasSetByContents; // Whether the most recently added control was auto-width'd to fit its contents. bool mUsesDPIScaling; // Whether the GUI uses DPI scaling. bool mIsMinimized; // Workaround for bad OS behaviour; see "case WM_SETFOCUS". bool mDisposed; // Simplifies Dispose(). bool mVisibleRefCounted; // Whether AddRef() has been done as a result of the window being shown. #define MAX_GUI_FONTS 200 // v1.0.44.14: Increased from 100 to 200 due to feedback that 100 wasn't enough. But to alleviate memory usage, the array is now allocated upon first use. static FontType *sFont; // An array of structs, allocated upon first use. static int sFontCount; static HWND sTreeWithEditInProgress; // Needed because TreeView's edit control for label-editing conflicts with IDOK (default button). // Don't overload new and delete operators in this case since we want to use real dynamic memory // (since GUIs can be destroyed and recreated, over and over). FResult Add(StrArg aCtrlType, optl<StrArg> aOptions, ExprTokenType *aContent, IObject *&aRetVal); #define ADD_METHOD(NAME, CTRLTYPE) \ FResult NAME(optl<StrArg> aOptions, ExprTokenType *aContent, IObject *&aRetVal) { \ return AddControl(aOptions, aContent, aRetVal, CTRLTYPE); \ } ADD_METHOD(AddActiveX, GUI_CONTROL_ACTIVEX) ADD_METHOD(AddButton, GUI_CONTROL_BUTTON) ADD_METHOD(AddCheckBox, GUI_CONTROL_CHECKBOX) ADD_METHOD(AddComboBox, GUI_CONTROL_COMBOBOX) ADD_METHOD(AddCustom, GUI_CONTROL_CUSTOM) ADD_METHOD(AddDateTime, GUI_CONTROL_DATETIME) ADD_METHOD(AddDDL, GUI_CONTROL_DROPDOWNLIST) ADD_METHOD(AddDropDownList, GUI_CONTROL_DROPDOWNLIST) ADD_METHOD(AddEdit, GUI_CONTROL_EDIT) ADD_METHOD(AddGroupBox, GUI_CONTROL_GROUPBOX) ADD_METHOD(AddHotkey, GUI_CONTROL_HOTKEY) ADD_METHOD(AddLink, GUI_CONTROL_LINK) ADD_METHOD(AddListBox, GUI_CONTROL_LISTBOX) ADD_METHOD(AddListView, GUI_CONTROL_LISTVIEW) ADD_METHOD(AddMonthCal, GUI_CONTROL_MONTHCAL) ADD_METHOD(AddPic, GUI_CONTROL_PIC) ADD_METHOD(AddPicture, GUI_CONTROL_PIC) ADD_METHOD(AddProgress, GUI_CONTROL_PROGRESS) ADD_METHOD(AddRadio, GUI_CONTROL_RADIO) ADD_METHOD(AddSlider, GUI_CONTROL_SLIDER) ADD_METHOD(AddStatusBar, GUI_CONTROL_STATUSBAR) ADD_METHOD(AddTab, GUI_CONTROL_TAB) ADD_METHOD(AddTab2, GUI_CONTROL_TAB2) ADD_METHOD(AddTab3, GUI_CONTROL_TAB3) ADD_METHOD(AddText, GUI_CONTROL_TEXT) ADD_METHOD(AddTreeView, GUI_CONTROL_TREEVIEW) ADD_METHOD(AddUpDown, GUI_CONTROL_UPDOWN) #undef ADD_METHOD FResult __New(optl<StrArg> aOptions, optl<StrArg> aTitle, optl<IObject*> aEventObj); FResult Destroy(); FResult Show(optl<StrArg> aOptions); FResult Hide(); FResult Minimize(); FResult Maximize(); FResult Restore(); FResult Flash(optl<BOOL> aBlink); FResult GetPos(int *aX, int *aY, int *aWidth, int *aHeight); FResult GetClientPos(int *aX, int *aY, int *aWidth, int *aHeight); FResult Move(optl<int> aX, optl<int> aY, optl<int> aWidth, optl<int> aHeight); FResult OnEvent(StrArg aEventName, ExprTokenType &aCallback, optl<int> aAddRemove); FResult OnMessage(UINT aNumber, ExprTokenType &aCallback, optl<int> aAddRemove); FResult Opt(StrArg aOptions); FResult SetFont(optl<StrArg> aOptions, optl<StrArg> aFontName); FResult Submit(optl<BOOL> aHideIt, IObject *&aRetVal); FResult __Enum(optl<int> aVarCount, IObject *&aRetVal); FResult get_Hwnd(UINT &aRetVal); FResult get_Title(StrRet &aRetVal); FResult set_Title(StrArg aValue); FResult get_MenuBar(ResultToken &aRetVal); FResult set_MenuBar(ExprTokenType &aValue); FResult get___Item(ExprTokenType &aIndex, IObject *&aRetVal); FResult get_FocusedCtrl(IObject *&aRetVal); FResult get_MarginX(int &aRetVal) { return get_Margin(aRetVal, mMarginX); } FResult get_MarginY(int &aRetVal) { return get_Margin(aRetVal, mMarginY); } FResult set_MarginX(int aValue) { mMarginX = Scale(aValue); return OK; } FResult set_MarginY(int aValue) { mMarginY = Scale(aValue); return OK; } FResult get_BackColor(ResultToken &aResultToken); FResult set_BackColor(ExprTokenType &aValue); FResult set_Name(StrArg aName); FResult get_Name(StrRet &aRetVal); static ObjectMemberMd sMembers[]; static int sMemberCount; static Object *sPrototype; GuiType() // Constructor : mHwnd(NULL), mOwner(NULL), mName(NULL) , mPrevGui(NULL), mNextGui(NULL) , mControl(NULL), mControlCount(0), mControlCapacity(0) , mStatusBarHwnd(NULL) , mDefaultButtonIndex(-1), mEventSink(NULL) , mMenu(NULL) // The styles DS_CENTER and DS_3DLOOK appear to be ineffectual in this case. // Also note that WS_CLIPSIBLINGS winds up on the window even if unspecified, which is a strong hint // that it should always be used for top level windows across all OSes. Usenet posts confirm this. // Also, it seems safer to have WS_POPUP under a vague feeling that it seems to apply to dialog // style windows such as this one, and the fact that it also allows the window's caption to be // removed, which implies that POPUP windows are more flexible than OVERLAPPED windows. , mStyle(WS_POPUP|WS_CLIPSIBLINGS|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX) // WS_CLIPCHILDREN (doesn't seem helpful currently) , mExStyle(0) // This and the above should not be used once the window has been created since they might get out of date. , mInRadioGroup(false), mUseTheme(true) , mCurrentFontIndex(FindOrCreateFont()) // Must call this in constructor to ensure sFont array is never empty while a GUI object exists. Omit params to tell it to find or create DEFAULT_GUI_FONT. , mTabControlCount(0), mCurrentTabControlIndex(MAX_TAB_CONTROLS), mCurrentTabIndex(0) , mCurrentColor(CLR_DEFAULT) , mBackgroundColorWin(CLR_DEFAULT), mBackgroundBrushWin(NULL) , mHdrop(NULL), mIconEligibleForDestruction(NULL), mIconEligibleForDestructionSmall(NULL) , mAccel(NULL) , mMarginX(COORD_UNSPECIFIED), mMarginY(COORD_UNSPECIFIED) // These will be set when the first control is added. , mPrevX(0), mPrevY(0) , mPrevWidth(0), mPrevHeight(0) // Needs to be zero for first control to start off at right offset. , mMaxExtentRight(0), mMaxExtentDown(0) , mSectionX(COORD_UNSPECIFIED), mSectionY(COORD_UNSPECIFIED) , mMaxExtentRightSection(COORD_UNSPECIFIED), mMaxExtentDownSection(COORD_UNSPECIFIED) , mMinWidth(COORD_UNSPECIFIED), mMinHeight(COORD_UNSPECIFIED) , mMaxWidth(COORD_UNSPECIFIED), mMaxHeight(COORD_UNSPECIFIED) , mGuiShowHasNeverBeenDone(true), mFirstActivation(true), mShowIsInProgress(false) , mDestroyWindowHasBeenCalled(false), mControlWidthWasSetByContents(false) , mUsesDPIScaling(true) , mDisposed(false) , mVisibleRefCounted(false) { SetBase(sPrototype); } ~GuiType() { // This is done here rather than in Dispose() to allow get_Name() and set_Name() // to omit the mHwnd checks, which allows the Gui to be identified after Destroy() // is called, and also reduces code size marginally. free(mName); } void Dispose(); static void DestroyIconsIfUnused(HICON ahIcon, HICON ahIconSmall); // L17: Renamed function and added parameter to also handle the window's small icon. static GuiType *Create() { return new GuiType(); } // For Object::New<GuiType>(). FResult AddControl(optl<StrArg> aOptions, ExprTokenType *aContent, IObject *&aRetVal, GuiControls aCtrlType); FResult Create(LPCTSTR aTitle); FResult OnEvent(GuiControlType *aControl, UINT aEvent, UCHAR aEventKind, ExprTokenType &aCallback, optl<int> aAddRemove); FResult OnEvent(GuiControlType *aControl, UINT aEvent, UCHAR aEventKind, IObject *aFunc, LPTSTR aMethodName, int aMaxThreads); void ApplyEventStyles(GuiControlType *aControl, UINT aEvent, bool aAdded); void ApplySubclassing(GuiControlType *aControl); static LPTSTR sEventNames[]; static LPTSTR ConvertEvent(GuiEventType evt); static GuiEventType ConvertEvent(LPCTSTR evt); BOOL IsMonitoring(GuiEventType aEvent) { return mEvents.IsMonitoring(aEvent); } ResultType GetEnumItem(UINT &aIndex, Var *, Var *, int); static IObject* CreateDropArray(HDROP hDrop); static void UpdateMenuBars(HMENU aMenu); ResultType AddControl(GuiControls aControlType, LPCTSTR aOptions, LPCTSTR aText, GuiControlType*& apControl, Array *aObj = NULL); void MethodGetPos(int *aX, int *aY, int *aWidth, int *aHeight, RECT &aRect, HWND aOrigin); ResultType ParseOptions(LPCTSTR aOptions, bool &aSetLastFoundWindow, ToggleValueType &aOwnDialogs); void SetOwnDialogs(ToggleValueType state) { if (state == TOGGLE_INVALID) return; g->DialogOwner = state == TOGGLED_ON ? mHwnd : NULL; } void GetNonClientArea(LONG &aWidth, LONG &aHeight); void GetTotalWidthAndHeight(LONG &aWidth, LONG &aHeight); void ParseMinMaxSizeOption(LPCTSTR aOptionValue, LONG &aWidth, LONG &aHeight); ResultType ControlParseOptions(LPCTSTR aOptions, GuiControlOptionsType &aOpt, GuiControlType &aControl , GuiIndexType aControlIndex = -1); // aControlIndex is not needed upon control creation. void ControlInitOptions(GuiControlOptionsType &aOpt, GuiControlType &aControl); void ControlAddItems(GuiControlType &aControl, Array *aObj); void ControlSetChoice(GuiControlType &aControl, int aChoice); ResultType ControlLoadPicture(GuiControlType &aControl, LPCTSTR aFilename, int aWidth, int aHeight, int aIconNumber); void Cancel(); void Close(); // Due to SC_CLOSE, etc. void Escape(); // Similar to close, except typically called when the user presses ESCAPE. void VisibilityChanged(); static GuiType *FindGui(HWND aHwnd); static GuiType *FindGuiParent(HWND aHwnd); GuiIndexType FindControl(LPCTSTR aControlID); GuiIndexType FindControlIndex(HWND aHwnd) { for (;;) { GuiIndexType index = GUI_HWND_TO_INDEX(aHwnd); // Retrieves a small negative on failure, which will be out of bounds when converted to unsigned. if (index < mControlCount && mControl[index]->hwnd == aHwnd) // A match was found. Fix for v1.1.09.03: Confirm it is actually one of our controls. return index; // Not found yet; try again with parent. ComboBox and ListView only need one iteration, // but multiple iterations may be needed by ActiveX/Custom or other future control types. // Note that a ComboBox's drop-list (class ComboLBox) is apparently a direct child of the // desktop, so this won't help us in that case. aHwnd = GetParent(aHwnd); if (!aHwnd || aHwnd == mHwnd) // No match, so indicate failure. return NO_CONTROL_INDEX; } } GuiControlType *FindControl(HWND aHwnd) { GuiIndexType index = FindControlIndex(aHwnd); return index == NO_CONTROL_INDEX ? NULL : mControl[index]; } int FindGroup(GuiIndexType aControlIndex, GuiIndexType &aGroupStart, GuiIndexType &aGroupEnd); static int FindOrCreateFont(LPCTSTR aOptions = _T(""), LPCTSTR aFontName = _T(""), FontType *aFoundationFont = NULL , COLORREF *aColor = NULL); static int FindFont(FontType &aFont); static void FontGetAttributes(FontType &aFont); void Event(GuiIndexType aControlIndex, UINT aNotifyCode, USHORT aGuiEvent = GUI_EVENT_NONE, UINT_PTR aEventInfo = 0); bool ControlWmNotify(GuiControlType &aControl, LPNMHDR aNmHdr, INT_PTR &aRetVal); bool MsgMonitor(GuiControlType *aControl, UINT aMsg, WPARAM awParam, LPARAM alParam, MSG *apMsg, INT_PTR *aRetVal); static WORD TextToHotkey(LPCTSTR aText); static LPTSTR HotkeyToText(WORD aHotkey, LPTSTR aBuf); FResult ControlSetName(GuiControlType &aControl, LPCTSTR aName); void ControlSetEnabled(GuiControlType &aControl, bool aEnabled); void ControlSetVisible(GuiControlType &aControl, bool aVisible); FResult ControlMove(GuiControlType &aControl, int aX, int aY, int aWidth, int aHeight); ResultType ControlSetFont(GuiControlType &aControl, LPCTSTR aOptions, LPCTSTR aFontName); void ControlSetTextColor(GuiControlType &aControl, COLORREF aColor); void ControlSetMonthCalColor(GuiControlType &aControl, COLORREF aColor, UINT aMsg); ResultType ControlChoose(GuiControlType &aControl, ExprTokenType &aParam, BOOL aOneExact = FALSE); void ControlCheckRadioButton(GuiControlType &aControl, GuiIndexType aControlIndex, WPARAM aCheckType); void ControlSetUpDownOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt); int ControlGetDefaultSliderThickness(DWORD aStyle, int aThumbThickness); void ControlSetSliderOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt); int ControlInvertSliderIfNeeded(GuiControlType &aControl, int aPosition); void ControlSetListViewOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt); void ControlSetTreeViewOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt); void ControlSetProgressOptions(GuiControlType &aControl, GuiControlOptionsType &aOpt, DWORD aStyle); GuiControlType *ControlOverrideBkColor(GuiControlType &aControl); void ControlGetBkColor(GuiControlType &aControl, bool aUseWindowColor, HBRUSH &aBrush, COLORREF &aColor); FResult ControlSetContents(GuiControlType &aControl, ExprTokenType &aContents, bool aIsText); FResult ControlSetPic(GuiControlType &aControl, LPTSTR aContents); FResult ControlSetChoice(GuiControlType &aControl, LPTSTR aContents, bool aIsText); // DDL, ComboBox, ListBox, Tab FResult ControlSetEdit(GuiControlType &aControl, LPTSTR aContents, bool aIsText); FResult ControlSetDateTime(GuiControlType &aControl, LPTSTR aContents); FResult ControlSetMonthCal(GuiControlType &aControl, LPTSTR aContents); FResult ControlSetHotkey(GuiControlType &aControl, LPTSTR aContents); FResult ControlSetCheck(GuiControlType &aControl, int aValue); // CheckBox, Radio FResult ControlSetUpDown(GuiControlType &aControl, int aValue); FResult ControlSetSlider(GuiControlType &aControl, int aValue); FResult ControlSetProgress(GuiControlType &aControl, int aValue); enum ValueModeType { Value_Mode, Text_Mode, Submit_Mode }; void ControlGetContents(ResultToken &aResultToken, GuiControlType &aControl, ValueModeType aMode = Value_Mode); void ControlGetCheck(ResultToken &aResultToken, GuiControlType &aControl); // CheckBox, Radio void ControlGetDDL(ResultToken &aResultToken, GuiControlType &aControl, ValueModeType aMode); void ControlGetComboBox(ResultToken &aResultToken, GuiControlType &aControl, ValueModeType aMode); void ControlGetListBox(ResultToken &aResultToken, GuiControlType &aControl, ValueModeType aMode); void ControlGetEdit(ResultToken &aResultToken, GuiControlType &aControl); void ControlGetDateTime(ResultToken &aResultToken, GuiControlType &aControl); void ControlGetMonthCal(ResultToken &aResultToken, GuiControlType &aControl); void ControlGetHotkey(ResultToken &aResultToken, GuiControlType &aControl); void ControlGetUpDown(ResultToken &aResultToken, GuiControlType &aControl); void ControlGetSlider(ResultToken &aResultToken, GuiControlType &aControl); void ControlGetProgress(ResultToken &aResultToken, GuiControlType &aControl); void ControlGetTab(ResultToken &aResultToken, GuiControlType &aControl, ValueModeType aMode); ResultType ControlGetWindowText(ResultToken &aResultToken, GuiControlType &aControl); void ControlRedraw(GuiControlType &aControl, bool aOnlyWithinTab = false); void ControlUpdateCurrentTab(GuiControlType &aTabControl, bool aFocusFirstControl); GuiControlType *FindTabControl(TabControlIndexType aTabControlIndex); int FindTabIndexByName(GuiControlType &aTabControl, LPTSTR aName, bool aExactMatch = false); int GetControlCountOnTabPage(TabControlIndexType aTabControlIndex, TabIndexType aTabIndex); void GetTabDisplayAreaRect(HWND aTabControlHwnd, RECT &aRect); POINT GetPositionOfTabDisplayArea(GuiControlType &aTabControl); ResultType SelectAdjacentTab(GuiControlType &aTabControl, bool aMoveToRight, bool aFocusFirstControl , bool aWrapAround); void AutoSizeTabControl(GuiControlType &aTabControl); ResultType CreateTabDialog(GuiControlType &aTabControl, GuiControlOptionsType &aOpt); void UpdateTabDialog(HWND aTabControlHwnd); void ControlGetPosOfFocusedItem(GuiControlType &aControl, POINT &aPoint); static void LV_Sort(GuiControlType &aControl, int aColumnIndex, bool aSortOnlyIfEnabled, TCHAR aForceDirection = '\0'); static IObject *ControlGetActiveX(HWND aWnd); void UpdateAccelerators(UserMenu &aMenu); void UpdateAccelerators(UserMenu &aMenu, LPACCEL aAccel, int &aAccelCount); void RemoveAccelerators(); static bool ConvertAccelerator(LPTSTR aString, ACCEL &aAccel); void SetDefaultMargins(); FResult get_Margin(int &aRetVal, int &aMargin); // See DPIScale() and DPIUnscale() for more details. int Scale(int x) { return mUsesDPIScaling ? DPIScale(x) : x; } int Unscale(int x) { return mUsesDPIScaling ? DPIUnscale(x) : x; } // The following is a workaround for the "w-1" and "h-1" options: int ScaleSize(int x) { return mUsesDPIScaling && x != -1 ? DPIScale(x) : x; } protected: bool Delete() override; };
37,967
C++
.h
632
57.803797
273
0.777849
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,129
script_func_impl.h
AutoHotkey_AutoHotkey/source/script_func_impl.h
#define ParamIndexToString(index, ...) TokenToString(*aParam[(index)], __VA_ARGS__) #define ParamIndexToInt64(index) TokenToInt64(*aParam[(index)]) #define ParamIndexToInt(index) (int)ParamIndexToInt64(index) #define ParamIndexToIntPtr(index) (INT_PTR)ParamIndexToInt64(index) #define ParamIndexToDouble(index) TokenToDouble(*aParam[(index)]) #define ParamIndexToNumber(index, output) TokenToDoubleOrInt64(*aParam[(index)], output) #define ParamIndexToBOOL(index) TokenToBOOL(*aParam[(index)]) #define ParamIndexToObject(index) TokenToObject(*aParam[(index)]) #define ParamIndexToToggleValue(index) TokenToToggleValue(*aParam[(index)]) #define ParamIndexToOutputVar(index) ((index) < aParamCount ? TokenToOutputVar(*aParam[(index)]) : nullptr) // Omitted parameter returns SCS_INSENSITIVE. #define ParamIndexToCaseSense(index) (ParamIndexIsOmitted((index)) ? SCS_INSENSITIVE : TokenToStringCase(*aParam[(index)])) #define ParamIndexIsNumeric(index) (TokenIsNumeric(*aParam[(index)])) // For functions that allow "" to mean parameter is omitted. #define ParamIndexIsOmittedOrEmpty(index) (ParamIndexIsOmitted(index) || TokenIsEmptyString(*aParam[(index)])) // For functions that don't allow "" to mean parameter is omitted. #define ParamIndexIsOmitted(index) ((index) >= aParamCount || aParam[(index)]->symbol == SYM_MISSING) #define PASTE(a, b) a##b #define ParamIndexToOptionalType(type, index, def) (ParamIndexIsOmitted(index) ? (def) : PASTE(ParamIndexTo,type)(index)) #define ParamIndexToOptionalInt(index, def) ParamIndexToOptionalType(Int, index, def) #define ParamIndexToOptionalIntPtr(index, def) ParamIndexToOptionalType(IntPtr, index, def) #define ParamIndexToOptionalDouble(index, def) ParamIndexToOptionalType(Double, index, def) #define ParamIndexToOptionalInt64(index, def) ParamIndexToOptionalType(Int64, index, def) #define ParamIndexToOptionalBOOL(index, def) ParamIndexToOptionalType(BOOL, index, def) #define ParamIndexToOptionalVar(index) (((index) < aParamCount && aParam[index]->symbol == SYM_VAR) ? aParam[index]->var : NULL) inline LPTSTR _OptionalStringDefaultHelper(LPTSTR aDef, LPTSTR aBuf = NULL, size_t *aLength = NULL, bool aPermitObject = false) { if (aLength) *aLength = _tcslen(aDef); return aDef; } #define ParamIndexToOptionalStringDef(index, def, ...) \ (ParamIndexIsOmitted(index) ? _OptionalStringDefaultHelper(def, __VA_ARGS__) \ : ParamIndexToString(index, __VA_ARGS__)) // The macro below defaults to "", since that is by far the most common default. // No check for SYM_MISSING is needed since TokenToString() returns "" for that. #define ParamIndexToOptionalString(index, ...) \ (((index) < aParamCount) ? ParamIndexToString(index, __VA_ARGS__) \ : _OptionalStringDefaultHelper(_T(""), __VA_ARGS__)) #define ParamIndexToOptionalObject(index) ((index) < aParamCount ? ParamIndexToObject(index) : NULL) #define _f_param_string(name, index, ...) \ TCHAR name##_buf[MAX_NUMBER_SIZE], *name; \ if (!TokenToStringParam(aResultToken, aParam, index, name##_buf, name, __VA_ARGS__)) return #define _f_param_string_opt_def(name, index, def, ...) \ TCHAR name##_buf[MAX_NUMBER_SIZE], *name; \ if (ParamIndexIsOmitted(index)) name = _OptionalStringDefaultHelper(def, name##_buf, __VA_ARGS__); else \ if (!TokenToStringParam(aResultToken, aParam, index, name##_buf, name, __VA_ARGS__)) return #define _f_param_string_opt(name, index, ...) \ _f_param_string_opt_def(name, index, _T(""), __VA_ARGS__) #define Throw_if_Param_NaN(ParamIndex) \ if (!TokenIsNumeric(*aParam[(ParamIndex)])) \ _f_throw_param((ParamIndex), _T("Number")) #define Throw_if_RValue_NaN() \ if (!TokenIsNumeric(aValue)) \ _f_throw_type(_T("Number"), aValue) #define BivRValueToString(...) TokenToString(aValue, _f_number_buf, __VA_ARGS__) #define BivRValueToInt64() TokenToInt64(aValue) #define BivRValueToBOOL() TokenToBOOL(aValue) #define BivRValueToObject() TokenToObject(aValue) template<class T> BIF_DECL(NewObject) { Object *obj = T::Create(); if (!obj) _f_throw_oom; obj->New(aResultToken, aParam, aParamCount); }
4,137
C++
.h
67
59.880597
131
0.746914
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,131
script.h
AutoHotkey_AutoHotkey/source/script.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #ifndef script_h #define script_h #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "SimpleHeap.h" // for overloaded new/delete operators. #include "keyboard_mouse.h" // for modLR_type #include "script_object.h" #include "var.h" // for a script's variables. #include "WinGroup.h" // for a script's Window Groups. #include "Util.h" // for FileTimeToYYYYMMDD(), strlcpy() #include "resources/resource.h" // For tray icon. #include "Debugger.h" #include "abi.h" #include "os_version.h" // For the global OS_Version object EXTERN_OSVER; // For the access to the g_os version object without having to include globaldata.h EXTERN_G; #define MAX_THREADS_LIMIT UCHAR_MAX // Uses UCHAR_MAX (255) because some variables that store a thread count are UCHARs. #define MAX_THREADS_DEFAULT 10 // Must not be higher than above. #define TOTAL_ADDITIONAL_THREADS 2 // See below. // Must allow two additional threads: One for the AutoExec/idle thread and one so that ExitApp() // can run even when #MaxThreads has been reached. // Explanation: If/when AutoExec() finishes, although it no longer needs g_array[0] (not even // AutoExecSectionTimeout() needs it because it either won't be called or it will return early), // at least the following might still use g_array[0]: // 1) Threadless (fast-mode) callbacks that have no controlling script thread; see RegisterCallbackCStub(). // 2) g_array[0].IsPaused indicates whether the script is in a paused state while idle. // In addition, it probably simplifies the code not to reclaim g_array[0]; e.g. ++g and --g can be done // unconditionally when creating new threads. enum ExecUntilMode {NORMAL_MODE, UNTIL_RETURN, UNTIL_BLOCK_END, ONLY_ONE_LINE}; // It's done this way so that mAttribute can store a pointer or one of these constants. // If it is storing a pointer for a given Action Type, be sure never to compare it // for equality against these constants because by coincidence, the pointer value // might just match one of them: #define ATTR_NONE (void *)0 // Some places might rely on this being zero. #define ATTR_TRUE (void *)1 typedef void *AttributeType; typedef int FileLoopModeType; #define FILE_LOOP_INVALID 0 #define FILE_LOOP_FILES_ONLY 1 #define FILE_LOOP_FOLDERS_ONLY 2 #define FILE_LOOP_RECURSE 4 #define FILE_LOOP_FILES_AND_FOLDERS (FILE_LOOP_FILES_ONLY | FILE_LOOP_FOLDERS_ONLY) enum VariableTypeType {VAR_TYPE_INVALID, VAR_TYPE_NUMBER, VAR_TYPE_INTEGER, VAR_TYPE_FLOAT , VAR_TYPE_TIME , VAR_TYPE_DIGIT, VAR_TYPE_XDIGIT, VAR_TYPE_ALNUM, VAR_TYPE_ALPHA , VAR_TYPE_UPPER, VAR_TYPE_LOWER, VAR_TYPE_SPACE }; #define ATTACH_THREAD_INPUT \ bool threads_are_attached = false;\ DWORD target_thread = GetWindowThreadProcessId(target_window, NULL);\ if (target_thread && target_thread != g_MainThreadID && !IsWindowHung(target_window))\ threads_are_attached = AttachThreadInput(g_MainThreadID, target_thread, TRUE) != 0; // BELOW IS SAME AS ABOVE except it checks do_activate and also does a SetActiveWindow(): #define ATTACH_THREAD_INPUT_AND_SETACTIVEWINDOW_IF_DO_ACTIVATE \ bool threads_are_attached = false;\ DWORD target_thread;\ if (do_activate)\ {\ target_thread = GetWindowThreadProcessId(target_window, NULL);\ if (target_thread && target_thread != g_MainThreadID && !IsWindowHung(target_window))\ threads_are_attached = AttachThreadInput(g_MainThreadID, target_thread, TRUE) != 0;\ SetActiveWindow(target_window);\ } #define DETACH_THREAD_INPUT \ if (threads_are_attached)\ AttachThreadInput(g_MainThreadID, target_thread, FALSE); // Since WM_COMMAND IDs must be shared among all menus and controls, they are carefully conserved, // especially since there are only 65,535 possible IDs. In addition, they are assigned to ranges // to minimize the need that they will need to be changed in the future (changing the ID of a main // menu item, tray menu item, or a user-defined menu item [by way of increasing MAX_CONTROLS_PER_GUI] // is bad because some scripts might be using PostMessage/SendMessage to automate AutoHotkey itself). // For this reason, the following ranges are reserved: // 0: unused (possibly special in some contexts) // 1: IDOK // 2: IDCANCEL // 3 to 1002: GUI window control IDs (these IDs must be unique only within their parent, not across all GUI windows) // 1003 to 65299: User Defined Menu IDs // 65300 to 65399: Standard tray menu items. // 65400 to 65534: main menu items (might be best to leave 65535 unused in case it ever has special meaning) enum CommandIDs {CONTROL_ID_FIRST = IDCANCEL + 1 , ID_USER_FIRST = MAX_CONTROLS_PER_GUI + 3 // The first ID available for user defined menu items. Do not change this (see above for why). , ID_USER_LAST = 65299 // The last. Especially do not change this due to scripts using Post/SendMessage to automate AutoHotkey. , ID_TRAY_FIRST, ID_TRAY_OPEN = ID_TRAY_FIRST , ID_TRAY_HELP, ID_TRAY_WINDOWSPY, ID_TRAY_RELOADSCRIPT , ID_TRAY_EDITSCRIPT, ID_TRAY_SUSPEND, ID_TRAY_PAUSE, ID_TRAY_EXIT , ID_TRAY_SEP1, ID_TRAY_SEP2, ID_TRAY_LAST = ID_TRAY_SEP2 // But this value should never hit the below. There is debug code to enforce. , ID_MAIN_FIRST = 65400, ID_MAIN_LAST = 65534}; // These should match the range used by resource.h #define ERR_ABORT_NO_SPACES _T("The current thread will exit.") #define ERR_ABORT _T(" ") ERR_ABORT_NO_SPACES #define WILL_EXIT _T("The program will exit.") #define UNSTABLE_WILL_EXIT _T("The program is now unstable and will exit.") #define OLD_STILL_IN_EFFECT _T("The script was not reloaded; the old version will remain in effect.") #define ERR_SCRIPT_NOT_FOUND _T("Script file not found.") #define ERR_ABORT_DELETE _T("__Delete will now return.") #define ERR_WARNING_FOOTER _T("For more details, read the documentation for #Warn.") #define ERR_UNRECOGNIZED_ACTION _T("This line does not contain a recognized action.") #define ERR_NONEXISTENT_HOTKEY _T("Nonexistent hotkey.") #define ERR_NONEXISTENT_VARIANT _T("Nonexistent hotkey variant (HotIf).") #define ERR_NONEXISTENT_HOTSTRING _T("Nonexistent hotstring.") #define ERR_INVALID_HOTKEY _T("Invalid hotkey.") #define ERR_INVALID_KEYNAME _T("Invalid key name.") #define ERR_UNSUPPORTED_PREFIX _T("Unsupported prefix key.") #define ERR_ALTTAB_MODLR _T("This AltTab hotkey must specify which key (L or R).") #define ERR_ALTTAB_ONEMOD _T("This AltTab hotkey must have exactly one modifier/prefix.") #define ERR_NONEXISTENT_FUNCTION _T("Call to nonexistent function.") #define ERR_INVALID_INDEX _T("Invalid index.") #define ERR_INVALID_VALUE _T("Invalid value.") #define ERR_INVALID_FUNCTOR _T("Invalid callback function.") #define ERR_PARAM_INVALID _T("Invalid parameter(s).") #define ERR_PARAM_COUNT_INVALID _T("Invalid number of parameters.") #define ERR_PARAM1_INVALID _T("Parameter #1 invalid.") #define ERR_PARAM2_INVALID _T("Parameter #2 invalid.") #define ERR_PARAM3_INVALID _T("Parameter #3 invalid.") #define ERR_PARAM4_INVALID _T("Parameter #4 invalid.") #define ERR_PARAM5_INVALID _T("Parameter #5 invalid.") #define ERR_PARAM6_INVALID _T("Parameter #6 invalid.") #define ERR_PARAM7_INVALID _T("Parameter #7 invalid.") #define ERR_PARAM8_INVALID _T("Parameter #8 invalid.") #define ERR_PARAM1_REQUIRED _T("Parameter #1 required") #define ERR_PARAM2_REQUIRED _T("Parameter #2 required") #define ERR_PARAM3_REQUIRED _T("Parameter #3 required") #define ERR_PARAM1_MUST_NOT_BE_BLANK _T("Parameter #1 must not be blank in this case.") #define ERR_MISSING_OPEN_PAREN _T("Missing \"(\"") #define ERR_MISSING_OPEN_BRACE _T("Missing \"{\"") #define ERR_MISSING_CLOSE_PAREN _T("Missing \")\"") #define ERR_MISSING_CLOSE_BRACE _T("Missing \"}\"") #define ERR_MISSING_CLOSE_BRACKET _T("Missing \"]\"") // L31 #define ERR_UNEXPECTED_OPEN_BRACE _T("Unexpected \"{\"") #define ERR_PROPERTY_EMPTY_BRACKETS _T("Empty [] not permitted.") #define ERR_BAD_AUTO_CONCAT _T("Missing space or operator before this.") #define ERR_MISSING_CLOSE_QUOTE _T("Missing close-quote") // No period after short phrases. #define ERR_MISSING_COMMA _T("Missing comma") // #define ERR_MISSING_COLON _T("Missing \":\"") // #define ERR_MISSING_PARAM_NAME _T("Missing parameter name.") #define ERR_PARAM_REQUIRED _T("Missing a required parameter.") #define ERR_TOO_MANY_PARAMS _T("Too many parameters passed to function.") // L31 #define ERR_TOO_FEW_PARAMS _T("Too few parameters passed to function.") // L31 #define ERR_BAD_OPTIONAL_PARAM _T("Expected \":=\"") #define ERR_HOTKEY_FUNC_PARAMS _T("A hotkey function must not require more or less than 1 parameter.") #define ERR_HOTKEY_MISSING_BRACE _T("Hotkey or hotstring is missing its opening brace.") #define ERR_BAD_JUMP_INSIDE_FINALLY _T("Jumps cannot exit a FINALLY block.") #define ERR_OUTOFMEM _T("Out of memory.") // Used by RegEx too, so don't change it without also changing RegEx to keep the former string. #define ERR_NO_LABEL _T("Label not found in current scope.") #define ERR_INVALID_MENU_TYPE _T("Invalid menu type.") #define ERR_INVALID_MENU_ITEM _T("Nonexistent menu item.") #define ERR_DIVIDEBYZERO _T("Divide by zero.") #define ERR_EXP_ILLEGAL_CHAR _T("Illegal character in expression.") #define ERR_DUPLICATE_DECLARATION _T("Duplicate declaration.") #define ERR_UNEXPECTED_DECL _T("Unexpected declaration.") #define ERR_UNEXPECTED_DIRECTIVE _T("Unexpected directive.") #define ERR_INVALID_VARDECL _T("Invalid variable declaration.") #define ERR_INVALID_FUNCDECL _T("Invalid function declaration.") #define ERR_INVALID_CLASS_VAR _T("Invalid class variable declaration.") #define ERR_INVALID_LINE_IN_CLASS_DEF _T("Not a valid method, class or property definition.") #define ERR_INVALID_LINE_IN_PROPERTY_DEF _T("Not a valid property getter/setter.") #define ERR_INVALID_OPTION _T("Invalid option.") // Generic message used by the Gui system. #define ERR_GUI_NO_WINDOW _T("Gui has no window.") #define ERR_GUI_NOT_FOR_THIS_TYPE _T("Not supported for this control type.") // Used by GuiControl object and Control functions. #define ERR_DYNAMIC_BLANK _T("This dynamic variable is blank.") #define ERR_DYNAMIC_UPVAR _T("This dynamic variable is not included in this closure.") #define ERR_DYNAMIC_NOT_FOUND _T("Variable not found.") #define ERR_DYNAMIC_BAD_GLOBAL _T("This dynamic assignment requires a \"global\" declaration.") #define ERR_HOTKEY_IF_EXPR _T("Parameter #1 must match an existing #HotIf expression.") #define ERR_EXCEPTION _T("An exception was thrown.") #define ERR_INVALID_ASSIGNMENT _T("Invalid assignment.") #define ERR_EXPR_EVAL _T("Error evaluating expression.") #define ERR_EXPR_SYNTAX _T("Syntax error.") #define ERR_EXPR_MISSING_OPERAND _T("Missing operand.") #define ERR_TYPE_MISMATCH _T("Type mismatch.") #define ERR_NOT_ENUMERABLE _T("Value not enumerable.") #define ERR_PROPERTY_READONLY _T("Property is read-only.") #define ERR_NO_PROCESS _T("Target process not found.") #define ERR_NO_WINDOW _T("Target window not found.") #define ERR_NO_CONTROL _T("Target control not found.") #define ERR_NO_STATUSBAR _T("No StatusBar.") #define ERR_WINDOW_HAS_NO_MENU _T("Non-existent or unsupported menu.") #define ERR_PCRE_EXEC _T("PCRE execution error.") #define ERR_INVALID_ARG_TYPE _T("Invalid arg type.") #define ERR_INVALID_RETURN_TYPE _T("Invalid return type.") #define ERR_INVALID_LENGTH _T("Invalid Length.") #define ERR_INVALID_ENCODING _T("Invalid Encoding.") #define ERR_INVALID_USAGE _T("Invalid usage.") #define ERR_INVALID_BASE _T("Invalid base.") #define ERR_INTERNAL_CALL _T("An internal function call failed.") // Win32 function failed. Eventually an error message should be generated based on GetLastError(). #define ERR_FAILED _T("Failed") // A function failed to achieve its primary purpose for unspecified reason. Equivalent to v1 throwing 1 (ErrorLevel). #define ERR_LOAD_ICON _T("Can't load icon.") #define ERR_STRING_NOT_TERMINATED _T("String not null-terminated.") #define ERR_SOUND_DEVICE _T("Device not found") #define ERR_SOUND_COMPONENT _T("Component not found") #define ERR_SOUND_CONTROLTYPE _T("Component doesn't support this control type") #define ERR_TIMEOUT _T("Timeout") #define WARNING_LOCAL_SAME_AS_GLOBAL _T("This local variable has the same name as a global variable.") //---------------------------------------------------------------------------------- void DoIncrementalMouseMove(int aX1, int aY1, int aX2, int aY2, int aSpeed); DWORD ProcessExist(LPCTSTR aProcess, bool aGetParent = false, bool aVerifyPID = true); DWORD GetProcessName(DWORD aProcessID, LPTSTR aBuf, DWORD aBufSize, bool aGetNameOnly); FResult Shutdown(int nFlag); void Util_WinKill(HWND hWnd); enum MainWindowModes {MAIN_MODE_NO_CHANGE, MAIN_MODE_LINES, MAIN_MODE_VARS , MAIN_MODE_HOTKEYS, MAIN_MODE_KEYHISTORY, MAIN_MODE_REFRESH}; ResultType ShowMainWindow(MainWindowModes aMode = MAIN_MODE_NO_CHANGE, bool aRestricted = true); DWORD GetAHKInstallDir(LPTSTR aBuf); struct InputBoxType { LPCTSTR title; LPCTSTR text; LPCTSTR default_string; LPTSTR return_string; int width; int height; int xpos; int ypos; TCHAR password_char; bool set_password_char; DWORD timeout; HWND hwnd; ResultType UpdateResult(HWND hControl); }; // The following functions are used in GUI DPI scaling, so that // GUIs designed for a 96 DPI setting (i.e. using absolute coords // or explicit widths/sizes) can continue to run with mostly no issues. static inline int DPIScale(int x) { extern int g_ScreenDPI; return MulDiv(x, g_ScreenDPI, 96); } static inline int DPIUnscale(int x) { extern int g_ScreenDPI; return MulDiv(x, 96, g_ScreenDPI); } #define INPUTBOX_DEFAULT INT_MIN ResultType InputBoxParseOptions(LPCTSTR aOptions, InputBoxType &aInputBox); INT_PTR CALLBACK InputBoxProc(HWND hWndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); VOID CALLBACK InputBoxTimeout(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); VOID CALLBACK DerefTimeout(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); BOOL CALLBACK EnumChildFindSeqNum(HWND aWnd, LPARAM lParam); BOOL CALLBACK EnumChildFindPoint(HWND aWnd, LPARAM lParam); BOOL CALLBACK EnumChildGetControlList(HWND aWnd, LPARAM lParam); BOOL CALLBACK EnumChildGetText(HWND aWnd, LPARAM lParam); LRESULT CALLBACK MainWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); bool HandleMenuItem(HWND aHwnd, WORD aMenuItemID, HWND aGuiHwnd); FResult ControlGetClassNN(HWND aWindow, HWND aControl, LPTSTR aBuf, int aBufSize); typedef UINT LineNumberType; typedef WORD FileIndexType; // Use WORD to conserve memory due to its use in the Line class (adjacency to other members and due to 4-byte struct alignment). #define ABSOLUTE_MAX_SOURCE_FILES 0xFFFF // Keep this in sync with the capacity of the type above. Actually it could hold 0xFFFF+1, but avoid the final item for maintainability (otherwise max-index won't be able to fit inside a variable of that type). #define LOADING_FAILED UINT_MAX // -2 for the beginning and ending g_DerefChars: #define MAX_VAR_NAME_LENGTH (UCHAR_MAX - 2) #define MAX_FUNCTION_PARAMS UCHAR_MAX // Also conserves stack space to support future attributes such as param default values. typedef UINT DerefLengthType; typedef int DerefParamCountType; // Traditionally DerefType was used to hold var and func references, which are parsed at an // early stage, but when the capability to nest expressions between percent signs was added, // it became necessary to pre-parse more. All non-numeric operands are represented in it. enum DerefTypeType : BYTE { DT_VAR, // Variable reference, including built-ins. DT_DOUBLE, // Marks the end of a double-deref. DT_STRING, // Segment of text in a text arg (delimited by '%'). DT_QSTRING, // Segment of text in a quoted string (delimited by '%'). DT_WORDOP, // Word operator: and, or, not, new. DT_CONST_INT, // Constant integer value (true, false). DT_DOTPERCENT, // Dynamic member: .%name% DT_FUNCREF // Reference to function (for fat arrow functions). }; class Func; // Forward declaration for use below. struct DerefType { LPTSTR marker; union { Var *var; // DT_VAR Func *func; // DT_FUNCREF bool terminal; // DT_STRING SymbolType symbol; // DT_WORDOP int int_value; // DT_CONST_INT LPCTSTR error_marker; // DT_DOUBLE, DT_DOTPERCENT }; // Keep any fields that aren't an even multiple of 4 adjacent to each other. This conserves memory // due to byte-alignment: DerefTypeType type; UCHAR substring_count; DerefLengthType length; // Listed only after byte-sized fields, due to it being a WORD. }; struct CallSite { Func *func = nullptr; LPTSTR member = nullptr; int flags = IT_CALL; int param_count = 0; bool is_variadic() { return flags & EIF_VARIADIC; } void is_variadic(bool b) { if (b) flags |= EIF_VARIADIC; else flags &= ~EIF_VARIADIC; } void *operator new(size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void operator delete(void *aPtr) {} // Intentionally does nothing. void operator delete[](void *aPtr) {} }; typedef UCHAR ArgTypeType; // UCHAR vs. an enum, to save memory. typedef UINT ArgLengthType; #define ARG_TYPE_NORMAL (UCHAR)0 #define ARG_TYPE_INPUT_VAR (UCHAR)1 #define ARG_TYPE_OUTPUT_VAR (UCHAR)2 #define ARGMAP_END_MARKER ((ArgLengthType)~0) // ExpressionToPostfix() may rely on this being greater than any possible arg character offset. struct ArgStruct { ArgTypeType type; bool is_expression; // Whether this ARG is known to contain an expression. // Above are kept adjacent to each other to conserve memory (any fields that aren't an even // multiple of 4, if adjacent to each other, consume less memory due to default byte alignment // setting [which helps performance]). ArgLengthType length; // Keep adjacent to above so that it uses no extra memory. This member was added in v1.0.44.14 to improve runtime performance. LPTSTR text; DerefType *deref; // Will hold a NULL-terminated array of operands/word-operators pre-parsed by ParseDerefs()/ParseOperands(). ExprTokenType *postfix; // An array of tokens in postfix order. int max_stack, max_alloc; }; enum FuncDefType : UCHAR { FuncDefNormal = FALSE, FuncDefFatArrow, FuncDefExpression, FuncDefExpressionResolved }; __int64 pow_ll(__int64 base, __int64 exp); // integer power function #define _f__oneline(act) do { act } while (0) // Make the macro safe to use like a function, under if(), etc. #define _f__ret(act) _f__oneline( act; return; ) // BIFs have no return value. // The following macros are used in built-in functions and objects to reduce code repetition // and facilitate changes to the script "ABI" (i.e. the way in which parameters and return // values are passed around). For instance, the built-in functions might someday be exposed // via COM IDispatch or coupled with different scripting languages. #define _f_return(...) _f__ret(aResultToken.Return(__VA_ARGS__)) #define _f_throw(...) _f__ret(aResultToken.Error(__VA_ARGS__)) #define _f_throw_param(_prm_, ...) return ((void)aResultToken.ParamError(_prm_, aParam[_prm_], __VA_ARGS__)) #define _f_throw_win32(...) return ((void)aResultToken.Win32Error(__VA_ARGS__)) #define _f_throw_value(...) return ((void)aResultToken.ValueError(__VA_ARGS__)) #define _f_throw_type(...) return ((void)aResultToken.TypeError(__VA_ARGS__)) #define _f_throw_oom return ((void)aResultToken.MemoryError()) #define _f_return_FAIL _f__ret(aResultToken.SetExitResult(FAIL)) // The _f_set_retval macros should be used with care because the integer macros assume symbol // is set to its default value; i.e. don't set a string and then attempt to return an integer. // It is also best for maintainability to avoid setting mem_to_free or an object without // returning if there's any chance _f_throw() will be used, since in that case the caller // may or may not Free() the result. _f_set_retval_i() may also invalidate _f_retval_buf. //#define _f_set_retval(...) aResultToken.Return(__VA_ARGS__) // Overrides the default return value but doesn't return. #define _f_set_retval_i(n) (aResultToken.value_int64 = static_cast<__int64>(n)) // Assumes symbol == SYM_INTEGER, the default for BIFs. #define _f_set_retval_p(...) aResultToken.ReturnPtr(__VA_ARGS__) // Overrides the default return value but doesn't return. Arg must already be in persistent memory. #define _f_return_i(n) _f__ret(_f_set_retval_i(n)) // Return an integer. Reduces code size vs _f_return() by assuming symbol == SYM_INTEGER, the default for BIFs. #define _f_return_b(b) _f_return_i((bool)(b)) // Boolean. Currently just returns an int because we have no boolean type. #define _f_return_p(...) _f__ret(_f_set_retval_p(__VA_ARGS__)) // Return a string which is already in persistent memory. #define _f_return_retval return // Return the value set by _f_set_retval(). #define _f_return_empty _f_return_p(_T(""), 0) #define _f_return_unset _f__ret(aResultToken.symbol = SYM_MISSING) #define _f_retval_buf (aResultToken.buf) #define _f_retval_buf_size MAX_NUMBER_SIZE #define _f_number_buf _f_retval_buf // An alias to show intended usage, and in case the buffer size is changed. #define _f_callee_id (aResultToken.func->mFID) // The _o_ macros originally needed different implementations due to differences between the // function signature for methods and that for built-in functions. Currently they're similar // enough that most of these macros can just be aliases (kept for maintainability). #define _o__ret _f__ret #define _o_throw _f_throw #define _o_throw_param _f_throw_param #define _o_throw_win32 _f_throw_win32 #define _o_throw_value _f_throw_value #define _o_throw_type _f_throw_type #define _o_throw_oom _f_throw_oom #define _o_return _f_return #define _o_return_p _f_return_p #define _o_return_FAIL _f_return_FAIL #define _o_return_retval _f_return_retval #define _o_return_empty _o_return_retval // Default return value for Invoke is "". #define _o_return_unset return (void)(aResultToken.symbol = SYM_MISSING) struct LoopFilesStruct : WIN32_FIND_DATA { // Note that using fixed buffer sizes significantly reduces code size vs. using CString // or probably any other method of dynamically allocating/expanding the buffers. It also // performs marginally better, but file system performance has a much bigger impact. // Unicode builds allow for the maximum path size supported by Win32 as of 2018, although // in some cases the script might need to use the \\?\ prefix to go beyond MAX_PATH. // On Windows 10 v1607+, MAX_PATH limits can be lifted by opting-in to long path support // via the application's manifest and LongPathsEnabled registry setting. In any case, // ANSI APIs are still limited to MAX_PATH, but MAX_PATH*2 allows for the longest path // supported by FindFirstFile() concatenated with the longest filename it can return. // This preserves backward-compatibility under the following set of conditions: // 1) the absolute path and pattern fits within MAX_PATH; // 2) the relative path and filename fits within MAX_PATH; and // 3) the absolute path and filename exceeds MAX_PATH. static const size_t BUF_SIZE = UorA(MAX_WIDE_PATH, MAX_PATH*2); // file_path contains the full path of the directory being looped, with trailing slash. // Temporarily also contains the pattern for FindFirstFile(), which is either a copy of // 'pattern' or "*" for scanning sub-directories. // During execution of the loop body, it contains the full path of the file. TCHAR file_path[BUF_SIZE]; TCHAR pattern[MAX_PATH]; // Naked filename or pattern. Allows max NTFS filename length plus a few chars. TCHAR short_path[BUF_SIZE]; // Short name version of orig_dir. TCHAR *file_path_suffix; // The dynamic part of file_path (used by A_LoopFilePath). TCHAR *orig_dir; // Initial directory as specified by caller (used by A_LoopFilePath). TCHAR *long_dir; // Full/long path of initial directory (used by A_LoopFileLongPath). size_t file_path_length, pattern_length, short_path_length, orig_dir_length, long_dir_length , dir_length; // Portion of file_path which is the directory, used by BIVs. LoopFilesStruct() : orig_dir_length(0), long_dir(NULL) {} ~LoopFilesStruct() { if (orig_dir_length) free(orig_dir); //else: orig_dir is the constant _T(""). free(long_dir); } }; // Some of these lengths and such are based on the MSDN example at // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/enumerating_registry_subkeys.asp: // FIX FOR v1.0.48: // OLDER (v1.0.44.07): Someone reported that a stack overflow was possible, implying that it only happens // during extremely deep nesting of subkey names (perhaps a hundred or more nested subkeys). Upon review, it seems // that the prior limit of 16383 for value-name-length is higher than needed; testing shows that a value name can't // be longer than 259 (limit might even be 255 if API vs. RegEdit is used to create the name). Testing also shows // that the total path name of a registry item (including item/value name but excluding the name of the root key) // obeys the same limit BUT ONLY within the RegEdit GUI. RegEdit seems capable of importing subkeys whose names // (even without any value name appended) are longer than 259 characters (see comments higher above). #define MAX_REG_ITEM_SIZE 1024 // Needs to be greater than 260 (see comments above), but I couldn't find any documentation at MSDN or the web about the max length of a subkey name. One example at MSDN RegEnumKeyEx() uses MAX_KEY_LENGTH=255 and MAX_VALUE_NAME=16383, but clearly MAX_KEY_LENGTH should be larger. #define REG_SUBKEY -2 // Custom type, not standard in Windows. struct RegItemStruct { HKEY root_key_type, root_key; // root_key_type is always a local HKEY, whereas root_key can be a remote handle. TCHAR subkey[MAX_REG_ITEM_SIZE]; // The branch of the registry where this subkey or value is located. TCHAR name[MAX_REG_ITEM_SIZE]; // The subkey or value name. DWORD type; // Value Type (e.g REG_DWORD). FILETIME ftLastWriteTime; // Non-initialized. void InitForValues() {ftLastWriteTime.dwHighDateTime = ftLastWriteTime.dwLowDateTime = 0;} void InitForSubkeys() {type = REG_SUBKEY;} // To distinguish REG_DWORD and such from the subkeys themselves. RegItemStruct(HKEY aRootKeyType, HKEY aRootKey, LPTSTR aSubKey) : root_key_type(aRootKeyType), root_key(aRootKey), type(REG_NONE) { *name = '\0'; // Make a local copy on the caller's stack so that if the current script subroutine is // interrupted to allow another to run, the contents of the deref buffer is saved here: tcslcpy(subkey, aSubKey, _countof(subkey)); // Even though the call may work with a trailing backslash, it's best to remove it // so that consistent results are delivered to the user. For example, if the script // is enumerating recursively into a subkey, subkeys deeper down will not include the // trailing backslash when they are reported. So the user's own subkey should not // have one either so that when A_ScriptSubKey is referenced in the script, it will // always show up as the value without a trailing backslash: size_t length = _tcslen(subkey); if (length && subkey[length - 1] == '\\') subkey[length - 1] = '\0'; } }; class TextStream; // TextIO struct LoopReadFileStruct { TextStream *mWriteFile; // Currently no need for mReadFile, so it's left as a local variable of PerformLoopRead(). LPTSTR mWriteFileName; #define READ_FILE_LINE_SIZE (64 * 1024) TCHAR mCurrentLine[READ_FILE_LINE_SIZE]; LoopReadFileStruct(LPTSTR aWriteFileName) : mWriteFile(nullptr) // mWriteFile is opened by FileAppend() only upon first use. , mWriteFileName(aWriteFileName) // Caller has passed the result of _tcsdup() for us to take over. { *mCurrentLine = '\0'; } ~LoopReadFileStruct() { free(mWriteFileName); } }; // TextStream flags for LoadIncludedFile (script files) and file-reading loops. // Do not lock read/write: older versions used fopen(), which is implicitly permissive. #define DEFAULT_READ_FLAGS (TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR | TextStream::SHARE_READ | TextStream::SHARE_WRITE) struct CatchStatementArgs { Var *output_var; IObject **prototype; int prototype_count; }; typedef UCHAR ArgCountType; #define MAX_ARGS 20 // Maximum number of args used by any command. enum DllArgTypes { DLL_ARG_INVALID , DLL_ARG_ASTR , DLL_ARG_INT , DLL_ARG_SHORT , DLL_ARG_CHAR , DLL_ARG_INT64 , DLL_ARG_FLOAT , DLL_ARG_DOUBLE , DLL_ARG_WSTR , DLL_ARG_STRUCT , DLL_ARG_STR = UorA(DLL_ARG_WSTR, DLL_ARG_ASTR) , DLL_ARG_xSTR = UorA(DLL_ARG_ASTR, DLL_ARG_WSTR) // To simplify some sections. }; // Some sections might rely on DLL_ARG_INVALID being 0. // Note that currently this value must fit into a sc_type variable because that is how TextToKey() // stores it in the hotkey class. sc_type is currently a UINT, and will always be at least a // WORD in size, so it shouldn't be much of an issue: #define MAX_JOYSTICKS 16 // The maximum allowed by any Windows operating system. #define MAX_JOY_BUTTONS 32 // Also the max that Windows supports. enum JoyControls {JOYCTRL_INVALID, JOYCTRL_XPOS, JOYCTRL_YPOS, JOYCTRL_ZPOS , JOYCTRL_RPOS, JOYCTRL_UPOS, JOYCTRL_VPOS, JOYCTRL_POV , JOYCTRL_NAME, JOYCTRL_BUTTONS, JOYCTRL_AXES, JOYCTRL_INFO , JOYCTRL_1, JOYCTRL_2, JOYCTRL_3, JOYCTRL_4, JOYCTRL_5, JOYCTRL_6, JOYCTRL_7, JOYCTRL_8 // Buttons. , JOYCTRL_9, JOYCTRL_10, JOYCTRL_11, JOYCTRL_12, JOYCTRL_13, JOYCTRL_14, JOYCTRL_15, JOYCTRL_16 , JOYCTRL_17, JOYCTRL_18, JOYCTRL_19, JOYCTRL_20, JOYCTRL_21, JOYCTRL_22, JOYCTRL_23, JOYCTRL_24 , JOYCTRL_25, JOYCTRL_26, JOYCTRL_27, JOYCTRL_28, JOYCTRL_29, JOYCTRL_30, JOYCTRL_31, JOYCTRL_32 , JOYCTRL_BUTTON_MAX = JOYCTRL_32 }; #define IS_JOYSTICK_BUTTON(joy) (joy >= JOYCTRL_1 && joy <= JOYCTRL_BUTTON_MAX) // Each line in the enumeration below corresponds to a group of built-in functions (defined // in g_BIF) which are implemented using a single C++ function. These IDs are passed to the // C++ function to tell it which function is being called. Each group starts at ID 0 in case // it helps the compiler to reduce code size. enum BuiltInFunctionID { FID_Object_New = -1, FID_GetMethod = 0, FID_HasMethod, FID_DllCall = 0, FID_ComCall, FID_TV_Add = 0, FID_TV_Modify, FID_TV_Delete, FID_TV_GetNext = 0, FID_TV_GetPrev, FID_TV_GetParent, FID_TV_GetChild, FID_TV_GetSelection, FID_TV_GetCount, FID_TV_Get = 0, FID_TV_GetText, FID_Trim = 0, FID_LTrim, FID_RTrim, FID_Input = 0, FID_InputEnd, FID_GetKeyName = 0, FID_GetKeyVK = 1, FID_GetKeySC, FID_StrLower = 0, FID_StrUpper, FID_StrTitle, FID_StrGet = 0, FID_StrPut, FID_WinExist = 0, FID_WinActive, FID_Floor = 0, FID_Ceil, FID_ASin = 0, FID_ACos, FID_Sqrt = 0, FID_Log, FID_Ln, FID_Min = 0, FID_Max, FID_ObjAddRef = 0, FID_ObjRelease, FID_ObjHasOwnProp = 0, FID_ObjOwnPropCount, FID_ObjGetCapacity, FID_ObjSetCapacity, FID_ObjOwnProps, FID_ObjGetBase = 0, FID_ObjSetBase, FID_ObjPtr = 0, FID_ObjPtrAddRef, FID_ObjFromPtr, FID_ObjFromPtrAddRef, FID_WinGetPos = 0, FID_WinGetClientPos, FID_WinMoveBottom = 0, FID_WinMoveTop, FID_WinShow = 0, FID_WinHide, FID_WinMinimize, FID_WinMaximize, FID_WinRestore, FID_WinClose, FID_WinKill, FID_WinActivate = 0, FID_WinActivateBottom, FID_ControlSend = SCM_NOT_RAW, FID_ControlSendText = SCM_RAW_TEXT, FID_PostMessage = 0, FID_SendMessage, FID_RegRead = 0, FID_RegWrite, FID_RegCreateKey, FID_RegDelete, FID_RegDeleteKey, FID_SoundGetVolume = 0, FID_SoundGetMute, FID_SoundGetName, FID_SoundGetInterface, FID_SoundSetVolume, FID_SoundSetMute, FID_WinWait = 0, FID_WinWaitClose, FID_WinWaitActive, FID_WinWaitNotActive, // Hotkey/HotIf/... FID_HotIfWinActive = HOT_IF_ACTIVE, FID_HotIfWinNotActive = HOT_IF_NOT_ACTIVE, FID_HotIfWinExist = HOT_IF_EXIST, FID_HotIfWinNotExist = HOT_IF_NOT_EXIST, FID_Hotkey, FID_HotIf }; enum ThreadCommands {THREAD_CMD_INVALID, THREAD_CMD_PRIORITY, THREAD_CMD_INTERRUPT, THREAD_CMD_NOTIMERS}; class Label; // Forward declaration so that each can use the other. class Line { private: ResultType EvaluateCondition(); ResultType EvaluateSwitchCase(ExprTokenType &aSwitch, SymbolType aSwitchIsNumeric, ExprTokenType &aCase, StringCaseSenseType aStringCaseSense); bool EvaluateLoopUntil(ResultType &aResult); ResultType PerformLoop(ResultToken *aResultToken, Line *&aJumpToLine, Line *aUntil , __int64 aIterationLimit, bool aIsInfinite); ResultType PerformLoopFilePattern(ResultToken *aResultToken, Line *&aJumpToLine, Line *aUntil , FileLoopModeType aFileLoopMode, bool aRecurseSubfolders, LPTSTR aFilePattern); bool ParseLoopFilePattern(LPTSTR aFilePattern, LoopFilesStruct &lfs, ResultType &aResult); ResultType PerformLoopFilePattern(ResultToken *aResultToken, Line *&aJumpToLine, Line *aUntil , FileLoopModeType aFileLoopMode, bool aRecurseSubfolders, LoopFilesStruct &lfs); ResultType PerformLoopReg(ResultToken *aResultToken, Line *&aJumpToLine, Line *aUntil , FileLoopModeType aFileLoopMode, bool aRecurseSubfolders, HKEY aRootKeyType, HKEY aRootKey, LPTSTR aRegSubkey); ResultType PerformLoopParse(ResultToken *aResultToken, Line *&aJumpToLine, Line *aUntil); ResultType PerformLoopParseCSV(ResultToken *aResultToken, Line *&aJumpToLine, Line *aUntil); ResultType PerformLoopReadFile(ResultToken *aResultToken, Line *&aJumpToLine, Line *aUntil, LPTSTR aReadFileName, LPTSTR aWriteFileName); ResultType PerformLoopWhile(ResultToken *aResultToken, Line *&aJumpToLine); // Lexikos: ACT_WHILE. ResultType PerformLoopFor(ResultToken *aResultToken, Line *&aJumpToLine, Line *aUntil); // Lexikos: ACT_FOR. ResultType PerformAssign(); bool CatchThis(ExprTokenType &aThrown); public: #define SET_S_DEREF_BUF(ptr, size) Line::sDerefBuf = ptr, Line::sDerefBufSize = size #define NULLIFY_S_DEREF_BUF \ {\ SET_S_DEREF_BUF(NULL, 0);\ if (sDerefBufSize > LARGE_DEREF_BUF_SIZE)\ --sLargeDerefBufs;\ } #define PRIVATIZE_S_DEREF_BUF \ LPTSTR our_deref_buf = Line::sDerefBuf;\ size_t our_deref_buf_size = Line::sDerefBufSize;\ SET_S_DEREF_BUF(NULL, 0) // For detecting whether ExpandExpression() caused a new buffer to be created. #define DEPRIVATIZE_S_DEREF_BUF \ if (our_deref_buf)\ {\ if (Line::sDerefBuf)\ {\ free(Line::sDerefBuf);\ if (Line::sDerefBufSize > LARGE_DEREF_BUF_SIZE)\ --Line::sLargeDerefBufs;\ }\ SET_S_DEREF_BUF(our_deref_buf, our_deref_buf_size);\ } //else the original buffer is NULL, so keep any new sDerefBuf that might have been created (should // help avg-case performance). static LPTSTR sDerefBuf; // Buffer to hold the values of any args that need to be dereferenced. static size_t sDerefBufSize; static int sLargeDerefBufs; // Static because only one line can be Expanded at a time (not to mention the fact that we // wouldn't want the size of each line to be expanded by this size): static LPTSTR sArgDeref[MAX_ARGS]; // Keep any fields that aren't an even multiple of 4 adjacent to each other. This conserves memory // due to byte-alignment: ActionTypeType mActionType; // What type of line this is. ArgCountType mArgc; // How many arguments exist in mArg[]. FileIndexType mFileIndex; // Which file the line came from. 0 is the first, and it's the main script file. LineNumberType mLineNumber; // The line number in the file from which the script was loaded, for debugging. ArgStruct *mArg; // Will be used to hold a dynamic array of dynamic Args. AttributeType mAttribute; Line *mPrevLine, *mNextLine; // The prev & next lines adjacent to this one in the linked list; NULL if none. Line *mRelatedLine; // e.g. the "else" that belongs to this "if" Line *mParentLine; // Indicates the parent (owner) of this line. #ifdef CONFIG_DEBUGGER Breakpoint *mBreakpoint; #endif // Probably best to always use ARG1 even if other things have supposedly verified // that it exists, since it's count-check should make the dereference of a NULL // pointer (or accessing non-existent array elements) virtually impossible. // Empty-string is probably more universally useful than NULL, since some // API calls and other functions might not appreciate receiving NULLs. In addition, // always remembering to have to check for NULL makes things harder to maintain // and more bug-prone. The below macros rely upon the fact that the individual // elements of mArg cannot be NULL (because they're explicitly set to be blank // when the user has omitted an arg in between two non-blank args). Later, might // want to review if any of the API calls used expect a string whose contents are // modifiable. #define RAW_ARG1 (mArgc > 0 ? mArg[0].text : _T("")) #define RAW_ARG2 (mArgc > 1 ? mArg[1].text : _T("")) #define RAW_ARG3 (mArgc > 2 ? mArg[2].text : _T("")) #define RAW_ARG4 (mArgc > 3 ? mArg[3].text : _T("")) #define RAW_ARG5 (mArgc > 4 ? mArg[4].text : _T("")) #define RAW_ARG6 (mArgc > 5 ? mArg[5].text : _T("")) #define RAW_ARG7 (mArgc > 6 ? mArg[6].text : _T("")) #define RAW_ARG8 (mArgc > 7 ? mArg[7].text : _T("")) #define LINE_RAW_ARG1 (line->mArgc > 0 ? line->mArg[0].text : _T("")) #define LINE_RAW_ARG2 (line->mArgc > 1 ? line->mArg[1].text : _T("")) #define LINE_RAW_ARG3 (line->mArgc > 2 ? line->mArg[2].text : _T("")) #define LINE_RAW_ARG4 (line->mArgc > 3 ? line->mArg[3].text : _T("")) #define LINE_RAW_ARG5 (line->mArgc > 4 ? line->mArg[4].text : _T("")) #define LINE_RAW_ARG6 (line->mArgc > 5 ? line->mArg[5].text : _T("")) #define LINE_RAW_ARG7 (line->mArgc > 6 ? line->mArg[6].text : _T("")) #define LINE_RAW_ARG8 (line->mArgc > 7 ? line->mArg[7].text : _T("")) #define LINE_RAW_ARG9 (line->mArgc > 8 ? line->mArg[8].text : _T("")) #define NEW_RAW_ARG1 (aArgc > 0 ? new_arg[0].text : _T("")) // Helps performance to use this vs. LINE_RAW_ARG where possible. #define NEW_RAW_ARG2 (aArgc > 1 ? new_arg[1].text : _T("")) #define NEW_RAW_ARG3 (aArgc > 2 ? new_arg[2].text : _T("")) #define NEW_RAW_ARG4 (aArgc > 3 ? new_arg[3].text : _T("")) #define NEW_RAW_ARG5 (aArgc > 4 ? new_arg[4].text : _T("")) #define NEW_RAW_ARG6 (aArgc > 5 ? new_arg[5].text : _T("")) #define NEW_RAW_ARG7 (aArgc > 6 ? new_arg[6].text : _T("")) #define NEW_RAW_ARG8 (aArgc > 7 ? new_arg[7].text : _T("")) #define NEW_RAW_ARG9 (aArgc > 8 ? new_arg[8].text : _T("")) #define SAVED_ARG1 (mArgc > 0 ? arg[0] : _T("")) #define SAVED_ARG2 (mArgc > 1 ? arg[1] : _T("")) #define SAVED_ARG3 (mArgc > 2 ? arg[2] : _T("")) #define SAVED_ARG4 (mArgc > 3 ? arg[3] : _T("")) #define SAVED_ARG5 (mArgc > 4 ? arg[4] : _T("")) #define ARG1 sArgDeref[0] // These are the expanded/resolved parameters for the currently-executing command. #define ARG2 sArgDeref[1] // They're populated by ExpandArgs(). #define ARG3 sArgDeref[2] #define ARG4 sArgDeref[3] #define ARG5 sArgDeref[4] #define ARG6 sArgDeref[5] #define ARG7 sArgDeref[6] #define ARG8 sArgDeref[7] #define ARG9 sArgDeref[8] #define ARG10 sArgDeref[9] #define ARG11 sArgDeref[10] #define TWO_ARGS ARG1, ARG2 #define THREE_ARGS ARG1, ARG2, ARG3 #define FOUR_ARGS ARG1, ARG2, ARG3, ARG4 #define FIVE_ARGS ARG1, ARG2, ARG3, ARG4, ARG5 #define SIX_ARGS ARG1, ARG2, ARG3, ARG4, ARG5, ARG6 #define SEVEN_ARGS ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7 #define EIGHT_ARGS ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7, ARG8 #define NINE_ARGS ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7, ARG8, ARG9 #define TEN_ARGS ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7, ARG8, ARG9, ARG10 #define ELEVEN_ARGS ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7, ARG8, ARG9, ARG10, ARG11 // If the arg's text is non-blank, it means the variable is a dynamic name such as array%i% // that must be resolved at runtime rather than load-time. Therefore, this macro must not // be used without first having checked that arg.text is blank: #define VAR(arg) ((Var *)arg.deref) // Uses arg number (i.e. the first arg is 1, not 0). Caller must ensure that ArgNum >= 1 and that // the arg in question is an input or output variable (since that isn't checked there). //#define ARG_HAS_VAR(ArgNum) (mArgc >= ArgNum && (*mArg[ArgNum-1].text || mArg[ArgNum-1].deref)) // Shouldn't go much higher than 400 since the main window's Edit control is currently limited // to 64KB to be compatible with the Win9x limit. Avg. line length is probably under 100 for // the vast majority of scripts, so 400 seems unlikely to exceed the buffer size. Even in the // worst case where the buffer size is exceeded, the text is simply truncated, so it's not too bad: #define LINE_LOG_SIZE 400 // See above. static Line *sLog[LINE_LOG_SIZE]; static DWORD sLogTick[LINE_LOG_SIZE]; static int sLogNext; #ifdef AUTOHOTKEYSC // Reduces code size to omit things that are unused, and helps catch bugs at compile-time. static LPTSTR sSourceFile[1]; // Only need to be able to hold the main script since compiled scripts don't support dynamic including. #else static LPTSTR *sSourceFile; // Will hold an array of strings. static int sMaxSourceFiles; // Maximum number of items it can currently hold. #endif static int sSourceFileCount; // Number of items in the above array. static void FreeDerefBufIfLarge(); ResultType ExecUntil(ExecUntilMode aMode, ResultToken *aResultToken = NULL, Line **apJumpToLine = NULL); // The following are characters that can't legally occur after a binary operator. It excludes all unary operators // "!~*&-+" as well as the parentheses chars "()": #define EXPR_CORE _T("<>=/|^,?:") // The characters common to both EXPR_TELLTALES (obsolete) and EXPR_OPERAND_TERMINATORS: #define EXPR_COMMON _T(" \t") EXPR_CORE _T("*&~!()[]{}") // Space and Tab are included at the beginning for performance. L31: Added [] for array-like syntax. #define CONTINUATION_LINE_SYMBOLS EXPR_CORE _T(".+-*&!~") // v1.0.46. #define EXPR_OPERATOR_SYMBOLS CONTINUATION_LINE_SYMBOLS // The set of operator symbols which can't appear at the end of a valid expression, plus '+' and '-' (which are valid for ++/--). // Characters that mark the end of an operand inside an expression. Double-quote must not be included: #define EXPR_OPERAND_TERMINATORS_EX_DOT EXPR_COMMON _T("%+-\n") // L31: Used in a few places where '.' needs special treatment. #define EXPR_OPERAND_TERMINATORS EXPR_OPERAND_TERMINATORS_EX_DOT _T(".") // L31: Used in expressions where '.' is always an operator. #define EXPR_ALL_SYMBOLS EXPR_OPERAND_TERMINATORS _T("\"'") #define EXPR_SYMBOLS_AFTER_MAYBE _T("),]}:?") // Excludes '.', which needs more complicated logic. // The following HOTSTRING option recognizer is kept somewhat forgiving/non-specific for backward compatibility // (e.g. scripts may have some invalid hotstring options, which are simply ignored). This definition is here // because it's related to continuation line symbols. Also, avoid ever adding "&" to hotstring options because // it might introduce ambiguity in the differentiation of things like: // : & x::hotkey action // : & *::abbrev with leading colon:: #define IS_HOTSTRING_OPTION(chr) (cisalnum(chr) || _tcschr(_T("?*- \t"), chr)) #define ArgLength(aArgNum) ArgIndexLength((aArgNum)-1) #define ArgToInt64(aArgNum) ArgIndexToInt64((aArgNum)-1) #define ArgToInt(aArgNum) (int)ArgToInt64(aArgNum) // Benchmarks show that having a "real" ArgToInt() that calls ATOI vs. ATOI64 (and ToInt() vs. ToInt64()) doesn't measurably improve performance. #define ArgToUInt(aArgNum) (UINT)ArgToInt64(aArgNum) // Similar to what ATOU() does. __int64 ArgIndexToInt64(int aArgIndex); size_t ArgIndexLength(int aArgIndex); ResultType ExpandArgs(ResultToken *aResultTokens = NULL); VarSizeType GetExpandedArgSize(); LPTSTR ExpandExpression(int aArgIndex, ResultType &aResult, ResultToken *aResultToken , LPTSTR &aTarget, LPTSTR &aDerefBuf, size_t &aDerefBufSize, LPTSTR aArgDeref[], size_t aExtraSize); ResultType ExpandSingleArg(int aArgIndex, ResultToken &aResultToken, LPTSTR &aDerefBuf, size_t &aDerefBufSize); ResultType ExpressionToPostfix(ArgStruct &aArg); ResultType ExpressionToPostfix(ArgStruct &aArg, ExprTokenType *&aInfix); ResultType FinalizeExpression(ArgStruct &aArg); static bool FileIsFilteredOut(LoopFilesStruct &aCurrentFile, FileLoopModeType aFileLoopMode); Label *GetJumpTarget(bool aIsDereferenced); Label *IsJumpValid(Label &aTargetLabel, bool aSilent = false); BOOL CheckValidFinallyJump(Line* jumpTarget, bool aSilent = false); static HWND DetermineTargetWindow(LPCTSTR aTitle, LPCTSTR aText, LPCTSTR aExcludeTitle, LPCTSTR aExcludeText); static ArgTypeType ArgIsVar(ActionTypeType aActionType, int aArgIndex, int aArgCount) { if (aActionType == ACT_ASSIGNEXPR && aArgIndex == 0 || aActionType == ACT_FOR && aArgIndex != aArgCount - 1) return ARG_TYPE_OUTPUT_VAR; return ARG_TYPE_NORMAL; } #define ArgHasDeref(aArgNum) ArgIndexHasDeref((aArgNum)-1) // Returns true if this arg requires evaluation at runtime. // Caller must ensure that aArgIndex is 0 or greater. bool ArgIndexHasDeref(int aArgIndex) { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // Arg doesn't exist. return false; ArgStruct &arg = mArg[aArgIndex]; // For performance. if (arg.type == ARG_TYPE_NORMAL) // Simple literal values are converted to non-expressions where possible, // so if this is true, the arg requires evaluation at runtime: return arg.is_expression; else // ARG_TYPE_INPUT_VAR is currently only used by ExpressionToPostfix(); // i.e. when the expression is just a simple variable reference. return (arg.type == ARG_TYPE_INPUT_VAR); } static HKEY RegConvertKey(LPTSTR aBuf, LPTSTR *aSubkey = NULL, bool *aIsRemoteRegistry = NULL) { const size_t COMPUTER_NAME_BUF_SIZE = 128; LPTSTR key_name_pos = aBuf, computer_name_end = NULL; if (*aBuf == '\\' && aBuf[1] == '\\') // Something like \\ComputerName\HKLM. { if ( !(computer_name_end = _tcschr(aBuf + 2, '\\')) || (computer_name_end - aBuf) >= COMPUTER_NAME_BUF_SIZE ) return NULL; key_name_pos = computer_name_end + 1; } // Copy root key name into temporary buffer for use by _tcsicmp(). TCHAR key_name[20]; int i; for (i = 0; key_name_pos[i] && key_name_pos[i] != '\\'; ++i) { if (i == 19) return NULL; // Too long to be valid. key_name[i] = key_name_pos[i]; } key_name[i] = '\0'; // Set output parameters for caller. if (aSubkey) *aSubkey = key_name_pos + i + (key_name_pos[i] == '\\'); if (aIsRemoteRegistry) *aIsRemoteRegistry = (computer_name_end != NULL); HKEY root_key = RegConvertRootKeyType(key_name); if (!root_key) // Invalid or unsupported root key name. return NULL; if (!aIsRemoteRegistry || !computer_name_end) // Either caller didn't want it opened, or it doesn't need to be. return root_key; // If it's a remote key, this value should only be used by the caller as an indicator. // Otherwise, it's a remote computer whose registry the caller wants us to open: // It seems best to require the two leading backslashes in case the computer name contains // spaces (just in case spaces are allowed on some OSes or perhaps for Unix interoperability, etc.). // Therefore, make no attempt to trim leading and trailing spaces from the computer name: TCHAR computer_name[COMPUTER_NAME_BUF_SIZE]; tcslcpy(computer_name, aBuf, _countof(computer_name)); computer_name[computer_name_end - aBuf] = '\0'; HKEY remote_key; return (RegConnectRegistry(computer_name, root_key, &remote_key) == ERROR_SUCCESS) ? remote_key : NULL; } static HKEY RegConvertRootKeyType(LPTSTR aName); static LPTSTR RegConvertRootKeyType(HKEY aKey); static int RegConvertValueType(LPTSTR aValueType) { if (!_tcsicmp(aValueType, _T("REG_SZ"))) return REG_SZ; if (!_tcsicmp(aValueType, _T("REG_EXPAND_SZ"))) return REG_EXPAND_SZ; if (!_tcsicmp(aValueType, _T("REG_MULTI_SZ"))) return REG_MULTI_SZ; if (!_tcsicmp(aValueType, _T("REG_DWORD"))) return REG_DWORD; if (!_tcsicmp(aValueType, _T("REG_BINARY"))) return REG_BINARY; return REG_NONE; // Unknown or unsupported type. } static LPTSTR RegConvertValueType(DWORD aValueType) { switch(aValueType) { case REG_SZ: return _T("REG_SZ"); case REG_EXPAND_SZ: return _T("REG_EXPAND_SZ"); case REG_BINARY: return _T("REG_BINARY"); case REG_DWORD: return _T("REG_DWORD"); case REG_DWORD_BIG_ENDIAN: return _T("REG_DWORD_BIG_ENDIAN"); case REG_LINK: return _T("REG_LINK"); case REG_MULTI_SZ: return _T("REG_MULTI_SZ"); case REG_RESOURCE_LIST: return _T("REG_RESOURCE_LIST"); case REG_FULL_RESOURCE_DESCRIPTOR: return _T("REG_FULL_RESOURCE_DESCRIPTOR"); case REG_RESOURCE_REQUIREMENTS_LIST: return _T("REG_RESOURCE_REQUIREMENTS_LIST"); case REG_QWORD: return _T("REG_QWORD"); case REG_SUBKEY: return _T("KEY"); // Custom (non-standard) type. default: return _T(""); // Make it be the empty string for REG_NONE and anything else. } } static DWORD RegConvertView(LPCTSTR aBuf) { if (!_tcsicmp(aBuf, _T("Default"))) return 0; else if (!_tcscmp(aBuf, _T("32"))) return KEY_WOW64_32KEY; else if (!_tcscmp(aBuf, _T("64"))) return KEY_WOW64_64KEY; else return -1; } static TitleMatchModes ConvertTitleMatchMode(LPCTSTR aBuf) { if (!aBuf || !*aBuf) return MATCHMODE_INVALID; if (*aBuf == '1' && !*(aBuf + 1)) return FIND_IN_LEADING_PART; if (*aBuf == '2' && !*(aBuf + 1)) return FIND_ANYWHERE; if (*aBuf == '3' && !*(aBuf + 1)) return FIND_EXACT; if (!_tcsicmp(aBuf, _T("RegEx"))) return FIND_REGEX; // Goes with the above, not fast/slow below. if (!_tcsicmp(aBuf, _T("Fast"))) return FIND_FAST; if (!_tcsicmp(aBuf, _T("Slow"))) return FIND_SLOW; return MATCHMODE_INVALID; } static ThreadCommands ConvertThreadCommand(LPCTSTR aBuf) { if (!aBuf || !*aBuf) return THREAD_CMD_INVALID; if (!_tcsicmp(aBuf, _T("Priority"))) return THREAD_CMD_PRIORITY; if (!_tcsicmp(aBuf, _T("Interrupt"))) return THREAD_CMD_INTERRUPT; if (!_tcsicmp(aBuf, _T("NoTimers"))) return THREAD_CMD_NOTIMERS; return THREAD_CMD_INVALID; } static ToggleValueType ConvertOnOff(LPCTSTR aBuf, ToggleValueType aDefault = TOGGLE_INVALID) // Returns aDefault if aBuf isn't either ON, OFF, or blank. { if (!aBuf || !*aBuf) return NEUTRAL; if (!_tcsicmp(aBuf, _T("On")) || !_tcscmp(aBuf, _T("1"))) return TOGGLED_ON; if (!_tcsicmp(aBuf, _T("Off")) || !_tcscmp(aBuf, _T("0"))) return TOGGLED_OFF; return aDefault; } static ToggleValueType ConvertOnOffAlways(LPCTSTR aBuf, ToggleValueType aDefault = TOGGLE_INVALID) // Returns aDefault if aBuf isn't either ON, OFF, ALWAYSON, ALWAYSOFF, or blank. { if (ToggleValueType toggle = ConvertOnOff(aBuf)) return toggle; if (!_tcsicmp(aBuf, _T("AlwaysOn"))) return ALWAYS_ON; if (!_tcsicmp(aBuf, _T("AlwaysOff"))) return ALWAYS_OFF; return aDefault; } static ToggleValueType Convert10Toggle(optl<int> aValue) { if (!aValue.has_value()) return NEUTRAL; switch (*aValue) { case 1: return TOGGLED_ON; case 0: return TOGGLED_OFF; case -1: return TOGGLE; } return TOGGLE_INVALID; } static ToggleValueType ConvertOnOffToggle(LPCTSTR aBuf, ToggleValueType aDefault = TOGGLE_INVALID) // Returns aDefault if aBuf isn't either ON, OFF, TOGGLE, or blank. { if (ToggleValueType toggle = ConvertOnOff(aBuf)) return toggle; if (!_tcsicmp(aBuf, _T("Toggle")) || !_tcscmp(aBuf, _T("-1"))) return TOGGLE; return aDefault; } static StringCaseSenseType ConvertStringCaseSense(LPTSTR aBuf) { if (!_tcsicmp(aBuf, _T("On")) || !_tcscmp(aBuf, _T("1"))) return SCS_SENSITIVE; if (!_tcsicmp(aBuf, _T("Off")) || !_tcscmp(aBuf, _T("0"))) return SCS_INSENSITIVE; if (!_tcsicmp(aBuf, _T("Locale"))) return SCS_INSENSITIVE_LOCALE; return SCS_INVALID; } static ToggleValueType ConvertBlockInput(LPCTSTR aBuf) { if (ToggleValueType toggle = ConvertOnOff(aBuf)) return toggle; if (!_tcsicmp(aBuf, _T("Send"))) return TOGGLE_SEND; if (!_tcsicmp(aBuf, _T("Mouse"))) return TOGGLE_MOUSE; if (!_tcsicmp(aBuf, _T("SendAndMouse"))) return TOGGLE_SENDANDMOUSE; if (!_tcsicmp(aBuf, _T("Default"))) return TOGGLE_DEFAULT; if (!_tcsicmp(aBuf, _T("MouseMove"))) return TOGGLE_MOUSEMOVE; if (!_tcsicmp(aBuf, _T("MouseMoveOff"))) return TOGGLE_MOUSEMOVEOFF; return TOGGLE_INVALID; } static SendModes ConvertSendMode(LPCTSTR aBuf, SendModes aValueToReturnIfInvalid) { if (!_tcsicmp(aBuf, _T("Play"))) return SM_PLAY; if (!_tcsicmp(aBuf, _T("Event"))) return SM_EVENT; if (!_tcsnicmp(aBuf, _T("Input"), 5)) // This IF must be listed last so that it can fall through to bottom line. { aBuf += 5; if (!*aBuf || !_tcsicmp(aBuf, _T("ThenEvent"))) // "ThenEvent" is supported for backward compatibility with 1.0.43.00. return SM_INPUT; if (!_tcsicmp(aBuf, _T("ThenPlay"))) return SM_INPUT_FALLBACK_TO_PLAY; //else fall through and return the indication of invalidity. } return aValueToReturnIfInvalid; } static FileLoopModeType ConvertLoopMode(LPCTSTR aBuf) // Returns the file loop mode, or FILE_LOOP_INVALID if aBuf contains an invalid mode. { if (!aBuf) return FILE_LOOP_FILES_ONLY; for (FileLoopModeType mode = FILE_LOOP_INVALID;;) { switch (ctoupper(*aBuf++)) { // For simplicity, both are allowed with either kind of loop: case 'F': // Files case 'V': // Values mode |= FILE_LOOP_FILES_ONLY; break; case 'D': // Directories case 'K': // Keys mode |= FILE_LOOP_FOLDERS_ONLY; break; case 'R': mode |= FILE_LOOP_RECURSE; break; case ' ': // Allow whitespace. case '\t': // break; case '\0': if ((mode & FILE_LOOP_FILES_AND_FOLDERS) == 0) mode |= FILE_LOOP_FILES_ONLY; // Set default. return mode; default: // Invalid character. return FILE_LOOP_INVALID; } } } static int ConvertRunMode(LPCTSTR aBuf) // Returns the matching WinShow mode, or SW_SHOWNORMAL if none. // These are also the modes that AutoIt3 uses. { if (!aBuf || !*aBuf) return SW_SHOWNORMAL; if (!_tcsicmp(aBuf, _T("Min"))) return SW_MINIMIZE; if (!_tcsicmp(aBuf, _T("Max"))) return SW_MAXIMIZE; if (!_tcsicmp(aBuf, _T("Hide"))) return SW_HIDE; return SW_SHOWNORMAL; } static int ConvertMouseButton(LPCTSTR aBuf, bool aAllowWheel = true) // Returns the matching VK, or zero if none. { if (!aBuf || !*aBuf || !_tcsicmp(aBuf, _T("Left")) || !_tcsicmp(aBuf, _T("L"))) return VK_LBUTTON; // Some callers rely on this default when !*aBuf. if (!_tcsicmp(aBuf, _T("Right")) || !_tcsicmp(aBuf, _T("R"))) return VK_RBUTTON; if (!_tcsicmp(aBuf, _T("Middle")) || !_tcsicmp(aBuf, _T("M"))) return VK_MBUTTON; if (!_tcsicmp(aBuf, _T("X1"))) return VK_XBUTTON1; if (!_tcsicmp(aBuf, _T("X2"))) return VK_XBUTTON2; if (aAllowWheel) { if (!_tcsicmp(aBuf, _T("WheelUp")) || !_tcsicmp(aBuf, _T("WU"))) return VK_WHEEL_UP; if (!_tcsicmp(aBuf, _T("WheelDown")) || !_tcsicmp(aBuf, _T("WD"))) return VK_WHEEL_DOWN; // Lexikos: Support horizontal scrolling in Windows Vista and later. if (!_tcsicmp(aBuf, _T("WheelLeft")) || !_tcsicmp(aBuf, _T("WL"))) return VK_WHEEL_LEFT; if (!_tcsicmp(aBuf, _T("WheelRight")) || !_tcsicmp(aBuf, _T("WR"))) return VK_WHEEL_RIGHT; } return 0; } static CoordModeType ConvertCoordMode(LPCTSTR aBuf) { if (!_tcsicmp(aBuf, _T("Screen"))) return COORD_MODE_SCREEN; else if (!_tcsicmp(aBuf, _T("Window"))) return COORD_MODE_WINDOW; else if (!_tcsicmp(aBuf, _T("Client"))) return COORD_MODE_CLIENT; return COORD_MODE_INVALID; } static CoordModeType ConvertCoordModeCmd(LPCTSTR aBuf) { if (!_tcsicmp(aBuf, _T("Pixel"))) return COORD_MODE_PIXEL; if (!_tcsicmp(aBuf, _T("Mouse"))) return COORD_MODE_MOUSE; if (!_tcsicmp(aBuf, _T("ToolTip"))) return COORD_MODE_TOOLTIP; if (!_tcsicmp(aBuf, _T("Caret"))) return COORD_MODE_CARET; if (!_tcsicmp(aBuf, _T("Menu"))) return COORD_MODE_MENU; return COORD_MODE_INVALID; } static bool IsValidFileCodePage(UINT aCP) { return aCP == 0 || aCP == 1200 || IsValidCodePage(aCP); } static UINT ConvertFileEncoding(LPCTSTR aBuf) // Returns the encoding with possible CP_AHKNOBOM flag, or (UINT)-1 if invalid. { if (!aBuf || !*aBuf) // Active codepage, equivalent to specifying CP0. return CP_ACP; if (!_tcsicmp(aBuf, _T("UTF-8"))) return CP_UTF8; if (!_tcsicmp(aBuf, _T("UTF-8-RAW"))) return CP_UTF8 | CP_AHKNOBOM; if (!_tcsicmp(aBuf, _T("UTF-16"))) return 1200; if (!_tcsicmp(aBuf, _T("UTF-16-RAW"))) return 1200 | CP_AHKNOBOM; if (!_tcsnicmp(aBuf, _T("CP"), 2)) aBuf += 2; UINT cp; if (ParseInteger(aBuf, cp)) { // CPnnn // Catch invalid or (not installed) code pages early rather than // failing conversion later on. if (IsValidFileCodePage(cp)) return cp; } return -1; } static UINT ConvertFileEncoding(ExprTokenType &aToken); static LPTSTR LogToText(LPTSTR aBuf, int aBufSize); LPTSTR ToText(LPTSTR aBuf, int aBufSize, bool aCRLF, DWORD aElapsed = 0, bool aLineWasResumed = false, bool aLineNumber = true); ResultType PreparseError(LPTSTR aErrorText, LPTSTR aExtraInfo = _T("")); // Call this LineError to avoid confusion with Script's error-displaying functions: ResultType LineError(LPCTSTR aErrorText, ResultType aErrorType = FAIL, LPCTSTR aExtraInfo = _T("")); IObject *CreateRuntimeException(LPCTSTR aErrorText, LPCTSTR aExtraInfo, Object *aPrototype); ResultType ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); ResultType SetThrownToken(global_struct &g, ResultToken *aToken, ResultType aErrorType = FAIL); ResultType ValidateVarUsage(Var *aVar, int aUsage); ResultType VarIsReadOnlyError(Var *aVar, int aErrorType); ResultType LineUnexpectedError(); Line(FileIndexType aFileIndex, LineNumberType aFileLineNumber, ActionTypeType aActionType , ArgStruct aArg[], ArgCountType aArgc) // Constructor : mFileIndex(aFileIndex), mLineNumber(aFileLineNumber), mActionType(aActionType) , mAttribute(ATTR_NONE), mArgc(aArgc), mArg(aArg) , mPrevLine(NULL), mNextLine(NULL), mRelatedLine(NULL), mParentLine(NULL) #ifdef CONFIG_DEBUGGER , mBreakpoint(NULL) #endif {} void *operator new(size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void operator delete(void *aPtr) {} // Intentionally does nothing because we're using SimpleHeap for everything. void operator delete[](void *aPtr) {} // AutoIt3 functions: static bool Util_CopyDir(LPCTSTR szInputSource, LPCTSTR szInputDest, int OverwriteMode, bool bMove); static bool Util_RemoveDir(LPCTSTR szInputSource, bool bRecurse); static int Util_CopyFile(LPCTSTR szInputSource, LPCTSTR szInputDest, bool bOverwrite, bool bMove, DWORD &aLastError); static void Util_ExpandFilenameWildcard(LPCTSTR szSource, LPCTSTR szDest, LPTSTR szExpandedDest); static void Util_ExpandFilenameWildcardPart(LPCTSTR szSource, LPCTSTR szDest, LPTSTR szExpandedDest); static bool Util_IsDir(LPCTSTR szPath); static void Util_GetFullPathName(LPCTSTR szIn, LPTSTR szOut); static void Util_GetFullPathName(LPCTSTR szIn, LPTSTR szOut, DWORD aBufSize); }; class Label { public: LPTSTR mName; Line *mJumpToLine; Label *mPrevLabel, *mNextLabel; // Prev & Next items in linked list. #ifdef CONFIG_DLL LineNumberType mLineNumber; FileIndexType mFileIndex; #endif Label(LPTSTR aLabelName) : mName(aLabelName) // Caller gave us a pointer to dynamic memory for this. , mJumpToLine(NULL) , mPrevLabel(NULL), mNextLabel(NULL) {} void *operator new(size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void operator delete(void *aPtr) {} void operator delete[](void *aPtr) {} }; // This class encapsulates a pointer to an object which can be called by a timer, // hotkey, etc. It was originally added to support functions/objects in addition // to labels, but label support was removed. class IObjectPtr { protected: IObject *mObject; public: IObjectPtr() : mObject(NULL) {} IObjectPtr(IObject *object) : mObject(object) {} ResultType ExecuteInNewThread(TCHAR *aNewThreadDesc , ExprTokenType *aParamValue = NULL, int aParamCount = 0, bool aReturnBoolean = false) const; const IObjectPtr* operator-> () { return this; } // Act like a pointer. operator void *() const { return mObject; } // For comparisons and boolean eval. // Caller beware: does not check for NULL. Func *ToFunc() const; IObject *ToObject() const { return mObject; } // Currently only used by ListLines, listing active timers. LPCTSTR Name() const; }; // IObjectPtr with automatic reference-counting, for storing an object safely, // such as in a HotkeyVariant, UserMenuItem, etc. Its specific purpose is to // work with old code that wasn't concerned with reference counting. class IObjectRef : public IObjectPtr { private: IObjectRef & operator = (const IObjectRef &) = delete; // Disable default copy assignment. public: IObjectRef() : IObjectPtr() {} IObjectRef(IObject *object) : IObjectPtr(object) { if (object) object->AddRef(); } IObjectRef(const IObjectPtr &other) : IObjectPtr(other) { if (mObject) mObject->AddRef(); } IObjectRef & operator = (IObject *object) { if (object) object->AddRef(); if (mObject) mObject->Release(); mObject = object; return *this; } IObjectRef & operator = (const IObjectPtr &other) { return *this = other.ToObject(); } ~IObjectRef() { if (mObject) mObject->Release(); } }; enum FuncParamDefaults {PARAM_DEFAULT_NONE, PARAM_DEFAULT_STR, PARAM_DEFAULT_INT, PARAM_DEFAULT_FLOAT, PARAM_DEFAULT_UNSET, PARAM_DEFAULT_EXPR}; struct FuncParam { Var *var; WORD is_byref; // Boolean, but defined as WORD in case it helps data alignment and/or performance (BOOL vs. WORD didn't help benchmarks). WORD default_type; union {LPTSTR default_str; __int64 default_int64; double default_double; Line *default_expr;}; }; struct FuncResult : public ResultToken { TCHAR mRetValBuf[MAX_NUMBER_SIZE]; FuncResult() { InitResult(mRetValBuf); } }; // List of named script items, sorted by mName for binary search. template<typename T, int INITIAL_SIZE> struct ScriptItemList { T **mItem = nullptr; int mCount = 0, mCountMax = 0; T *Find(LPCTSTR aName, int *apInsertPos = nullptr); T *Find(LPCTSTR aName, size_t aNameLength, int *apInsertPos = nullptr); ResultType Insert(T *aItem, int aInsertPos); ResultType Alloc(int aAllocCount); }; class Func; typedef ScriptItemList<UserFunc, 4> FuncList; // Initial count is small since functions aren't expected to contain many nested functions. typedef ScriptItemList<Var, VARLIST_INITIAL_SIZE> VarList; struct FreeVars { int mRefCount, mVarCount; Var *mVar; UserFunc *mFunc; FreeVars *mOuterVars; void AddRef() { ++mRefCount; } void Release() { if (--mRefCount == 0) FullyReleased(); } bool FullyReleased(ULONG aRefPendingRelease = 0); FreeVars *ForFunc(UserFunc *aFunc) { FreeVars *fv = this; do { if (fv->mFunc == aFunc) return fv; } while (fv = fv->mOuterVars); return NULL; } static FreeVars *Alloc(UserFunc &aFunc, int aVarCount, FreeVars *aOuterVars) { Var *v = aVarCount ? ::new Var[aVarCount] : NULL; return new FreeVars(v, aFunc, aVarCount, aOuterVars); // Must use :: to avoid SimpleHeap. } private: FreeVars(Var *aVars, UserFunc &aFunc, int aVarCount, FreeVars *aOuterVars) : mVar(aVars), mVarCount(aVarCount), mRefCount(1) , mFunc(&aFunc), mOuterVars(aOuterVars) { if (aOuterVars) aOuterVars->AddRef(); } ~FreeVars() { if (mOuterVars) mOuterVars->Release(); for (int i = 0; i < mVarCount; ++i) mVar[i].Free(VAR_ALWAYS_FREE | VAR_CLEAR_ALIASES); // Clear aliases, since their targets should not be freed (they don't belong to this function). ::delete[] mVar; // Must use :: to avoid SimpleHeap. } }; struct ClosureInfo { Var *var; UserFunc *func; }; ResultType VariadicCall(IObject *aObj, IObject_Invoke_PARAMS_DECL); struct UDFCallInfo { UserFunc *func; VarBkp *backup = nullptr; // Backup of previous instance's local vars. NULL if no previous instance or no vars. int backup_count = 0; // Number of previous instance's local vars. 0 if no previous instance or no vars. UDFCallInfo(UserFunc *f) : func(f) {} }; class DECLSPEC_NOVTABLE Func : public Object { public: LPCTSTR mName; int mParamCount = 0; // The function's maximum number of parameters. For UDFs, also the number of items in the mParam array. int mMinParams = 0; // The number of mandatory parameters (populated for both UDFs and built-in's). bool mIsVariadic = false; // Whether to allow mParamCount to be exceeded. #ifdef CONFIG_DLL LineNumberType mLineNumber = 0; FileIndexType mFileIndex = 0; #endif virtual bool IsBuiltIn() = 0; // FIXME: Should not need to rely on this. virtual bool ArgIsOutputVar(int aArg) = 0; virtual bool ArgIsOptional(int aArg) { return aArg >= mMinParams; } // bool result indicates whether aResultToken contains a value (i.e. false for FAIL/EARLY_EXIT). virtual bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount); enum MemberID { M_Call, M_Bind, M_IsOptional, M_IsByRef, P_Name, P_MinParams, P_MaxParams, P_IsBuiltIn, P_IsVariadic }; static ObjectMember sMembers[]; void Invoke(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount); static Object *sPrototype; ResultType Invoke(IObject_Invoke_PARAMS_DECL); Func(LPCTSTR aFuncName) : mName(aFuncName) // Caller gave us a pointer to dynamic memory for this. { SetBase(sPrototype); } }; class ScriptModule; class UserFunc : public Func { public: int mInstances = 0; // How many instances currently exist on the call stack (due to recursion or thread interruption). Future use: Might be used to limit how deep recursion can go to help prevent stack overflow. Line *mJumpToLine = nullptr; FuncParam *mParam = nullptr; // Holds an array of FuncParams (array length: mParamCount). Object *mClass = nullptr; // The class or prototype object which this user-defined method was defined for, or nullptr. Label *mFirstLabel = nullptr, *mLastLabel = nullptr; // Linked list of private labels. UserFunc *mOuterFunc = nullptr; // Func which contains this func (usually nullptr). ScriptModule *mModule = nullptr; // Module in which this function was defined. VarList mVars {}; // Sorted list of non-static local variables. VarList mStaticVars {}; // Sorted list of static variables. Var **mDownVar = nullptr, **mUpVar = nullptr; int *mUpVarIndex = nullptr; ClosureInfo *mClosure = nullptr; // Array of nested functions containing upvars. static FreeVars *sFreeVars; #define MAX_FUNC_UP_VARS 1000 int mDownVarCount = 0, mUpVarCount = 0; int mClosureCount = 0; // Keep small members adjacent to each other to save space and improve perf. due to byte alignment: FuncDefType mIsFuncExpression; // Whether this function was defined *within* an expression and is therefore allowed under a control flow statement. bool mIsStatic = false; // Whether the "static" keyword was used with a function (not method); this prevents a nested function from becoming a closure. #define VAR_DECLARE_GLOBAL (VAR_DECLARED | VAR_GLOBAL) #define VAR_DECLARE_LOCAL (VAR_DECLARED | VAR_LOCAL) #define VAR_DECLARE_STATIC (VAR_DECLARED | VAR_LOCAL | VAR_LOCAL_STATIC) UCHAR mDefaultVarType = VAR_DECLARE_LOCAL; UserFunc(LPCTSTR aName) : Func(aName) {} bool IsBuiltIn() override { return false; } bool ArgIsOutputVar(int aArg) override { return aArg < mParamCount && mParam[aArg].is_byref; } // Find a local (not global or nonlocal/outer) variable. Var *FindLocalVar(LPCTSTR aName, size_t aNameLength) { if (Var *var = mVars.Find(aName, aNameLength)) return var; if (Var *var = mStaticVars.Find(aName, aNameLength)) return var; return nullptr; } bool IsAssumeGlobal() { return mDefaultVarType & VAR_GLOBAL; } bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount) override; bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount, FreeVars *aUpVars); // Execute the body of the function. ResultType Execute(ResultToken *aResultToken) { // The performance gain of conditionally passing NULL in place of result (when this is the // outermost function call of a line consisting only of function calls, namely ACT_EXPRESSION) // would not be significant because the Return command's expression (arg1) must still be evaluated // in case it calls any functions that have side-effects, e.g. "return LogThisError()". // Although a GOTO that jumps to a position outside of the function's body could be supported, // it seems best not to for these reasons: // 1) The extreme rarity of a legitimate desire to intentionally do so. // 2) The fact that any return encountered after the Goto cannot provide a return value for // the function because load-time validation checks for this (it's preferable not to // give up this check, since it is an informative error message and might also help catch // bugs in the script). // 3) More difficult to maintain because we have handle jump_to_line the same way ExecUntil() does, // checking aResult the same way it does, then checking jump_to_line the same way it does, etc. // Fix for v1.0.31.05: g->mLoopFile and the other g_script members that follow it are // now passed to ExecUntil() for two reasons (update for v1.0.44.14: now they're implicitly "passed" // because they're done via parameter anymore): // 1) To fix the fact that any function call in one parameter of a command would reset // A_Index and related variables so that if those variables are referenced in another // parameter of the same command, they would be wrong. // 2) So that the caller's value of A_Index and such will always be valid even inside // of called functions (unless overridden/eclipsed by a loop in the body of the function), // which seems to add flexibility without giving up anything. This fix is necessary at least // for a command that references A_Index in two of its args such as the following: // ToolTip, O, ((cos(A_Index) * 500) + 500), A_Index ResultType result; result = mJumpToLine->ExecUntil(UNTIL_BLOCK_END, aResultToken); if (result == EARLY_RETURN) { #ifdef CONFIG_DEBUGGER // Don't do this for fat-arrow functions because they're only (part of) a single line, // and they are removed from the linked list of Lines (which would be relied upon below). // Inline function definitions are treated the same if they start with a RETURN statement. if (g_Debugger.IsConnected() && (!mIsFuncExpression || mJumpToLine->mActionType != ACT_RETURN)) { // Find the end of this function. //Line *line; //for (line = mJumpToLine; line && (line->mActionType != ACT_BLOCK_END || !line->mAttribute); line = line->mNextLine); // Since mJumpToLine points at the first line *inside* the body, mJumpToLine->mParentLine // is the block-begin. That line's mRelatedLine is the line *after* the block-end, so // use it's mPrevLine. mRelatedLine is guaranteed to be non-NULL by load-time logic. Line *line = mJumpToLine->mParentLine->mRelatedLine->mPrevLine; // Give user the opportunity to inspect variables before returning. if (line) g_Debugger.PreExecLine(line); } #endif result = OK; // Function results should be OK, FAIL or EARLY_EXIT. } return result; } void *operator new(size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void operator delete(void *aPtr) {} void operator delete[](void *aPtr) {} }; class Closure : public Func { UserFunc *mFunc; FreeVars *mVars; public: static Object *sPrototype; enum Flags : decltype(mFlags) { ClosureGroupedFlag = LastObjectFlag << 1 }; Closure(UserFunc *aFunc, FreeVars *aVars, bool aIsGrouped) : mFunc(aFunc), mVars(aVars), Func(aFunc->mName) { if (aIsGrouped) { mFlags |= ClosureGroupedFlag; mRefCount = 0; } else aVars->AddRef(); mMinParams = aFunc->mMinParams; mParamCount = aFunc->mParamCount; mIsVariadic = aFunc->mIsVariadic; SetBase(sPrototype); } ~Closure(); bool Delete() override; bool IsBuiltIn() override { return false; } bool ArgIsOutputVar(int aArg) override { return mFunc->ArgIsOutputVar(aArg); } bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount) override; }; class BoundFunc : public Func { IObject *mFunc; LPTSTR mMember; Array *mParams; int mFlags; BoundFunc(IObject *aFunc, LPTSTR aMember, Array *aParams, int aFlags) : mFunc(aFunc), mMember(aMember), mParams(aParams), mFlags(aFlags) , Func(_T("")) { mIsVariadic = true; SetBase(sPrototype); } public: static Object *sPrototype; static BoundFunc *Bind(IObject *aFunc, int aFlags, LPCTSTR aMember, ExprTokenType **aParam, int aParamCount); ~BoundFunc(); bool IsBuiltIn() override { return false; } bool ArgIsOutputVar(int aArg) override { return false; } bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount) override; }; class DECLSPEC_NOVTABLE NativeFunc : public Func { protected: NativeFunc(LPCTSTR aName) : Func(aName) {} public: bool IsBuiltIn() override { return true; } bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount) override; void *operator new(size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void *operator new[](size_t aBytes) {return SimpleHeap::Alloc(aBytes);} void operator delete(void *aPtr) {} void operator delete[](void *aPtr) {} }; struct FuncEntry; class BuiltInFunc : public NativeFunc { public: BuiltInFunctionType mBIF; union { BuiltInFunctionID mFID; // For code sharing: this function's ID in the group of functions which share the same C++ function. void *mData; }; UCHAR *mOutputVars = nullptr; // String of indices indicating which params are output vars. BuiltInFunc(LPCTSTR aName) : NativeFunc(aName) {} BuiltInFunc(FuncEntry &); BuiltInFunc(LPCTSTR aName, BuiltInFunctionType aBIF, int aMinParams, int aMaxParams, bool aIsVariadic = false, void *aData = nullptr) : BuiltInFunc(aName) { mBIF = aBIF; mMinParams = aMinParams; mParamCount = aMaxParams; mIsVariadic = aIsVariadic; //mFID = (BuiltInFunctionID)0; mData = aData; } #define MAX_FUNC_OUTPUT_VAR 7 bool ArgIsOutputVar(int aIndex) override { if (!mOutputVars) return false; ++aIndex; // Convert to one-based. for (int i = 0; i < MAX_FUNC_OUTPUT_VAR && mOutputVars[i]; ++i) if (mOutputVars[i] == aIndex) return true; return false; } bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount) override; }; class BuiltInMethod : public NativeFunc { public: ObjectMethod mBIM; Object *mClass; // The class or prototype object which this method was defined for, and which `this` must derive from. UCHAR mMID; UCHAR mMIT; BuiltInMethod(LPTSTR aName) : NativeFunc(aName) {} bool ArgIsOutputVar(int aArg) override { return false; } bool ArgIsOptional(int aArg) override { return aArg >= mMinParams || aArg == 1 && (mMIT & BIMF_UNSET_ARG_1); } bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount) override; }; class ExprOpFunc : public BuiltInFunc { // ExprOpFunc: Used in combination with SYM_FUNC to implement certain operations in expressions. // These are not inserted into the script's function list, so mName is used only by the debugger. public: ExprOpFunc(BuiltInFunctionType aBIF, int aID) : BuiltInFunc(_T("<object>")) // ExpressionToPostfix relies on the name beginning with '<'. { mBIF = aBIF; mFID = (BuiltInFunctionID)aID; // Allow any number of parameters, since these functions aren't called directly by users // and might break the rules in some cases. mParamCount = 255; mIsVariadic = true; } }; template<BuiltInFunctionType bif, int flags> struct ExprOpT { static ExprOpFunc Func; }; template<BuiltInFunctionType bif, int flags> ExprOpFunc ExprOpT<bif, flags>::Func(bif, flags); // ExprOp<bif, flags>() returns a Func* which calls bif with the given ID/flags. // The call is optimized out and replaced with a reference to a static variable, // which should be unique for that combination of bif and flags. template<BuiltInFunctionType bif, int flags> inline BuiltInFunc *ExprOp() { // Using static ExprOpFunc directly increased code size considerably. return &ExprOpT<bif, flags>::Func; } struct FuncEntry { LPCTSTR mName; BuiltInFunctionType mBIF; UCHAR mMinParams, mMaxParams; UCHAR mID; UCHAR mOutputVars[MAX_FUNC_OUTPUT_VAR]; }; class DECLSPEC_NOVTABLE EnumBase : public Func { public: static Object *sPrototype; EnumBase() : Func(_T("")) { mParamCount = 2; SetBase(sPrototype); } bool IsBuiltIn() override { return true; }; bool ArgIsOutputVar(int aArg) override { return true; } bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount) override; virtual ResultType Next(Var *, Var *) = 0; }; class IndexEnumerator : public EnumBase { public: typedef ResultType (Object::* Callback)(UINT &aIndex, Var *aOutputVar1, Var *aOutputVar2, int aVarCount); private: Object *mObject; UINT mIndex = UINT_MAX; Callback mGetItem; public: IndexEnumerator(Object *aObject, int aVarCount, Callback aGetItem) : mObject(aObject), mGetItem(aGetItem) { mObject->AddRef(); mParamCount = aVarCount; SetBase(EnumBase::sPrototype); } ~IndexEnumerator() { mObject->Release(); } ResultType Next(Var *, Var *) override; }; class Object::PropEnum : public EnumBase { Object *mObject; index_t *mIndex; int mIndexCount = 0; ExprTokenType mThisToken; public: PropEnum(Object *aObject); PropEnum(Object *aObject, ExprTokenType &aThisToken); ~PropEnum(); ResultType Next(Var *aName, Var *aVal) override; }; class ScriptTimer { public: IObjectRef mCallback; DWORD mPeriod; // v1.0.36.33: Changed from int to DWORD to double its capacity. DWORD mTimeLastRun; // TickCount int mPriority; // Thread priority relative to other threads, default 0. UCHAR mExistingThreads; // Whether this timer is already running its subroutine. UCHAR mDeleteLocked; // Lock count to prevent full deletion. Separate to mExistingThreads so it doesn't prevent timer execution. bool mEnabled; bool mRunOnlyOnce; ScriptTimer *mNextTimer; // Next items in linked list void ScriptTimer::Disable(); ScriptTimer(IObject *aLabel) #define DEFAULT_TIMER_PERIOD 250 : mCallback(aLabel), mPeriod(DEFAULT_TIMER_PERIOD), mPriority(0) // Default is always 0. , mExistingThreads(0), mTimeLastRun(0) , mEnabled(false), mRunOnlyOnce(false), mNextTimer(NULL) // Note that mEnabled must default to false for the counts to be right. , mDeleteLocked(0) {} }; struct MsgMonitorStruct { union { IObject *func; LPTSTR method_name; // Used only by GUI. LPVOID union_value; // Internal use. }; UINT msg; // Keep any members smaller than 4 bytes adjacent to save memory: static const UCHAR MAX_INSTANCES = MAX_THREADS_LIMIT; // For maintainability. Causes a compiler warning if MAX_THREADS_LIMIT > MAX_UCHAR. UCHAR instance_count; // Distinct from func.mInstances because the script might have called the function explicitly. UCHAR max_instances; // v1.0.47: Support more than one thread. UCHAR msg_type; // Used only by GUI, so may be ignored by some methods. bool is_method; // Used only by GUI. }; struct MsgMonitorInstance; class MsgMonitorList { MsgMonitorStruct *mMonitor; MsgMonitorInstance *mTop; int mCount, mCountMax; friend struct MsgMonitorInstance; MsgMonitorStruct *AddInternal(UINT aMsg, bool aAppend); public: MsgMonitorStruct *Find(UINT aMsg, IObject *aCallback, UCHAR aMsgType = 0); MsgMonitorStruct *Find(UINT aMsg, LPTSTR aMethodName, UCHAR aMsgType = 0); MsgMonitorStruct *Add(UINT aMsg, IObject *aCallback, bool aAppend = TRUE); MsgMonitorStruct *Add(UINT aMsg, LPTSTR aMethodName, bool aAppend = TRUE); void Delete(MsgMonitorStruct *aMonitor); ResultType Call(ExprTokenType *aParamValue, int aParamCount, int aInitNewThreadIndex, __int64 *aRetVal = nullptr); // Used for OnExit and OnClipboardChange, but not OnMessage. ResultType Call(ExprTokenType *aParamValue, int aParamCount, UINT aMsg, UCHAR aMsgType, GuiType *aGui, INT_PTR *aRetVal = NULL); // Used by GUI. MsgMonitorStruct& operator[] (const int aIndex) { return mMonitor[aIndex]; } int Count() { return mCount; } BOOL IsMonitoring(UINT aMsg, UCHAR aMsgType = 0); BOOL IsMonitoringGuiMsg(); BOOL IsRunning(UINT aMsg, UCHAR aMsgType = 0); MsgMonitorList() : mCount(0), mCountMax(0), mMonitor(NULL), mTop(NULL) {} void Dispose(); }; struct MsgMonitorInstance { MsgMonitorList &list; MsgMonitorInstance *previous; int index; int count; bool deleted; MsgMonitorInstance(MsgMonitorList &aList) : list(aList), previous(aList.mTop), index(0), count(aList.mCount) , deleted(false) { aList.mTop = this; } ~MsgMonitorInstance() { list.mTop = previous; } void Delete(int mon_index) { if (index >= mon_index && index >= 0) { if (index == mon_index) deleted = true; // Callers who care about this will reset it after each iteration. index--; // So index+1 is the next item. } count--; } void Dispose() { count = 0; // Prevent further iteration. deleted = true; // Mark the current item as deleted, so it won't be accessed. } }; #define MAX_MENU_NAME_LENGTH MAX_PATH // The observed limit for Win32 menu item text. class UserMenuItem; // Forward declaration since classes use each other (i.e. a menu *item* can have a submenu). class UserMenu : public Object { public: class Bar; UserMenuItem *mFirstMenuItem = nullptr, *mLastMenuItem = nullptr, *mDefault = nullptr; UserMenu *mNextMenu = nullptr; // Next item in linked list // Keep any fields that aren't an even multiple of 4 adjacent to each other. This conserves memory // due to byte-alignment: int mClickCount = 2; // How many clicks it takes to trigger the default menu item. 2 = double-click UINT mMenuItemCount = 0; // The count of user-defined menu items (doesn't include the standard items, if present). MenuTypeType mMenuType; // MENU_TYPE_POPUP (via CreatePopupMenu) vs. MENU_TYPE_BAR (via CreateMenu). HMENU mMenu = NULL; HBRUSH mBrush = NULL; // Background color to apply to menu. COLORREF mColor = CLR_DEFAULT; // The color that corresponds to the above. static ObjectMemberMd sMembers[]; static int sMemberCount; static Object *sPrototype, *sBarPrototype; // Don't overload new and delete operators in this case since we want to use real dynamic memory // (since menus can be read in from a file, destroyed and recreated, over and over). UserMenu(MenuTypeType aMenuType); static UserMenu *Create() { return new UserMenu(MENU_TYPE_POPUP); } void Dispose(); ~UserMenu(); FResult Add(optl<StrArg> aName, optl<IObject*> aFuncOrSubmenu, optl<StrArg> aOptions); FResult Add(optl<StrArg> aName, optl<IObject*> aFuncOrSubmenu, optl<StrArg> aOptions, UserMenuItem **insert_at); FResult AddStandard(); FResult Check(StrArg aItemName); FResult Delete(optl<StrArg> aItemName); FResult Disable(StrArg aItemName); FResult Enable(StrArg aItemName); FResult Insert(optl<StrArg> aBefore, optl<StrArg> aName, optl<IObject*> aFuncOrSubmenu, optl<StrArg> aOptions); FResult Rename(StrArg aItemName, optl<StrArg> aNewName); FResult SetColor(ExprTokenType *aColor, optl<BOOL> aApplyToSubmenus); FResult SetIcon(StrArg aItemName, StrArg aIconFile, optl<int> aIconNumber, optl<int> aIconWidth); FResult Show(optl<int> aX, optl<int> aY, optl<BOOL> aWait); FResult ToggleCheck(StrArg aItemName, BOOL &aRetVal); FResult ToggleEnable(StrArg aItemName, BOOL &aRetVal); FResult Uncheck(StrArg aItemName); FResult get_ClickCount(int &aRetVal); FResult set_ClickCount(int aValue); FResult get_Default(StrRet &aRetVal); FResult set_Default(StrArg aItemName); FResult get_Handle(UINT_PTR &aRetVal); ResultType AddItem(LPCTSTR aName, UINT aMenuID, IObject *aCallback, UserMenu *aSubmenu, LPCTSTR aOptions, UserMenuItem **aInsertAt = nullptr); ResultType InternalAppendMenu(UserMenuItem *aMenuItem, UserMenuItem *aInsertBefore = NULL); void DeleteItem(UserMenuItem *aMenuItem, UserMenuItem *aMenuItemPrev, bool aUpdateGuiMenuBars = true); void DeleteAllItems(); ResultType ModifyItem(UserMenuItem *aMenuItem, IObject *aCallback, UserMenu *aSubmenu, LPCTSTR aOptions); ResultType UpdateOptions(UserMenuItem *aMenuItem, LPCTSTR aOptions); ResultType RenameItem(UserMenuItem *aMenuItem, LPCTSTR aNewName); ResultType UpdateName(UserMenuItem *aMenuItem, LPCTSTR aNewName); void SetItemState(UserMenuItem *aMenuItem, UINT aState, UINT aStateMask); FResult SetItemState(StrArg aItemName, UINT aState, UINT aStateMask, UINT *aNewState = nullptr); void SetDefault(UserMenuItem *aMenuItem = NULL, bool aUpdateGuiMenuBars = true); ResultType CreateHandle(); void DestroyHandle(); void SetColor(COLORREF aColor, bool aApplyToSubmenus); void ApplyColor(bool aApplyToSubmenus); ResultType AppendStandardItems(); ResultType EnableStandardOpenItem(bool aEnable); ResultType Display(int aX = COORD_UNSPECIFIED, int aY = COORD_UNSPECIFIED, optl<BOOL> aWait = false); FResult GetItem(LPCTSTR aNameOrPos, UserMenuItem *&aItem); FResult ItemNotFoundError(LPCTSTR aItem); UserMenuItem *FindItem(LPCTSTR aNameOrPos, UserMenuItem *&aPrevItem, bool &aByPos); UserMenuItem *FindItemByID(UINT aID); bool ContainsMenu(UserMenu *aMenu); void UpdateAccelerators(); // L17: Functions for menu icons. ResultType SetItemIcon(UserMenuItem *aMenuItem, LPCTSTR aFilename, int aIconNumber, int aWidth); void ApplyItemIcon(UserMenuItem *aMenuItem); void RemoveItemIcon(UserMenuItem *aMenuItem); }; class UserMenu::Bar : public UserMenu { Bar(const Bar &) = delete; // Never instantiated. public: static UserMenu *Create() { return new UserMenu(MENU_TYPE_BAR); } }; class UserMenuItem { public: LPTSTR mName; // Dynamically allocated. size_t mNameCapacity; IObjectRef mCallback; UserMenu *mSubmenu; UserMenu *mMenu; // The menu to which this item belongs. Needed to support script var A_ThisMenu. UINT mMenuID; int mPriority; // Keep any fields that aren't an even multiple of 4 adjacent to each other. This conserves memory // due to byte-alignment: WORD mMenuState; WORD mMenuType; UserMenuItem *mNextMenuItem; // Next item in linked list // For menu item icons: // Windows Vista and later support alpha channels via 32-bit bitmaps. Since owner-drawing prevents // visual styles being applied to menus, we convert each icon to a 32-bit bitmap, calculating the // alpha channel as necessary. This is done only once, when the icon is initially set. HBITMAP mBitmap; UserMenuItem(LPTSTR aName, size_t aNameCapacity, UINT aMenuID, IObject *aCallback, UserMenu *aSubmenu, UserMenu *aMenu); ~UserMenuItem(); // Don't overload new and delete operators in this case since we want to use real dynamic memory // (since menus can be read in from a file, destroyed and recreated, over and over). UINT Pos(); }; struct DerefList { DerefType *items; int size, count; DerefList() : items(NULL), size(0), count(0) {} ~DerefList() { free(items); } ResultType Push(); DerefType *Last() { return items + count - 1; } }; struct UnresolvedBaseClass { Object *subclass, *subclass_proto; LPTSTR name; FileIndexType file_index; LineNumberType line_number; UnresolvedBaseClass *next; }; #include "script_module.h" class Script { private: friend class Hotkey; #ifdef CONFIG_DEBUGGER friend class Debugger; #endif #ifdef CONFIG_DLL friend class AutoHotkeyLib; friend class FuncCollection; friend class VarCollection; friend class LabelCollection; friend class EnumFuncs; friend class EnumVars; friend class EnumLabels; friend bool LibNotifyProblem(LPCTSTR, LPCTSTR, Line *, bool); #endif struct PartialExpression { PartialExpression *outer; UserFunc *func = nullptr; LPTSTR code; size_t length; Line *rejoin_first_line = nullptr, *rejoin_last_line = nullptr; LPCTSTR pending_hotkey = nullptr; int funcs_index; LineNumberType line_no; ActionTypeType action; bool add_block_end_after = false; PartialExpression(LPTSTR aCode, size_t aLen, ActionTypeType aAct, Script &aScript) : code(aCode), length(aLen), action(aAct) , outer(aScript.mExprContainingThisFunc) , funcs_index(aScript.mFuncs.mCount + 1) // +1 to exclude func itself. , line_no(aScript.mCombinedLineNumber) {} ~PartialExpression() { free(code); } }; #define FDE_SUBSTITUTE_STRING L"(\u2026){}" #define FDE_SUBSTITUTE_STRING_LENGTH (_countof(FDE_SUBSTITUTE_STRING)-1) Line *mFirstLine, *mLastLine; // The first and last lines in the linked list. Label *mLastLabel; // The last defined label. #ifdef CONFIG_DLL int mLabelCount; #endif FuncList mFuncs; ScriptModuleList mModules; ScriptModule mBuiltinModule { _T("AHK") }; ScriptModule mDefaultModule { _T("__Main") }; ScriptModule *mCurrentModule = &mBuiltinModule; ScriptModule *mLastModule = nullptr; WinGroup *mFirstGroup, *mLastGroup; // The first and last variables in the linked list. Line *mLineParent = nullptr; // While loading the script, the parent line or block-begin for the next line to be added. Line *mPendingRelatedLine; Line *mLastParamInitializer; LPCTSTR mPendingHotkey = nullptr; // The name of a hotkey or hotstring awaiting its block/function. PartialExpression *mExprContainingThisFunc = nullptr; int mExprFuncIndex = INT_MAX; SymbolType mDefaultReturn = SYM_STRING; bool mNextLineIsFunctionBody; // Whether the very next line to be added will be the first one of the body. bool mIgnoreNextBlockBegin; #define MAX_NESTED_CLASSES 5 #define MAX_CLASS_NAME_LENGTH UCHAR_MAX int mClassObjectCount; Object *mClassObject[MAX_NESTED_CLASSES]; // Class definition currently being parsed. TCHAR mClassName[MAX_CLASS_NAME_LENGTH + 1]; // Only used during load-time. Property *mClassProperty; LPTSTR mClassPropertyDef; // These two track the file number and line number in that file of the line currently being loaded, // which simplifies calls to ScriptError() and LineError() (reduces the number of params that must be passed). // These are used ONLY while loading the script into memory. After that (while the script is running), // only mCurrLine is kept up-to-date: int mCurrFileIndex; LineNumberType mCombinedLineNumber; // In the case of a continuation section/line(s), this is always the top line. bool mClassPropertyStatic; #define UPDATE_TIP_FIELD tcslcpy(mNIC.szTip, mTrayIconTip ? mTrayIconTip \ : mFileName, _countof(mNIC.szTip)); NOTIFYICONDATA mNIC; // For ease of adding and deleting our tray icon. struct LineBuffer { TCHAR *p = nullptr; size_t length = 0; size_t size = 0; const size_t INITIAL_SIZE = 0x1000; // # characters for first allocation. Subsequent Reallocs will grow exponentially. const size_t RESERVED_SPACE = 3; // Allow for a null-terminator and appending "()" for call statements. size_t Capacity() { ASSERT(size); return size - RESERVED_SPACE; } ResultType Expand(); ResultType EnsureCapacity(size_t aLength); ResultType Realloc(size_t aNewSize); ~LineBuffer() { free(p); } operator LPTSTR() const { return p; } }; size_t GetLine(LineBuffer &aBuf, int aInContinuationSection, bool aInBlockComment, TextStream *ts); ResultType GetLineContinuation(TextStream *ts, LineBuffer &aBuf, LineBuffer &aNextBuf , LineNumberType &aPhysLineNumber, bool &aHasContinuationSection); ResultType GetLineContExpr(TextStream *ts, LineBuffer &aBuf, LineBuffer &aNextBuf , LineNumberType &aPhysLineNumber, bool &aHasContinuationSection); bool IsSOLContExpr(LineBuffer &aBuf); ResultType BalanceExprError(int aBalance, TCHAR aExpect[], LPTSTR aLineText); static bool IsFunctionDefinition(LPTSTR aBuf, LPTSTR aNextBuf); ResultType IsDirective(LPTSTR aBuf); ResultType ConvertDirectiveBool(LPTSTR aBuf, bool &aResult, bool aDefault); ResultType RequirementError(LPCTSTR aRequirement); ResultType ParseAndAddLine(LPTSTR aLineText, ActionTypeType aActionType = ACT_INVALID); ResultType ParseOperands(LPTSTR aArgText, DerefList &aDeref, int *aPos = NULL, TCHAR aEndChar = 0); ResultType ParseDoubleDeref(LPTSTR aArgText, DerefList &aDeref, int *aPos); ResultType ParseFatArrow(LPTSTR aArgText, DerefList &aDeref , LPTSTR aPrmStart, LPTSTR aPrmEnd, LPTSTR aExpr, LPTSTR &aExprEnd); ResultType ParseFatArrow(DerefList &aDeref, LPTSTR aPrmStart, LPTSTR aPrmEnd, LPTSTR aExpr, LPTSTR aExprEnd); ResultType ParseAndAddLineInBlock(LPTSTR aLineText, ActionTypeType aActionType = ACT_INVALID); LPTSTR ParseActionType(LPTSTR aBufTarget, LPTSTR aBufSource); ResultType AddLabel(LPTSTR aLabelName, bool aAllowDupe); ResultType AddLine(ActionTypeType aActionType, LPTSTR aArg[] = NULL, int aArgc = 0, bool aAllArgsAreExpressions = false); ResultType PreparseExpressions(); ResultType PreparseExpressions(Line *aStartingLine); ResultType PreparseExpressions(FuncList &aFuncs); void PreparseHotkeyIfExpr(Line *aLine); ResultType PreparseCommands(); ResultType PreparseCommands(Line *aStartingLine); ResultType PreparseCatchVar(Line *aLine); ResultType PreparseCatchClass(Line *aLine); bool IsLabelTarget(Line *aLine); Label *CurrentFirstLabel() { return g->CurrentFunc ? g->CurrentFunc->mFirstLabel : mCurrentModule->mFirstLabel; } public: Line *mCurrLine; // Seems better to make this public than make Line our friend. Object *mNewRuntimeException = nullptr; // Lets Error__New detect that it's being called by CreateRuntimeException. LPTSTR mThisHotkeyName, mPriorHotkeyName; MsgMonitorList mOnExit, mOnClipboardChange, mOnError; // Event handlers for OnExit(), OnClipboardChange() and OnError(). bool mOnClipboardChangeIsRunning; int mPendingExitCode = 0; ScriptTimer *mFirstTimer, *mLastTimer; // The first and last script timers in the linked list. UINT mTimerCount, mTimerEnabledCount; UserMenu *mFirstMenu, *mLastMenu; UINT mMenuCount; DWORD mThisHotkeyStartTime, mPriorHotkeyStartTime; // Tickcount timestamp of when its subroutine began. TCHAR mEndChar; // The ending character pressed to trigger the most recent non-auto-replace hotstring. modLR_type mThisHotkeyModifiersLR; LPTSTR mFileSpec; // Will hold the full filespec, for convenience. LPTSTR mFileDir; // Will hold the directory containing the script file. LPTSTR mFileName; // Will hold the script's naked file name. LPTSTR mScriptName; // Value of A_ScriptName; defaults to mFileName if NULL. See also DefaultDialogTitle(). LPTSTR mOurEXE; // Will hold this app's module name (e.g. C:\Program Files\AutoHotkey\AutoHotkey.exe). LPTSTR mOurEXEDir; // Same as above but just the containing directory (for convenience). LPTSTR mMainWindowTitle; // Will hold our main window's title, for consistency & convenience. enum Kind { ScriptKindFile, ScriptKindResource, ScriptKindStdIn } mKind; bool mIsReadyToExecute; bool mAutoExecSectionIsRunning; bool mIsRestart; // The app is restarting rather than starting from scratch. bool mErrorStdOut; // true if load-time syntax errors should be sent to stdout vs. a MsgBox. UINT mErrorStdOutCP; void SetErrorStdOut(LPTSTR aParam); void PrintErrorStdOut(LPCTSTR aErrorText, int aLength = 0, LPCTSTR aFile = _T("*")); void PrintErrorStdOut(LPCTSTR aErrorText, LPCTSTR aExtraInfo, FileIndexType aFileIndex, LineNumberType aLineNumber); #ifndef AUTOHOTKEYSC bool mValidateThenExit; LPTSTR mCmdLineInclude; #endif int mUninterruptedLineCountMax; // 32-bit for performance (since huge values seem unnecessary here). int mUninterruptibleTime; DWORD mLastPeekTime; CStringW mRunAsUser, mRunAsPass, mRunAsDomain; HICON mCustomIcon; // NULL unless the script has loaded a custom icon during its runtime. HICON mCustomIconSmall; // L17: Use separate big/small icons for best results. LPTSTR mCustomIconFile; // Filename of icon. Allocated on first use. bool mIconFrozen; // If true, the icon does not change state when the state of pause or suspend changes. LPTSTR mTrayIconTip; // Custom tip text for tray icon. Allocated on first use. UINT mCustomIconNumber; // The number of the icon inside the above file. UserMenu *mTrayMenu; // Our tray menu, which should be destroyed upon exiting the program. ResultType Init(LPTSTR aScriptFilename, IObject *aArgs); ResultType CreateWindows(); void EnableClipboardListener(bool aEnable); void AllowMainWindow(bool aAllow); void EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags); void CreateTrayIcon(); void UpdateTrayIcon(bool aForceUpdate = false); void ShowTrayIcon(bool aShow); ResultType SetTrayIcon(LPCTSTR aIconFile, int aIconNumber, ToggleValueType aFreezeIcon); void SetTrayTip(LPTSTR aText); ResultType AutoExecSection(); ResultType ExecuteModule(ScriptModule *aModule); bool IsPersistent(); void ExitIfNotPersistent(ExitReasons aExitReason); ResultType Edit(LPCTSTR aFileName = nullptr); ResultType Reload(bool aDisplayErrors); ResultType ExitApp(ExitReasons aExitReason); void TerminateApp(ExitReasons aExitReason, int aExitCode); // L31: Added aExitReason. See script.cpp. LineNumberType LoadFromFile(LPCTSTR aFileSpec); ResultType LoadIncludedFile(LPCTSTR aFileSpec, bool aAllowDuplicateInclude, bool aIgnoreLoadFailure); ResultType LoadIncludedFile(TextStream *fp); ResultType ParseRemap(LPCTSTR aSource, vk_type remap_dest_vk, LPCTSTR aDestName, LPCTSTR aDestMods); ResultType OpenIncludedFile(TextStream *&ts, LPCTSTR aFileSpec, bool aAllowDuplicateInclude, bool aIgnoreLoadFailure); LineNumberType CurrentLine(); LPTSTR CurrentFile(); static ActionTypeType ConvertActionType(LPCTSTR aActionTypeString); enum SetTimerFlags { SET_TIMER_PERIOD = 1, SET_TIMER_STATE = 2, SET_TIMER_PRIORITY = 4, SET_TIMER_RESET = 8 }; ResultType UpdateOrCreateTimer(IObject *aCallback , bool aUpdatePeriod, __int64 aPeriod, bool aUpdatePriority, int aPriority); void DeleteTimer(IObject *aCallback); LPTSTR DefaultDialogTitle(); UserFunc* CreateHotFunc(); ResultType DefineFunc(LPTSTR aBuf, bool aStatic = false, FuncDefType aIsInExpression = FuncDefNormal); #ifndef AUTOHOTKEYSC struct FuncLibrary { LPTSTR path; size_t length; }; void InitFuncLibraries(FuncLibrary aLibs[]); void InitFuncLibrary(FuncLibrary &aLib, LPTSTR aPathBase, LPTSTR aPathSuffix); LPTSTR FindLibraryFile(LPTSTR aName, size_t aNameLength, bool aIsModule = false); #endif IObject *GetBuiltinObject(LPCTSTR aName); static Func *GetBuiltInFunc(LPCTSTR aFuncName); static Func *GetBuiltInMdFunc(LPCTSTR aFuncName); UserFunc *AddFunc(LPCTSTR aFuncName, size_t aFuncNameLength, FuncDefType aIsInExpression = FuncDefNormal, Object *aClassObject = nullptr); Var *AddFuncVar(UserFunc *aFunc); UserFunc *AddFuncToList(UserFunc *aFunc); ResultType DefineClass(LPTSTR aBuf, TCHAR aExport); UserFunc *DefineClassInit(bool aStatic); ResultType DefineClassVars(LPTSTR aBuf, bool aStatic); ResultType DefineClassVarInit(LPTSTR aBuf, bool aStatic, Object *aObject, ActionTypeType aActionType = ACT_INVALID); ResultType DefineClassProperty(LPTSTR aBuf, bool aStatic, bool &aBufHasBraceOrNotNeeded); ResultType DefineClassPropertyXet(LPTSTR aBuf, LPTSTR aEnd); Object *FindClass(LPCTSTR aClassName, size_t aClassNameLength = 0); static SymbolType ConvertWordOperator(LPCTSTR aWord, size_t aLength); static bool EndsWithOperator(LPTSTR aBuf, LPTSTR aBuf_marker); #define FINDVAR_DEFAULT (VAR_LOCAL | VAR_GLOBAL) #define FINDVAR_GLOBAL (VAR_GLOBAL | FINDVAR_GLOBAL_FALLBACK) #define FINDVAR_LOCAL VAR_LOCAL #define FINDVAR_GLOBAL_FALLBACK 0x100 #define ADDVAR_NO_VALIDATE 0x400 #define FINDVAR_FOR_WRITE FINDVAR_DEFAULT #define FINDVAR_FOR_READ (FINDVAR_DEFAULT | FINDVAR_GLOBAL_FALLBACK) Var *FindOrAddVar(LPCTSTR aVarName, size_t aVarNameLength, int aScope); Var *FindVar(LPCTSTR aVarName, size_t aVarNameLength, int aScope = FINDVAR_FOR_READ , VarList **apList = nullptr, int *apInsertPos = nullptr, ResultType *aDisplayError = nullptr); Var *FindUpVar(LPCTSTR aVarName, size_t aVarNameLength, UserFunc &aInner, ResultType *aDisplayError); Var *AddVar(LPCTSTR aVarName, size_t aVarNameLength, VarList *aList, int aInsertPos, int aScope); Var *FindOrAddBuiltInVar(LPCTSTR aVarName, bool aAllowNonVirtual, ResultType *aDisplayError); static VarEntry *GetBuiltInVar(LPCTSTR aVarName); // Alias to improve clarity and reduce code size (if compiler chooses not to inline; due to how parameter defaults work): Var *FindGlobalVar(LPCTSTR aVarName, size_t aVarNameLength = 0) { return FindVar(aVarName, aVarNameLength, FINDVAR_GLOBAL); } VarList *GlobalVars() { return &CurrentModule()->mVars; } ScriptModule *CurrentModule() { return g->CurrentFunc ? g->CurrentFunc->mModule : mCurrentModule; } ResultType ParseModuleDirective(LPCTSTR aName); ResultType ParseImportStatement(LPTSTR aBuf); ResultType CloseCurrentModule(); ResultType ResolveImports(); ResultType ResolveImports(ScriptImport &aImport); Var *AddNewImportVar(LPTSTR aVarName); Var *FindImportedVar(LPCTSTR aVarName); ResultType DerefInclude(LPTSTR &aOutput, LPTSTR aBuf); WinGroup *FindGroup(LPCTSTR aGroupName, bool aCreateIfNotFound = false); ResultType AddGroup(LPCTSTR aGroupName); Label *FindLabel(LPCTSTR aLabelName); ResultType DoRunAs(LPTSTR aCommandLine, LPCTSTR aWorkingDir, bool aDisplayErrors, WORD aShowWindow , PROCESS_INFORMATION &aPI, bool &aSuccess, HANDLE &aNewProcess, DWORD &aLastError); ResultType ActionExec(LPCTSTR aAction, LPCTSTR aParams = NULL, LPCTSTR aWorkingDir = NULL , bool aDisplayErrors = true, LPCTSTR aRunShowMode = NULL, HANDLE *aProcess = NULL , bool aUpdateLastError = false, bool aUseRunAs = false); LPTSTR ListVars(LPTSTR aBuf, int aBufSize); LPTSTR ListKeyHistory(LPTSTR aBuf, int aBufSize); UINT GetFreeMenuItemID(); UserMenu *FindMenu(HMENU aMenuHandle); UserMenu *AddMenu(UserMenu *aMenu); ResultType ScriptDeleteMenu(UserMenu *aMenu); UserMenuItem *FindMenuItemByID(UINT aID) { for (UserMenu *m = mFirstMenu; m; m = m->mNextMenu) if (UserMenuItem *mi = m->FindItemByID(aID)) return mi; return NULL; } UserMenuItem *FindMenuItemBySubmenu(HMENU aSubmenu) // L26: Used by WM_MEASUREITEM/WM_DRAWITEM to find the menu item with an associated submenu. Fixes icons on such items when owner-drawn menus are in use. { UserMenuItem *mi; for (UserMenu *m = mFirstMenu; m; m = m->mNextMenu) for (mi = m->mFirstMenuItem; mi; mi = mi->mNextMenuItem) if (mi->mSubmenu && mi->mSubmenu->mMenu == aSubmenu) return mi; return NULL; } // Call this ScriptError to avoid confusion with Line's error-displaying functions. // Use it for load time errors and non-continuable runtime errors: ResultType ScriptError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); // , ResultType aErrorType = FAIL); // CriticalError forces the program to exit after displaying an error. // Bypasses try/catch but does allow OnError and OnExit callbacks. ResultType CriticalError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); // RuntimeError allows the user to choose to continue, in which case OK is returned instead of FAIL; // therefore, caller must not rely on a FAIL result to abort the overall operation. ResultType RuntimeError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T(""), ResultType aErrorType = FAIL_OR_OK, Line *aLine = nullptr, Object *aPrototype = nullptr); ResultType ConflictingDeclarationError(LPCTSTR aDeclType, Var *aExisting); ResultType VarIsReadOnlyError(Var *aVar, int aErrorType = VARREF_LVALUE); ResultType VarUnsetError(Var *aVar); ResultType ShowError(LPCTSTR aErrorText, ResultType aErrorType, LPCTSTR aExtraInfo, Line *aLine); ResultType ShowError(LPCTSTR aErrorText, ResultType aErrorType, LPCTSTR aExtraInfo, Line *aLine, Object *aException); ResultType ShowError(Line* aLine, ResultType aErrorType, ExprTokenType *aException); void ScriptWarning(WarnMode warnMode, LPCTSTR aWarningText, LPCTSTR aExtraInfo = _T(""), Line *line = NULL); void WarnUnassignedVar(Var *aVar, Line *aLine); void WarnLocalSameAsGlobal(LPCTSTR aVarName); ResultType PreprocessLocalVars(FuncList &aFuncs); ResultType PreprocessLocalVars(UserFunc &aFunc); ResultType PreparseVarRefs(); ResultType PreparseVarRefs(Line *aStartingLine); void CountNestedFuncRefs(UserFunc &aWithin, LPCTSTR aFuncName); ResultType ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aExtraInfo, Line *aLine, ResultType aErrorType, Object *aPrototype = nullptr); ResultType ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); ResultType Win32Error(DWORD aError = GetLastError(), ResultType aErrorType = FAIL_OR_OK); ResultType UnhandledException(Line* aLine, ResultType aErrorType = FAIL); static void FreeExceptionToken(ResultToken*& aToken); #define SOUNDPLAY_ALIAS _T("AHK_PlayMe") // Used by destructor and SoundPlay(). Script(); ~Script(); // Note that the anchors to any linked lists will be lost when this // object goes away, so for now, be sure the destructor is only called // when the program is about to be exited, which will thereby reclaim // the memory used by the abandoned linked lists (otherwise, a memory // leak will result). }; //////////////////////// // BUILT-IN VARIABLES // //////////////////////// BIV_DECL_RW(BIV_Clipboard); BIV_DECL_R (BIV_MMM_DDD); BIV_DECL_R (BIV_DateTime); BIV_DECL_RW(BIV_ListLines); BIV_DECL_RW(BIV_TitleMatchMode); BIV_DECL_R (BIV_TitleMatchModeSpeed); // Write is handled by BIV_TitleMatchMode_Set. BIV_DECL_RW(BIV_DetectHiddenWindows); BIV_DECL_RW(BIV_DetectHiddenText); BIV_DECL_RW(BIV_xDelay); BIV_DECL_RW(BIV_DefaultMouseSpeed); BIV_DECL_RW(BIV_CoordMode); BIV_DECL_RW(BIV_SendMode); BIV_DECL_RW(BIV_SendLevel); BIV_DECL_RW(BIV_StoreCapsLockMode); BIV_DECL_RW(BIV_Hotkey); BIV_DECL_R (BIV_KeybdHookInstalled); BIV_DECL_R (BIV_MouseHookInstalled); BIV_DECL_RW(BIV_MenuMaskKey); BIV_DECL_R (BIV_IsPaused); BIV_DECL_R (BIV_IsCritical); BIV_DECL_R (BIV_IsSuspended); BIV_DECL_R (BIV_IsCompiled); BIV_DECL_RW(BIV_FileEncoding); BIV_DECL_RW(BIV_RegView); BIV_DECL_RW(BIV_LastError); BIV_DECL_RW(BIV_AllowMainWindow); BIV_DECL_R (BIV_TrayMenu); BIV_DECL_RW(BIV_IconHidden); BIV_DECL_RW(BIV_IconTip); BIV_DECL_R (BIV_IconFile); BIV_DECL_R (BIV_IconNumber); BIV_DECL_R (BIV_Space_Tab); BIV_DECL_R (BIV_AhkVersion); BIV_DECL_R (BIV_AhkPath); BIV_DECL_R (BIV_TickCount); BIV_DECL_R (BIV_Now); BIV_DECL_R (BIV_OSVersion); BIV_DECL_R (BIV_Is64bitOS); BIV_DECL_R (BIV_Language); BIV_DECL_R (BIV_UserName_ComputerName); BIV_DECL_RW(BIV_WorkingDir); BIV_DECL_R (BIV_InitialWorkingDir); BIV_DECL_R (BIV_WinDir); BIV_DECL_R (BIV_Temp); BIV_DECL_R (BIV_ComSpec); BIV_DECL_R (BIV_SpecialFolderPath); // Handles various variables. BIV_DECL_R (BIV_MyDocuments); BIV_DECL_R (BIV_Caret); BIV_DECL_R (BIV_Cursor); BIV_DECL_R (BIV_ScreenWidth_Height); BIV_DECL_RW(BIV_ScriptName); BIV_DECL_R (BIV_ScriptDir); BIV_DECL_R (BIV_ScriptFullPath); BIV_DECL_R (BIV_ScriptHwnd); BIV_DECL_R (BIV_LineNumber); BIV_DECL_R (BIV_LineFile); BIV_DECL_R (BIV_LoopFileName); BIV_DECL_R (BIV_LoopFileExt); BIV_DECL_R (BIV_LoopFileDir); BIV_DECL_R (BIV_LoopFilePath); BIV_DECL_R (BIV_LoopFileFullPath); BIV_DECL_R (BIV_LoopFileShortPath); BIV_DECL_R (BIV_LoopFileTime); BIV_DECL_R (BIV_LoopFileAttrib); BIV_DECL_R (BIV_LoopFileSize); BIV_DECL_R (BIV_LoopRegType); BIV_DECL_R (BIV_LoopRegKey); BIV_DECL_R (BIV_LoopRegName); BIV_DECL_R (BIV_LoopRegTimeModified); BIV_DECL_R (BIV_LoopReadLine); BIV_DECL_R (BIV_LoopField); BIV_DECL_RW(BIV_LoopIndex); BIV_DECL_R (BIV_ThisFunc); BIV_DECL_R (BIV_ThisHotkey); BIV_DECL_R (BIV_PriorHotkey); BIV_DECL_R (BIV_TimeSinceThisHotkey); BIV_DECL_R (BIV_TimeSincePriorHotkey); BIV_DECL_R (BIV_EndChar); BIV_DECL_R (BIV_HotIf); BIV_DECL_RW(BIV_EventInfo); BIV_DECL_R (BIV_TimeIdle); BIV_DECL_R (BIV_IPAddress); BIV_DECL_R (BIV_IsAdmin); BIV_DECL_R (BIV_PtrSize); BIV_DECL_R (BIV_PriorKey); BIV_DECL_R (BIV_ScreenDPI); //////////////////////// // BUILT-IN FUNCTIONS // //////////////////////// #ifdef ENABLE_DLLCALL void *GetDllProcAddress(LPCTSTR aDllFileFunc, HMODULE *hmodule_to_free = NULL); BIF_DECL(BIF_DllCall); #endif BIF_DECL(BIF_StrCompare); BIF_DECL(BIF_String); BIF_DECL(BIF_StrLen); BIF_DECL(BIF_SubStr); BIF_DECL(BIF_InStr); BIF_DECL(BIF_StrCase); BIF_DECL(BIF_Sort); BIF_DECL(BIF_Ord); BIF_DECL(BIF_Chr); BIF_DECL(BIF_Format); BIF_DECL(BIF_FormatTime); BIF_DECL(BIF_NumGet); BIF_DECL(BIF_NumPut); BIF_DECL(BIF_StrGetPut); BIF_DECL(BIF_StrPtr); BIF_DECL(BIF_IsTypeish); BIF_DECL(BIF_IsSet); BIF_DECL(BIF_VarSetStrCapacity); BIF_DECL(BIF_WinExistActive); BIF_DECL(BIF_Round); BIF_DECL(BIF_FloorCeil); BIF_DECL(BIF_Integer); BIF_DECL(BIF_Float); BIF_DECL(BIF_Number); BIF_DECL(BIF_Mod); BIF_DECL(BIF_Abs); BIF_DECL(BIF_Sin); BIF_DECL(BIF_Cos); BIF_DECL(BIF_Tan); BIF_DECL(BIF_ASinACos); BIF_DECL(BIF_ATan); BIF_DECL(BIF_ATan2); BIF_DECL(BIF_Exp); BIF_DECL(BIF_SqrtLogLn); BIF_DECL(BIF_MinMax); BIF_DECL(BIF_Trim); // L31: Also handles LTrim and RTrim. BIF_DECL(BIF_VerCompare); BIF_DECL(BIF_Type); BIF_DECL(BIF_IsObject); BIF_DECL(BIF_Throw); BIF_DECL(Op_Object); BIF_DECL(Op_Array); BIF_DECL(Op_RegEx); BIF_DECL(BIF_ObjAddRefRelease); BIF_DECL(BIF_ObjBindMethod); BIF_DECL(BIF_ObjPtr); // Built-ins also available as methods -- these are available as functions for use primarily by overridden methods (i.e. where using the built-in methods isn't possible as they're no longer accessible). BIF_DECL(BIF_ObjXXX); BIF_DECL(BIF_StructFromPtr); BIF_DECL(BIF_Base); BIF_DECL(BIF_HasBase); BIF_DECL(BIF_HasProp); BIF_DECL(BIF_GetMethod); // Advanced file IO interfaces BIF_DECL(BIF_FileOpen); // COM interop BIF_DECL(ComValue_Call); BIF_DECL(ComObject_Call); BIF_DECL(ComObjArray_Call); BIF_DECL(BIF_ComObj); BIF_DECL(BIF_ComObjActive); BIF_DECL(BIF_ComObjGet); BIF_DECL(BIF_ComObjConnect); BIF_DECL(BIF_ComObjType); BIF_DECL(BIF_ComObjValue); BIF_DECL(BIF_ComObjFlags); BIF_DECL(BIF_ComObjQuery); BIF_DECL(BIF_Click); BIF_DECL(BIF_Reg); BIF_DECL(BIF_Random); BIF_DECL(BIF_Sound); BOOL ResultToBOOL(LPTSTR aResult); BOOL VarToBOOL(Var &aVar); BOOL TokenToBOOL(ExprTokenType &aToken); ToggleValueType TokenToToggleValue(ExprTokenType &aToken); SymbolType TokenIsNumeric(ExprTokenType &aToken); SymbolType TokenIsPureNumeric(ExprTokenType &aToken); SymbolType TokenIsPureNumeric(ExprTokenType &aToken, SymbolType &aIsImpureNumeric); BOOL TokenIsEmptyString(ExprTokenType &aToken); SymbolType TypeOfToken(ExprTokenType &aToken); __int64 TokenToInt64(ExprTokenType &aToken); double TokenToDouble(ExprTokenType &aToken, BOOL aCheckForHex = TRUE); LPTSTR TokenToString(ExprTokenType &aToken, LPTSTR aBuf = NULL, size_t *aLength = NULL); ResultType TokenToDoubleOrInt64(const ExprTokenType &aInput, ExprTokenType &aOutput); StringCaseSenseType TokenToStringCase(ExprTokenType& aToken); bool TokenIsOutputVar(ExprTokenType &aToken); bool ObjectCanBeOutputVar(IObject *aObj); Var *TokenToOutputVar(ExprTokenType &aToken); IObject *TokenToObject(ExprTokenType &aToken); // L31 ResultType ValidateFunctor(IObject *aFunc, int aParamCount, ResultToken &aResultToken, int *aMinParams = nullptr, bool aShowError = true); FResult ValidateFunctor(IObject *aFunc, int aParamCount, int *aMinParams = nullptr, bool aShowError = true); ResultType TokenSetResult(ResultToken &aResultToken, LPCTSTR aValue, size_t aLength = -1); LPTSTR TokenTypeString(ExprTokenType &aToken); #define STRING_TYPE_STRING _T("String") #define INTEGER_TYPE_STRING _T("Integer") #define FLOAT_TYPE_STRING _T("Float") ResultType TokenToStringParam(ResultToken &aResultToken, ExprTokenType *aParam[], int aIndex, LPTSTR aBuf, LPTSTR &aString, size_t *aLength = nullptr, bool aPermitObject = false); ResultType MemoryError(); ResultType ValueError(LPCTSTR aErrorText, LPCTSTR aExtraInfo, ResultType aErrorType); ResultType TypeError(LPCTSTR aExpectedType, ExprTokenType &aActualValue); ResultType TypeError(LPCTSTR aExpectedType, LPCTSTR aActualType, LPCTSTR aExtraInfo); ResultType ParamError(int aIndex, ExprTokenType *aParam, LPCTSTR aExpectedType, LPCTSTR aFunction); FResult FError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T(""), Object *aPrototype = nullptr); FResult FValueError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); FResult FTypeError(LPCTSTR aExpectedType, ExprTokenType &aActualValue); FResult FParamError(int aIndex, ExprTokenType *aParam, LPCTSTR aExpectedType = nullptr); ResultType FResultToError(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount, FResult aResult, int aFirstParam); void PauseCurrentThread(); void ToggleSuspendState(); LPCTSTR RegExMatch(LPCTSTR aHaystack, LPCTSTR aNeedleRegEx); FResult SetWorkingDir(LPCTSTR aNewDir); void UpdateWorkingDir(LPCTSTR aNewDir = NULL); LPTSTR GetWorkingDir(); int ConvertJoy(LPCTSTR aBuf, int *aJoystickID = NULL, bool aAllowOnlyButtons = false); bool ScriptGetKeyState(vk_type aVK, KeyStateTypes aKeyStateType); bool ScriptGetJoyState(JoyControls aJoy, int aJoystickID, ExprTokenType &aToken, LPTSTR aBuf); bool FileCreateDir(LPCTSTR aDirSpec); ResultType DetermineTargetHwnd(HWND &aWindow, ResultToken &aResultToken, ExprTokenType &aToken); ResultType DetermineTargetWindow(HWND &aWindow, ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount, int aNonWinParamCount = 0); #define WINTITLE_PARAMETERS_DECL ExprTokenType *aWinTitle, optl<StrArg> aWinText, optl<StrArg> aExcludeTitle, optl<StrArg> aExcludeText #define WINTITLE_PARAMETERS aWinTitle, aWinText, aExcludeTitle, aExcludeText FResult DetermineTargetHwnd(HWND &aWindow, bool &aDetermined, ExprTokenType &aToken); FResult DetermineTargetWindow(HWND &aWindow, WINTITLE_PARAMETERS_DECL, bool aFindLastMatch = false); #define CONTROL_PARAMETERS_DECL ExprTokenType &aControlSpec, WINTITLE_PARAMETERS_DECL #define CONTROL_PARAMETERS_DECL_OPT ExprTokenType *aControlSpec, WINTITLE_PARAMETERS_DECL #define CONTROL_PARAMETERS aControlSpec, WINTITLE_PARAMETERS FResult DetermineTargetControl(HWND &aControl, HWND &aWindow, CONTROL_PARAMETERS_DECL, bool aThrowIfNotFound = true); FResult DetermineTargetControl(HWND &aControl, HWND &aWindow, CONTROL_PARAMETERS_DECL_OPT, bool aThrowIfNotFound = true); #define DETERMINE_TARGET_WINDOW do { \ auto fr = DetermineTargetWindow(target_window, aWinTitle, aWinText.value_or_null(), aExcludeTitle.value_or_null(), aExcludeText.value_or_null()); \ if (fr != OK) \ return fr; } while (0) #define DETERMINE_TARGET_CONTROL2 \ HWND target_window, control_window; \ { auto fr = DetermineTargetControl(control_window, target_window, CONTROL_PARAMETERS); \ if (fr != OK) \ return fr; } LPTSTR GetExitReasonString(ExitReasons aExitReason); FResult ControlSetTab(HWND aHwnd, DWORD aTabIndex); FResult PixelSearch(BOOL *aFound, ResultToken *aFoundX, ResultToken *aFoundY , int aLeft, int aTop, int aRight, int aBottom, COLORREF aColorRGB , int aVariation, LPTSTR aGetColor); bool ColorToBGR(ExprTokenType &aColorNameOrRGB, COLORREF &aBGR); ResultType GetObjectPtrProperty(IObject *aObject, LPTSTR aPropName, UINT_PTR &aPtr, ResultToken &aResultToken, bool aOptional = false); ResultType GetObjectIntProperty(IObject *aObject, LPTSTR aPropName, __int64 &aValue, ResultToken &aResultToken, bool aOptional = false); ResultType SetObjectIntProperty(IObject * aObject, LPTSTR aPropName, __int64 aValue, ResultToken & aResultToken); void GetBufferObjectPtr(ResultToken &aResultToken, IObject *obj, size_t &aPtr, size_t &aSize); void GetBufferObjectPtr(ResultToken &aResultToken, IObject *obj, size_t &aPtr); void ObjectToString(ResultToken & aResultToken, ExprTokenType & aThisToken, IObject * aObject); #ifdef CONFIG_DLL bool LibNotifyProblem(ExprTokenType &aProblem); bool LibNotifyProblem(LPCTSTR aMessage, LPCTSTR aExtra, Line *aLine, bool aWarn = false); #endif #endif
116,458
C++
.h
2,403
46.337495
311
0.755975
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,132
DispObject.h
AutoHotkey_AutoHotkey/source/DispObject.h
/* DispObject.h Original code by Steve Gray. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, without restriction. */ #pragma once // DispObject : Template for boiler-plate IDispatch objects. template <typename I> class DispObject : public I { public: // IUnknown STDMETHOD_(ULONG, AddRef)(); STDMETHOD_(ULONG, Release)(); STDMETHOD(QueryInterface)(REFIID iid, void** ppv); // IDispatch STDMETHOD(GetTypeInfoCount)(UINT* pCountTypeInfo); STDMETHOD(GetTypeInfo)(UINT iTypeInfo, LCID lcid, ITypeInfo** ppITypeInfo); STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgDispId); STDMETHOD(Invoke)(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pDispParams , VARIANT* pVarResult, EXCEPINFO* pExcepInfo, UINT* puArgErr); DispObject(ITypeInfo *typeInfo) : m_cRef(1), m_pTypeInfo(typeInfo) {} ~DispObject(); typedef I *DispInterface; private: ULONG m_cRef; ITypeInfo* m_pTypeInfo; }; HRESULT LoadMyTypeInfo(REFIID riid, ITypeInfo **ppTypeInfo); template<class T, typename I> HRESULT CreateDispatchInstance(I **ppInst) { ITypeInfo *typeInfo; auto hr = LoadMyTypeInfo(__uuidof(T::DispInterface), &typeInfo); if (FAILED(hr)) { *ppInst = nullptr; return hr; } *ppInst = new T(typeInfo); return S_OK; } template<typename I> DispObject<I>::~DispObject() { if (m_pTypeInfo) m_pTypeInfo->Release(); } // // IUnknown methods // template<typename I> STDMETHODIMP DispObject<I>::QueryInterface(REFIID iid, void ** ppv) { if (iid == IID_IUnknown) *ppv = static_cast<IUnknown*>(this); else if (iid == __uuidof(I)) *ppv = static_cast<I*>(this); else if (iid == IID_IDispatch) *ppv = static_cast<IDispatch*>(this); else { *ppv = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; } template<typename I> STDMETHODIMP_(ULONG) DispObject<I>::AddRef() { return ++m_cRef; } template<typename I> STDMETHODIMP_(ULONG) DispObject<I>::Release() { if (--m_cRef != 0) return m_cRef; delete this; return 0; } // // IDispatch methods // template<typename I> STDMETHODIMP DispObject<I>::GetTypeInfoCount(UINT * pCountTypeInfo) { *pCountTypeInfo = 1; return S_OK; } template<typename I> STDMETHODIMP DispObject<I>::GetTypeInfo(UINT iTypeInfo, LCID lcid, ITypeInfo ** ppITypeInfo) { if (iTypeInfo != 0) return DISP_E_BADINDEX; m_pTypeInfo->AddRef(); *ppITypeInfo = m_pTypeInfo; return S_OK; } template<typename I> STDMETHODIMP DispObject<I>::GetIDsOfNames(REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId) { return m_pTypeInfo->GetIDsOfNames(rgszNames, cNames, rgDispId); } template<typename I> STDMETHODIMP DispObject<I>::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr) { return m_pTypeInfo->Invoke(static_cast<I*>(this), dispIdMember, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); }
3,225
C++
.h
113
26.707965
181
0.761426
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,133
debug.h
AutoHotkey_AutoHotkey/source/debug.h
#pragma once // This file debugging defines some macros like MFC does. #ifndef TRACE #ifdef _DEBUG #ifdef _MSC_VER #define TRACE OutputDebugStringFormat #else #define TRACE(...) _ftprintf(stderr, __VA_ARGS__) #endif #else #define TRACE(...) #endif #endif /* This part of codes map the new operator to the debug version. Although the map is contains in "crtdbg.h", it is not really work (we will always get a wrong information show us the leaked memory blocks are allocated in "crtdbg.h"). */ #ifdef _MSC_VER // #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> // #ifdef _DEBUG // #define new new(_NORMAL_BLOCK, __FILE__, __LINE__) // #endif #endif #ifndef ASSERT #ifdef _ASSERTE #define ASSERT(expr) _ASSERTE(expr) #else #ifdef _DEBUG #include <assert.h> #define ASSERT(expr) assert(expr) #else #define ASSERT(expr) #endif #endif #endif #ifndef VERIFY #ifdef _DEBUG #define VERIFY(expr) ASSERT(expr) #else #define VERIFY(expr) expr #endif #endif
996
C++
.h
43
20.953488
124
0.721987
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,134
Debugger.h
AutoHotkey_AutoHotkey/source/Debugger.h
/* Debugger.h Original code by Steve Gray. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, without restriction. */ #pragma once #ifndef CONFIG_DEBUGGER #define DEBUGGER_STACK_PUSH(...) #define DEBUGGER_STACK_POP() #else #ifndef Debugger_h #define Debugger_h #include <winsock2.h> #include "script_object.h" #define DEBUGGER_INITIAL_BUFFER_SIZE 2048 #define DEBUGGER_XML_TAG "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" #define DEBUGGER_XML_TAG_SIZE (_countof(DEBUGGER_XML_TAG)-1) #define DEBUGGER_LANG_NAME AHK_NAME // DBGp Error Codes #define DEBUGGER_E_OK 0 #define DEBUGGER_E_PARSE_ERROR 1 #define DEBUGGER_E_INVALID_OPTIONS 3 #define DEBUGGER_E_UNIMPL_COMMAND 4 #define DEBUGGER_E_COMMAND_UNAVAIL 5 #define DEBUGGER_E_CAN_NOT_OPEN_FILE 100 #define DEBUGGER_E_BREAKPOINT_TYPE 201 // Breakpoint type not supported. #define DEBUGGER_E_BREAKPOINT_INVALID 202 // Invalid line number or filename. #define DEBUGGER_E_BREAKPOINT_NO_CODE 203 // No code on breakpoint line. #define DEBUGGER_E_BREAKPOINT_STATE 204 // Invalid breakpoint state. #define DEBUGGER_E_BREAKPOINT_NOT_FOUND 205 // No such breakpoint. #define DEBUGGER_E_EVAL_FAIL 206 #define DEBUGGER_E_UNKNOWN_PROPERTY 300 #define DEBUGGER_E_INVALID_STACK_DEPTH 301 #define DEBUGGER_E_INVALID_CONTEXT 302 #define DEBUGGER_E_INTERNAL_ERROR 998 // Unrecoverable internal error, usually the result of a Winsock error. #define DEBUGGER_E_CONTINUE -1 // Internal code used by continuation commands. // Error messages: these are shown directly to the user, so are in the native string format. #define DEBUGGER_ERR_INTERNAL _T("An internal error has occurred in the debugger engine.") #define DEBUGGER_ERR_DISCONNECT_PROMPT _T("\nContinue running the script without the debugger?") #define DEBUGGER_ERR_FAILEDTOCONNECT _T("Failed to connect to an active debugger client.") // Buffer size required for a given XML message size, plus protocol overhead. // Format: data_length NULL xml_tag data NULL //#define DEBUGGER_XML_SIZE_REQUIRED(xml_size) (MAX_NUMBER_LENGTH + DEBUGGER_XML_TAG_SIZE + xml_size + 2) #define DEBUGGER_RESPONSE_OVERHEAD (MAX_INTEGER_LENGTH + DEBUGGER_XML_TAG_SIZE + 2) class Debugger; extern Debugger g_Debugger; // jackieku: modified to hold the buffer. extern CStringA g_DebuggerHost; extern CStringA g_DebuggerPort; extern LPCTSTR g_AutoExecuteThreadDesc; enum BreakpointTypeType {BT_Line, BT_Call, BT_Return, BT_Exception, BT_Conditional, BT_Watch}; enum BreakpointStateType {BS_Disabled=0, BS_Enabled}; class Breakpoint { public: int id; char type; char state = BS_Disabled; bool temporary = false; Line *line = nullptr; Breakpoint *next = nullptr; // Not yet supported: function, hit_count, hit_value, hit_condition Breakpoint(BreakpointTypeType aType = BT_Line, int aID = AllocateID()) : id(aID), type((char)aType) {} static int AllocateID() { return ++sMaxId; } private: static int sMaxId; // Highest used breakpoint ID. }; // Forward-declarations (this file is included in script.h before these are declared). class Line; class NativeFunc; struct UDFCallInfo; template<typename T, int S> struct ScriptItemList; typedef ScriptItemList<Var, VARLIST_INITIAL_SIZE> VarList; struct DbgStack { enum StackEntryType {SE_Thread, SE_BIF, SE_UDF}; struct Entry { Line *line; union { LPCTSTR desc; // SE_Thread -- "auto-exec", hotkey/hotstring name, "timer", etc. NativeFunc *func; // SE_BIF UDFCallInfo *udf; // SE_UDF }; StackEntryType type; LPCTSTR Name(); }; Entry *mBottom, *mTop, *mTopBound; size_t mSize; // i.e. capacity. DbgStack() { // We don't want to set the following too low since the stack would need to be reallocated, // but also don't want to set it too high since the average script mightn't recurse deeply; // if the stack size never approaches its maximum, there'll be wasted memory: mSize = 128; mBottom = (Entry *)malloc(mSize * sizeof(Entry)); mTop = mBottom - 1; // ++mTop will be the first entry. mTopBound = mTop + mSize; // Topmost valid position. } int Depth() { return (int)(mTop + 1 - mBottom); } // noinline currently seems to have a slight effect on benchmarks. // Since it should be called very rarely, we don't want it inlined. void __declspec(noinline) Expand() { mSize *= 2; // To keep the design as simple as possible, assume the allocation will never fail. // These reallocations should be very rare: if size starts at 128 and doubles each // time, three expansions would bring it to 1024 entries, which is probably larger // than any script could need. (Generally the program's stack will run out before // script recursion gets anywhere near that deep.) Entry *new_bottom = (Entry *)realloc(mBottom, mSize * sizeof(Entry)); // Recalculate top of stack. mTop = mTop - mBottom + new_bottom; mBottom = new_bottom; // After using its old value. // Pre-calculate upper bound to keep Push() simple. mTopBound = mBottom - 1 + mSize; } Entry *Push(); void Pop(); void Push(LPCTSTR aDesc); void Push(NativeFunc *aFunc); void Push(UDFCallInfo *aRecurse); void GetLocalVars(int aDepth, VarList *&aVars, VarList *&aStaticVars, VarBkp *&aBkp, VarBkp *&aBkpEnd); }; #define DEBUGGER_STACK_PUSH(aWhat) g_Debugger.mStack.Push(aWhat); #define DEBUGGER_STACK_POP() g_Debugger.mStack.Pop(); enum PropertyContextType {PC_Local=0, PC_Global}; class Debugger { public: int Connect(const char *aAddress, const char *aPort); int Disconnect(); void Exit(ExitReasons aExitReason, char *aCommandName=NULL); // Called when exiting AutoHotkey. inline bool IsConnected() { return mSocket != INVALID_SOCKET; } inline bool IsStepping() { return mInternalState >= DIS_StepInto; } inline bool HasStdErrHook() { return mStdErrMode != SR_Disabled; } inline bool HasStdOutHook() { return mStdOutMode != SR_Disabled; } inline bool BreakOnExceptionIsEnabled() { return mBreakOnException.state == BS_Enabled; } LPCTSTR WhatThrew(); // Code flow notification functions: int PreExecLine(Line *aLine); // Called before executing each line. void LeaveFunction(); bool PreThrow(ExprTokenType *aException); // Receive and process commands. Returns when a continuation command is received. int ProcessCommands(LPCSTR aBreakReason = nullptr); int Break(LPCSTR aReason = "ok"); bool HasPendingCommand(); // Streams int WriteStreamPacket(LPCTSTR aText, LPCSTR aType); bool OutputStdErr(LPCTSTR aText); bool OutputStdOut(LPCTSTR aText); #define DEBUGGER_COMMAND(cmd) int cmd(char **aArgV, int aArgCount, char *aTransactionId) // // Debugger commands. // DEBUGGER_COMMAND(status); DEBUGGER_COMMAND(feature_get); DEBUGGER_COMMAND(feature_set); DEBUGGER_COMMAND(run); DEBUGGER_COMMAND(step_into); DEBUGGER_COMMAND(step_over); DEBUGGER_COMMAND(step_out); DEBUGGER_COMMAND(_break); DEBUGGER_COMMAND(stop); DEBUGGER_COMMAND(detach); DEBUGGER_COMMAND(breakpoint_set); DEBUGGER_COMMAND(breakpoint_get); DEBUGGER_COMMAND(breakpoint_update); DEBUGGER_COMMAND(breakpoint_remove); DEBUGGER_COMMAND(breakpoint_list); DEBUGGER_COMMAND(stack_depth); DEBUGGER_COMMAND(stack_get); DEBUGGER_COMMAND(context_names); DEBUGGER_COMMAND(context_get); DEBUGGER_COMMAND(typemap_get); DEBUGGER_COMMAND(property_get); DEBUGGER_COMMAND(property_set); DEBUGGER_COMMAND(property_value); DEBUGGER_COMMAND(source); DEBUGGER_COMMAND(redirect_stdout); DEBUGGER_COMMAND(redirect_stderr); Debugger() {} // Stack - keeps track of threads and function calls. DbgStack mStack; friend struct DbgStack; private: SOCKET mSocket = INVALID_SOCKET; Line *mCurrLine = nullptr; // Similar to g_script.mCurrLine, but may be different when breaking post-function-call, before continuing expression evaluation. ExprTokenType *mThrownToken = nullptr; // The exception that triggered the current exception breakpoint. // Linked list of breakpoints. Using the exception breakpoint as the const head of the list simplifies // some operations and reduces code size. The first line breakpoint is always mFirstBreakpoint->next. Breakpoint *const mFirstBreakpoint = &mBreakOnException, *mLastBreakpoint = &mBreakOnException; Breakpoint mBreakOnException { BT_Exception, 0 }; // Supports a single catchall breakpoint exception. class Buffer { public: int Write(char *aData, size_t aDataSize=-1); int WriteF(const char *aFormat, ...); int WriteEncodeBase64(const char *aData, size_t aDataSize, bool aSkipBufferSizeCheck = false); int Expand(); int ExpandIfNecessary(size_t aRequiredSize); void Delete(size_t aDataSize); void Clear(); Buffer() : mData(NULL), mDataSize(0), mDataUsed(0), mFailed(FALSE) {} char *mData; size_t mDataSize; size_t mDataUsed; BOOL mFailed; ~Buffer() { if (mData) free(mData); } private: int EstimateFileURILength(LPCTSTR aPath); void WriteFileURI(LPCWSTR aPath); } mCommandBuf, mResponseBuf; enum DebuggerInternalStateType { DIS_None = 0, DIS_Starting = DIS_None, DIS_Run, DIS_Break, DIS_StepInto, DIS_StepOver, DIS_StepOut } mInternalState = DIS_Starting; enum StreamRedirectType { SR_Disabled = 0, SR_Copy = 1, SR_Redirect = 2 } mStdErrMode = SR_Disabled, mStdOutMode = SR_Disabled; int mContinuationDepth = 0; // Stack depth at last continuation command, for step_into/step_over. CStringA mContinuationTransactionId {""}; // transaction_id of last continuation command. int mMaxPropertyData = 1024, mMaxChildren = 1000, mMaxDepth = 1; HookType mDisabledHooks = 0; bool mProcessingCommands; enum PropertyType { PropNone = 0, PropVar, PropVarBkp, PropValue, // Read-only (ExprTokenType) PropEnum }; struct PropertySource { PropertyType kind = PropNone; Var *var; VarBkp *bkp; ResultToken value; IObject *invokee = nullptr; PropertySource(LPTSTR aResultBuf) { value.InitResult(aResultBuf); } ~PropertySource() { value.Free(); } }; struct PropertyInfo : PropertySource { LPCSTR name; CStringA &fullname; LPSTR facet; // Initialised during writing. bool is_alias = false, is_builtin = false, is_static = false; // Facets. int page = 0, pagesize; // Attributes which are also parameters. int max_data; // Parameters. int max_depth; PropertyInfo(CStringA &aNameBuf, LPTSTR aResultBuf) : PropertySource(aResultBuf), fullname(aNameBuf) {} }; struct PropertyWriter : public IDebugProperties { Debugger &mDbg; PropertyInfo &mProp; size_t mNameLength; int mDepth; int mError; PropertyWriter(Debugger &aDbg, PropertyInfo &aProp) : mDbg(aDbg) , mProp(aProp) , mNameLength(aProp.fullname.GetLength()) , mDepth(0) , mError(0) { } void WriteProperty(LPCSTR aName, ExprTokenType &aValue); void WriteProperty(LPCWSTR aName, ExprTokenType &aValue); void WriteProperty(ExprTokenType &aKey, ExprTokenType &aValue); void WriteBaseProperty(IObject *aBase); void WriteDynamicProperty(LPTSTR aName); void WriteEnumItems(IObject *aEnumerable, int aStart, int aEnd); void _WriteProperty(ExprTokenType &aValue, IObject *aInvokee = nullptr); void BeginProperty(LPCSTR aName, LPCSTR aType, int aNumChildren, DebugCookie &aCookie); void EndProperty(DebugCookie aCookie); ExprTokenType &ThisToken() { return mProp.value; } }; // Receive next command from debugger UI: int ReceiveCommand(int *aCommandSize=NULL); // Send XML response to debugger UI: int SendResponse(size_t aStartOffset = 0); int SendErrorResponse(char *aCommandName, char *aTransactionId, int aError=999, char *aExtraAttributes=NULL); int SendStandardResponse(char *aCommandName, char *aTransactionId); int SendContinuationResponse(LPCSTR aCommand = nullptr, LPCSTR aStatus = "break", LPCSTR aReason = "ok"); int EnterBreakState(LPCSTR aReason = "ok"); void ExitBreakState(); int WriteBreakpointXml(Breakpoint *aBreakpoint); Line *FindFirstLineForBreakpoint(int file_index, UINT line_no); Breakpoint *CreateBreakpoint(); void DeleteBreakpoint(Breakpoint *aBp); void AppendPropertyName(CStringA &aNameBuf, size_t aParentNameLength, const char *aName); void AppendStringKey(CStringA &aNameBuf, size_t aParentNameLength, const char *aKey); int GetPropertyInfo(Var &aVar, PropertyInfo &aProp); int GetPropertyInfo(VarBkp &aBkp, PropertyInfo &aProp); int GetPropertyValue(Var &aVar, ResultToken &aValue); int GetPropertyValue(VarBkp &aBkp, ResultToken &aValue); int WritePropertyXml(PropertyInfo &aProp); int WritePropertyXml(PropertyInfo &aProp, LPTSTR aName); int WritePropertyObjectXml(PropertyInfo &aProp); int WritePropertyData(LPCTSTR aData, size_t aDataSize, int aMaxEncodedSize); int WritePropertyData(ExprTokenType &aValue, int aMaxEncodedSize); int WriteEnumItems(PropertyInfo &aProp); LPWSTR ParsePropertyKeyLiteral(LPWSTR aPtr, ExprTokenType &aKey); int ParsePropertyName(LPCSTR aFullName, int aDepth, int aVarScope, ExprTokenType *aSetValue , PropertySource &aResult); int ParsePropertyName(LPWSTR aNamePtr, int aDepth, int aVarScope, ExprTokenType *aSetValue , PropertySource &aResult); int property_get_or_value(char **aArgV, int aArgCount, char *aTransactionId, bool aIsPropertyGet); int redirect_std(char **aArgV, int aArgCount, char *aTransactionId, char *aCommandName); int run_step(char **aArgV, int aArgCount, char *aTransactionId, char *aCommandName, DebuggerInternalStateType aNewState); // Decode a file URI in-place. void DecodeURI(char *aUri); static const char *sBase64Chars; static size_t Base64Encode(char *aBuf, const char *aInput, size_t aInputSize = -1); static size_t Base64Decode(char *aBuf, const char *aInput, size_t aInputSize = -1); //typedef int (Debugger::*CommandFunc)(char **aArgV, int aArgCount, char *aTransactionId); typedef DEBUGGER_COMMAND((Debugger::*CommandFunc)); struct CommandDef { const char *mName; CommandFunc mFunc; }; static CommandDef sCommands[]; // Debugger::ParseArgs // // Returns DEBUGGER_E_OK on success, or a DBGp error code otherwise. // // The Xdebug/DBGp documentation is very vague about command line rules, // so this function has no special treatment of quotes, backslash, etc. // There is currently no way to include a literal " -" in an arg as it // would be recognized as the beginning of the next arg. // int ParseArgs(char *aArgs, char **aArgV, int &aArgCount, char *&aTransactionId); // Caller must verify that aArg is within bounds: inline char *ArgValue(char **aArgV, int aArg) { return aArgV[aArg] + 1; } inline char ArgChar(char **aArgV, int aArg) { return *aArgV[aArg]; } // Fatal debugger error. Prompt user to terminate script or only disconnect debugger. static int FatalError(LPCTSTR aMessage = DEBUGGER_ERR_INTERNAL DEBUGGER_ERR_DISCONNECT_PROMPT); }; constexpr auto SCRIPT_STACK_BUF_SIZE = 2048; // Character limit for Error().Stack and stack traces generated by the error dialog. void GetScriptStack(LPTSTR aBuf, int aBufSize, DbgStack::Entry *aTop = nullptr); #endif #endif
15,267
C++
.h
373
38.455764
157
0.768835
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,136
input_object.h
AutoHotkey_AutoHotkey/source/input_object.h
#pragma once class InputObject : public Object { input_type input; FResult get_On(IObject *&aRetVal, IObject *&aOn); FResult set_On(ExprTokenType &aValue, IObject *&aOn, int aValidParamCount); public: IObject *onEnd = nullptr, *onKeyDown = nullptr, *onChar = nullptr, *onKeyUp = nullptr; static Object *sPrototype; static ObjectMemberMd sMembers[]; static int sMemberCount; InputObject(); ~InputObject() { if (onEnd) onEnd->Release(); if (onKeyDown) onKeyDown->Release(); if (onChar) onChar->Release(); if (onKeyUp) onKeyUp->Release(); } static Object *Create(); FResult __New(optl<StrArg> aOptions, optl<StrArg> aEndKeys, optl<StrArg> aMatchList); FResult Start(); FResult Wait(optl<double> aMaxTime, StrRet &aRetVal); FResult Stop(); FResult KeyOpt(StrArg aKeys, StrArg aKeyOptions); FResult get_InProgress(BOOL &aRetVal) { aRetVal = input.InProgress(); return OK; } FResult get_EndReason(StrRet &aRetVal); FResult get_EndKey(StrRet &aRetVal); FResult get_EndMods(StrRet &aRetVal); FResult get_Input(StrRet &aRetVal); FResult get_Match(StrRet &aRetVal); #define ONX_OPTION(X, N) \ FResult get_On##X(IObject *&aRetVal) { \ return get_On(aRetVal, on##X); \ } \ FResult set_On##X(ExprTokenType &aValue) { \ return set_On(aValue, on##X, N); \ } ONX_OPTION(End, 1); ONX_OPTION(Char, 2); ONX_OPTION(KeyDown, 3); ONX_OPTION(KeyUp, 3); #undef ONX_OPTION #define BOOL_OPTION(OPT) \ FResult get_##OPT(BOOL &aRetVal) { \ aRetVal = input.OPT; \ return OK; \ } \ FResult set_##OPT(BOOL aValue) { \ input.OPT = aValue; \ return OK; \ } BOOL_OPTION(BackspaceIsUndo); BOOL_OPTION(CaseSensitive); BOOL_OPTION(FindAnywhere); BOOL_OPTION(NotifyNonText); BOOL_OPTION(VisibleNonText); BOOL_OPTION(VisibleText); #undef BOOL_OPTION FResult get_MinSendLevel(int &aRetVal) { aRetVal = input.MinSendLevel; return OK; } FResult set_MinSendLevel(int aValue); FResult get_Timeout(double &aRetVal) { aRetVal = input.Timeout / 1000.0; return OK; } FResult set_Timeout(double aValue); };
2,078
C++
.h
68
27.808824
87
0.724068
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,137
keyboard_mouse.h
AutoHotkey_AutoHotkey/source/keyboard_mouse.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #ifndef keyboard_h #define keyboard_h #include "defines.h" #include "abi.h" EXTERN_G; // The max number of keystrokes to Send prior to taking a break to pump messages: #define MAX_LUMP_KEYS 50 // Maybe define more of these later, perhaps with ifndef (since they should be in the normal header, and probably // will be eventually): // ALREADY DEFINED: #define VK_HELP 0x2F // In case a compiler with a non-updated header file is used: #ifndef VK_BROWSER_BACK #define VK_BROWSER_BACK 0xA6 #define VK_BROWSER_FORWARD 0xA7 #define VK_BROWSER_REFRESH 0xA8 #define VK_BROWSER_STOP 0xA9 #define VK_BROWSER_SEARCH 0xAA #define VK_BROWSER_FAVORITES 0xAB #define VK_BROWSER_HOME 0xAC #define VK_VOLUME_MUTE 0xAD #define VK_VOLUME_DOWN 0xAE #define VK_VOLUME_UP 0xAF #define VK_MEDIA_NEXT_TRACK 0xB0 #define VK_MEDIA_PREV_TRACK 0xB1 #define VK_MEDIA_STOP 0xB2 #define VK_MEDIA_PLAY_PAUSE 0xB3 #define VK_LAUNCH_MAIL 0xB4 #define VK_LAUNCH_MEDIA_SELECT 0xB5 #define VK_LAUNCH_APP1 0xB6 #define VK_LAUNCH_APP2 0xB7 #endif // Create some "fake" virtual keys to simplify sections of the code. // According to winuser.h, the following ranges (among others) // are considered "unassigned" rather than "reserved", so should be // fairly safe to use for the foreseeable future. 0xFF should probably // be avoided since it's sometimes used as a failure indictor by API // calls. And 0x00 should definitely be avoided because it is used // to indicate failure by many functions that deal with virtual keys. // 0x88 - 0x8F : unassigned // 0x97 - 0x9F : unassigned (this range seems less likely to be used) #define VK_NEW_MOUSE_FIRST 0x9A #define VK_WHEEL_LEFT 0x9C // v1.0.48: Lexikos: Fake virtual keys for support for horizontal scrolling in #define VK_WHEEL_RIGHT 0x9D // Windows Vista and later. #define VK_WHEEL_DOWN 0x9E #define VK_WHEEL_UP 0x9F #define IS_WHEEL_VK(aVK) ((aVK) >= VK_WHEEL_LEFT && (aVK) <= VK_WHEEL_UP) #define VK_NEW_MOUSE_LAST 0x9F // These are the only keys for which another key with the same VK exists. Therefore, use scan code for these. // If use VK for some of these (due to them being more likely to be used as hotkeys, thus minimizing the // use of the keyboard hook), be sure to use SC for its counterpart. // Always use the compressed version of scancode, i.e. 0x01 for the high-order byte rather than vs. 0xE0. #define SC_NUMPADENTER 0x11C #define SC_INSERT 0x152 #define SC_DELETE 0x153 #define SC_HOME 0x147 #define SC_END 0x14F #define SC_UP 0x148 #define SC_DOWN 0x150 #define SC_LEFT 0x14B #define SC_RIGHT 0x14D #define SC_PGUP 0x149 #define SC_PGDN 0x151 // These are the same scan codes as their counterpart except the extended flag is 0 rather than // 1 (0xE0 uncompressed): #define SC_ENTER 0x1C // In addition, the below dual-state numpad keys share the same scan code (but different vk's) // regardless of the state of numlock: #define SC_NUMPADDEL 0x53 #define SC_NUMPADINS 0x52 #define SC_NUMPADEND 0x4F #define SC_NUMPADHOME 0x47 #define SC_NUMPADCLEAR 0x4C #define SC_NUMPADUP 0x48 #define SC_NUMPADDOWN 0x50 #define SC_NUMPADLEFT 0x4B #define SC_NUMPADRIGHT 0x4D #define SC_NUMPADPGUP 0x49 #define SC_NUMPADPGDN 0x51 #define SC_NUMPADDOT SC_NUMPADDEL #define SC_NUMPAD0 SC_NUMPADINS #define SC_NUMPAD1 SC_NUMPADEND #define SC_NUMPAD2 SC_NUMPADDOWN #define SC_NUMPAD3 SC_NUMPADPGDN #define SC_NUMPAD4 SC_NUMPADLEFT #define SC_NUMPAD5 SC_NUMPADCLEAR #define SC_NUMPAD6 SC_NUMPADRIGHT #define SC_NUMPAD7 SC_NUMPADHOME #define SC_NUMPAD8 SC_NUMPADUP #define SC_NUMPAD9 SC_NUMPADPGUP #define SC_NUMLOCK 0x145 #define SC_NUMPADDIV 0x135 #define SC_NUMPADMULT 0x037 #define SC_NUMPADSUB 0x04A #define SC_NUMPADADD 0x04E #define SC_PAUSE 0x045 #define SC_LCONTROL 0x01D #define SC_RCONTROL 0x11D #define SC_LSHIFT 0x02A #define SC_RSHIFT 0x136 // Must be extended, at least on WinXP, or there will be problems, e.g. SetModifierLRState(). #define SC_LALT 0x038 #define SC_RALT 0x138 #define SC_LWIN 0x15B #define SC_RWIN 0x15C #define SC_APPSKEY 0x15D #define SC_PRINTSCREEN 0x137 // The system injects events with these scan codes: // - For Shift-up prior to a Numpad keydown or keyup if Numlock is on and Shift is down; // e.g. to translate Shift+Numpad1 to unshifted-NumpadEnd. // - For Shift-down prior to a non-Numpad keydown if a Numpad key is still held down // after the above; e.g. for Shift+Numpad1+Esc. // - For LCtrl generated by AltGr. // Note that the system uses the normal scan codes (0x2A or 0x36) for Shift-down following // the Numpad keyup if no other keys were pushed. Our hook filters out the second byte to // simplify the code, so these values can only be found in KBDLLHOOKSTRUCT::scanCode. // Find "fake shift-key events" for older and more detailed comments. // Note that 0x0200 corresponds to SCANCODE_SIMULATED in kbd.h (DDK). #define SC_FAKE_FLAG 0x200 #define SC_FAKE_LSHIFT 0x22A #define SC_FAKE_RSHIFT 0x236 // This is the actual scancode received by the hook, excluding the 0x100 we add for "extended" keys. // Testing with the KbdEdit Demo preview mode indicates that AltGr will send this SC // even if the VK assigned to 0x1D is changed. It is a combination of SCANCODE_CTRL // and SCANCODE_SIMULATED, which are defined in kbd.h (Windows DDK). #define SC_FAKE_LCTRL 0x21D // UPDATE for v1.0.39: Changed sc_type to USHORT vs. UINT to save memory in structs such as sc_hotkey. // This saves 60K of memory in one place, and possibly there are other large savings too. // The following older comment dates back to 2003/inception and I don't remember its exact intent, // but there is no current storage of mouse message constants in scan code variables: // OLD: Although only need 9 bits for compressed and 16 for uncompressed scan code, use a full 32 bits // so that mouse messages (WPARAM) can be stored as scan codes. Formerly USHORT (which is always 16-bit). typedef USHORT sc_type; // Scan code. typedef UCHAR vk_type; // Virtual key. typedef UINT mod_type; // Standard Windows modifier type for storing MOD_CONTROL, MOD_WIN, MOD_ALT, MOD_SHIFT. // The maximum number of virtual keys and scan codes that can ever exist. // As of WinXP, these are absolute limits, except for scan codes for which there might conceivably // be more if any non-standard keyboard or keyboard drivers generate scan codes that don't start // with either 0x00 or 0xE0. UPDATE: Decided to allow all possible scancodes, rather than just 512, // since a lookup array for the 16-bit scan code value will only consume 64K of RAM if the element // size is one char. UPDATE: decided to go back to 512 scan codes, because WinAPI's KeyboardProc() // itself can only handle that many (a 9-bit value). 254 is the largest valid vk, according to the // WinAPI docs (I think 255 is value that is sometimes returned to indicate an invalid vk). But // just in case something ever tries to access such arrays using the largest 8-bit value (255), add // 1 to make it 0xFF, thus ensuring array indexes will always be in-bounds if they are 8-bit values. #define VK_MAX 0xFF #define SC_MAX 0x1FF typedef UCHAR modLR_type; // Only the left-right win/alt/ctrl/shift rather than their generic counterparts. #define MODLR_MAX 0xFF #define MODLR_COUNT 8 #define MOD_LCONTROL 0x01 #define MOD_RCONTROL 0x02 #define MOD_LALT 0x04 #define MOD_RALT 0x08 #define MOD_LSHIFT 0x10 #define MOD_RSHIFT 0x20 #define MOD_LWIN 0x40 #define MOD_RWIN 0x80 #define MODLR_LMASK (MOD_LCONTROL | MOD_LALT | MOD_LSHIFT | MOD_LWIN) #define MODLR_RMASK (MOD_RCONTROL | MOD_RALT | MOD_RSHIFT | MOD_RWIN) #define MODLR_MASK (MODLR_LMASK | MODLR_RMASK) #define MODLR_STRING _T("<^>^<!>!<+>+<#>#") struct CachedLayoutType { HKL hkl; ResultType has_altgr; }; struct key_to_vk_type // Map key names to virtual keys. { LPTSTR key_name; vk_type vk; }; struct key_to_sc_type // Map key names to scan codes. { LPTSTR key_name; sc_type sc; }; enum KeyStateTypes {KEYSTATE_LOGICAL, KEYSTATE_PHYSICAL, KEYSTATE_TOGGLE}; // For use with GetKeyJoyState(), etc. enum KeyEventTypes {KEYDOWN, KEYUP, KEYDOWNANDUP}; void SendKeys(LPCTSTR aKeys, SendRawModes aSendRaw, SendModes aSendModeOrig, HWND aTargetWindow = NULL); void SendKey(vk_type aVK, sc_type aSC, modLR_type aModifiersLR, modLR_type aModifiersLRPersistent , int aRepeatCount, KeyEventTypes aEventType, modLR_type aKeyAsModifiersLR, HWND aTargetWindow , int aX = COORD_UNSPECIFIED, int aY = COORD_UNSPECIFIED, bool aMoveOffset = false); void SendKeySpecial(TCHAR aChar, int aRepeatCount, modLR_type aModifiersLR); void SendASC(LPCTSTR aAscii); struct PlaybackEvent { UINT message; union { struct { sc_type sc; // Placed above vk for possibly better member stacking/alignment. vk_type vk; }; struct { // Screen coordinates, which can be negative. SHORT vs. INT is used because the likelihood // have having a virtual display surface wider or taller than 32,767 seems too remote to // justify increasing the struct size, which would impact the stack space and dynamic memory // used by every script every time it uses the playback method to send keystrokes or clicks. // Note: WM_LBUTTONDOWN uses WORDs vs. SHORTs, but they're not really comparable because // journal playback/record both use screen coordinates but WM_LBUTTONDOWN et. al. use client // coordinates. SHORT x; SHORT y; }; DWORD time_to_wait; // This member is present only when message==0; otherwise, a struct is present. }; }; LRESULT CALLBACK PlaybackProc(int aCode, WPARAM wParam, LPARAM lParam); // Below uses a pseudo-random value. It's best that this be constant so that if multiple instances // of the app are running, they will all ignore each other's keyboard & mouse events. Also, a value // close to UINT_MAX might be a little better since it's might be less likely to be used as a pointer // value by any apps that send keybd events whose ExtraInfo is really a pointer value. #define KEY_IGNORE 0xFFC3D44F #define KEY_PHYS_IGNORE (KEY_IGNORE - 1) // Same as above but marked as physical for other instances of the hook. #define KEY_IGNORE_ALL_EXCEPT_MODIFIER (KEY_IGNORE - 2) // Non-physical and ignored only if it's not a modifier. // Same as KEY_IGNORE_ALL_EXCEPT_MODIFIER, but only ignored by Hotkeys & Hotstrings at InputLevel LEVEL and below. // The levels are set up to use negative offsets from KEY_IGNORE_ALL_EXCEPT_MODIFIER so that we can leave // the values above unchanged and have KEY_IGNORE_LEVEL(0) == KEY_IGNORE_ALL_EXCEPT_MODIFIER. // // In general, KEY_IGNORE_LEVEL(g->SendLevel) should be used for any input that's meant to be treated as "real", // as opposed to input generated for side effects (e.g., masking modifier keys to prevent default OS responses). // A lot of the calls that generate input fall into the latter category, so KEY_IGNORE_ALL_EXCEPT_MODIFIER // (aka KEY_IGNORE_LEVEL(0)) still gets used quite often. // // Note that there are no "level" equivalents for KEY_IGNORE or KEY_PHYS_IGNORE (only KEY_IGNORE_ALL_EXCEPT_MODIFIER). // For the KEY_IGNORE_LEVEL use cases, there isn't a need to ignore modifiers or differentiate between physical // and non-physical, and leaving them out keeps the code much simpler. #define KEY_IGNORE_LEVEL(LEVEL) (KEY_IGNORE_ALL_EXCEPT_MODIFIER - LEVEL) #define KEY_IGNORE_MIN KEY_IGNORE_LEVEL(SendLevelMax) #define KEY_IGNORE_MAX KEY_IGNORE // There are two extra values above KEY_IGNORE_LEVEL(0) // This is used to generate an Alt key-up event for the purpose of changing system state, but having the hook // block it from the active window to avoid unwanted side-effects: #define KEY_BLOCK_THIS (KEY_IGNORE + 1) // The default in the below is KEY_IGNORE_ALL_EXCEPT_MODIFIER, which causes standard calls to // KeyEvent() to update g_modifiersLR_logical_non_ignored the same way it updates g_modifiersLR_logical. // This is done because only the Send command has a realistic chance of interfering with (or being // interfered with by) hook hotkeys (namely the modifiers used to decide whether to trigger them). // There are two types of problems: // 1) Hotkeys not firing due to Send having temporarily released one of that hotkey's modifiers that // the user is still holding down. This causes the hotkey's suffix to flow through to the system, // which is usually undesirable. This happens when the user is holding down a hotkey to auto-repeat // it, and perhaps other times. // 2) The wrong hotkey firing because Send has temporarily put a modifier into effect and (once again) // the user is holding down the hotkey to auto-repeat it. If the Send's temp-down modifier happens // to make the hotkey suffix match a different set of modifiers, the wrong hotkey would fire. void KeyEvent(KeyEventTypes aEventType, vk_type aVK, sc_type aSC = 0, HWND aTargetWindow = NULL , bool aDoKeyDelay = false, DWORD aExtraInfo = KEY_IGNORE_ALL_EXCEPT_MODIFIER); void KeyEventMenuMask(KeyEventTypes aEventType, DWORD aExtraInfo = KEY_IGNORE_ALL_EXCEPT_MODIFIER); ResultType PerformClick(LPTSTR aOptions); void ParseClickOptions(LPTSTR aOptions, int &aX, int &aY, vk_type &aVK, KeyEventTypes &aEventType , int &aRepeatCount, bool &aMoveOffset); FResult PerformMouse(ActionTypeType aActionType, optl<StrArg> aButton , optl<int> aX1, optl<int> aY1, optl<int> aX2, optl<int> aY2 , optl<int> aSpeed, optl<StrArg> aOffsetMode, optl<int> aRepeatCount, optl<StrArg> aDownUp); void PerformMouseCommon(ActionTypeType aActionType, vk_type aVK, int aX1, int aY1, int aX2, int aY2 , int aRepeatCount, KeyEventTypes aEventType, int aSpeed, bool aMoveOffset); void MouseClickDrag(vk_type aVK // Which button. , int aX1, int aY1, int aX2, int aY2, int aSpeed, bool aMoveOffset); void MouseClick(vk_type aVK // Which button. , int aX, int aY, int aRepeatCount, int aSpeed, KeyEventTypes aEventType, bool aMoveOffset = false); void MouseMove(int &aX, int &aY, DWORD &aEventFlags, int aSpeed, bool aMoveOffset); void MouseEvent(DWORD aEventFlags, DWORD aData, DWORD aX = COORD_UNSPECIFIED, DWORD aY = COORD_UNSPECIFIED); #define MSG_OFFSET_MOUSE_MOVE 0x80000000 // Bitwise flag, should be near/at high-order bit to avoid overlap messages. void PutKeybdEventIntoArray(modLR_type aKeyAsModifiersLR, vk_type aVK, sc_type aSC, DWORD aEventFlags, DWORD aExtraInfo); void PutMouseEventIntoArray(DWORD aEventFlags, DWORD aData, DWORD aX, DWORD aY); ResultType ExpandEventArray(); void InitEventArray(void *aMem, UINT aMaxEvents, modLR_type aModifiersLR); void SendEventArray(int &aFinalKeyDelay, modLR_type aModsDuringSend); void CleanupEventArray(int aFinalKeyDelay); extern SendModes sSendMode; void DoKeyDelay(int aDelay = (sSendMode == SM_PLAY) ? g->KeyDelayPlay : g->KeyDelay); void DoMouseDelay(); void UpdateKeyEventHistory(bool aKeyUp, vk_type aVK, sc_type aSC); void SetKeyHistoryMax(int aMax); #define KEYEVENT_PHYS(event_type, vk, sc) KeyEvent(event_type, vk, sc, NULL, false, KEY_PHYS_IGNORE) ToggleValueType ToggleKeyState(vk_type aVK, ToggleValueType aToggleValue); FResult SetToggleState(vk_type aVK, ToggleValueType &ForceLock, optl<StrArg> aToggleText); #define STD_MODS_TO_DISGUISE (MOD_LALT|MOD_RALT|MOD_LWIN|MOD_RWIN) void SetModifierLRState(modLR_type aModifiersLRnew, modLR_type aModifiersLRnow, HWND aTargetWindow , bool aDisguiseDownWinAlt, bool aDisguiseUpWinAlt, DWORD aExtraInfo = KEY_IGNORE_ALL_EXCEPT_MODIFIER); modLR_type GetModifierLRState(bool aExplicitlyGet = false); #define IsKeyDown(vk) (GetKeyState(vk) & 0x8000) #define IsKeyDownAsync(vk) (GetAsyncKeyState(vk) & 0x8000) #define IsKeyToggledOn(vk) (GetKeyState(vk) & 0x01) void AdjustKeyState(BYTE aKeyState[], modLR_type aModifiersLR); modLR_type KeyToModifiersLR(vk_type aVK, sc_type aSC = 0, bool *pIsNeutral = NULL); modLR_type ConvertModifiers(mod_type aModifiers); mod_type ConvertModifiersLR(modLR_type aModifiersLR); LPTSTR ModifiersLRToText(modLR_type aModifiersLR, LPTSTR aBuf); DWORD GetFocusedCtrlThread(HWND *apControl = NULL, HWND aWindow = GetForegroundWindow()); HKL GetFocusedKeybdLayout(HWND aWindow = GetForegroundWindow()); bool ActiveWindowLayoutHasAltGr(); ResultType LayoutHasAltGr(HKL aLayout); //--------------------------------------------------------------------- LPTSTR SCtoKeyName(sc_type aSC, LPTSTR aBuf, int aBufSize, bool aUseFallback = true); LPTSTR VKtoKeyName(vk_type aVK, LPTSTR aBuf, int aBufSize, bool aUseFallback = true); TCHAR VKtoChar(vk_type aVK, HKL aKeybdLayout = NULL); sc_type TextToSC(LPCTSTR aText, bool *aSpecifiedByNumber = NULL); vk_type TextToVK(LPCTSTR aText, modLR_type *pModifiersLR = NULL, bool aExcludeThoseHandledByScanCode = false , bool aAllowExplicitVK = true, HKL aKeybdLayout = GetKeyboardLayout(0)); vk_type CharToVKAndModifiers(TCHAR aChar, modLR_type *pModifiersLR, HKL aKeybdLayout, bool aEnableAZFallback = true); bool TextToVKandSC(LPCTSTR aText, vk_type &aVK, sc_type &aSC, modLR_type *pModifiersLR = NULL, HKL aKeybdLayout = GetKeyboardLayout(0)); vk_type TextToSpecial(LPTSTR aText, size_t aTextLength, KeyEventTypes &aEventTypem, modLR_type &aModifiersLR , bool aUpdatePersistent); LPTSTR GetKeyName(vk_type aVK, sc_type aSC, LPTSTR aBuf, int aBufSize, LPTSTR aDefault = _T("not found")); sc_type vk_to_sc(vk_type aVK, bool aReturnSecondary = false); vk_type sc_to_vk(sc_type aSC); inline bool IsMouseVK(vk_type aVK) { return aVK >= VK_LBUTTON && aVK <= VK_XBUTTON2 && aVK != VK_CANCEL || aVK >= VK_NEW_MOUSE_FIRST && aVK <= VK_NEW_MOUSE_LAST; } void OurBlockInput(bool aEnable); #endif
18,144
C++
.h
326
54.230061
136
0.773326
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,138
defines.h
AutoHotkey_AutoHotkey/source/defines.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #ifndef defines_h #define defines_h // Disable silly performance warning about converting int to bool: // Unlike other typecasts from a larger type to a smaller, I'm 99% sure // that all compilers are supposed to do something special for bool, // not just truncate. Example: // bool x = 0xF0000000 // The above should give the value "true" to x, not false which is // what would happen if: // char x = 0xF0000000 // #ifdef _MSC_VER #pragma warning(disable:4800) #endif #include "ahkversion.h" #define AHK_WEBSITE "https://autohotkey.com" #ifdef AUTOHOTKEYSC #define SCRIPT_RESOURCE_NAME _T(">AUTOHOTKEY SCRIPT<") #else #define SCRIPT_RESOURCE_SPEC _T("*#1") #define SCRIPT_RESOURCE_NAME MAKEINTRESOURCE(1) #define SCRIPT_PRESOURCE_SPEC _T("*#2") #define SCRIPT_PRESOURCE_NAME MAKEINTRESOURCE(2) #endif // Window class names: Changing these may result in new versions not being able to detect any old instances // that may be running (such as the use of FindWindow() in WinMain()). It may also have other unwanted // effects, such as anything in the OS that relies on the class name that the user may have changed the // settings for, such as whether to hide the tray icon (though it probably doesn't use the class name // in that example). // MSDN: "Because window classes are process specific, window class names need to be unique only within // the same process. Also, because class names occupy space in the system's private atom table, you // should keep class name strings as short a possible: #define WINDOW_CLASS_MAIN _T("AutoHotkey") #define WINDOW_CLASS_GUI _T("AutoHotkeyGUI") // There's a section in Script::Edit() that relies on these all starting with "AutoHotkey". #define EXT_AUTOHOTKEY _T(".ahk") #define AHK_HELP_FILE _T("AutoHotkey.chm") // AutoIt2 supports lines up to 16384 characters long, and we want to be able to do so too // so that really long lines from aut2 scripts, such as a chain of IF commands, can be // brought in and parsed. In addition, it also allows continuation sections to be long. #define LINE_SIZE (16384 + 1) // +1 for terminator. Don't increase LINE_SIZE above 65535 without considering ArgStruct::length's type (WORD). // Maximum length of a Unicode file path, plus null-terminator. #define MAX_WIDE_PATH 32768 #ifdef UNICODE #define T_MAX_PATH MAX_WIDE_PATH #else #define T_MAX_PATH MAX_PATH #endif // The following avoid having to link to OLDNAMES.lib, but they probably don't // reduce code size at all. #define stricmp(str1, str2) _stricmp(str1, str2) #define strnicmp(str1, str2, size) _strnicmp(str1, str2, size) // Items that may be needed for VC++ 6.X: #ifndef VK_XBUTTON1 #define VK_XBUTTON1 0x05 /* NOT contiguous with L & RBUTTON */ #define VK_XBUTTON2 0x06 /* NOT contiguous with L & RBUTTON */ #define WM_NCXBUTTONDOWN 0x00AB #define WM_NCXBUTTONUP 0x00AC #define WM_NCXBUTTONDBLCLK 0x00AD #define GET_WHEEL_DELTA_WPARAM(wParam) ((short)HIWORD(wParam)) #define WM_XBUTTONDOWN 0x020B #define WM_XBUTTONUP 0x020C #define WM_XBUTTONDBLCLK 0x020D #define GET_KEYSTATE_WPARAM(wParam) (LOWORD(wParam)) #define GET_NCHITTEST_WPARAM(wParam) ((short)LOWORD(wParam)) #define GET_XBUTTON_WPARAM(wParam) (HIWORD(wParam)) /* XButton values are WORD flags */ #define XBUTTON1 0x0001 #define XBUTTON2 0x0002 #endif #ifndef HIMETRIC_INCH #define HIMETRIC_INCH 2540 #endif #define IS_32BIT(signed_value_64) (signed_value_64 >= INT_MIN && signed_value_64 <= INT_MAX) #define GET_BIT(buf,n) (((buf) & (1 << (n))) >> (n)) #define SET_BIT(buf,n,val) ((val) ? ((buf) |= (1<<(n))) : (buf &= ~(1<<(n)))) // FAIL = 0 to remind that FAIL should have the value zero instead of something arbitrary // because some callers may simply evaluate the return result as true or false // (and false is a failure): enum ResultType {FAIL = 0, OK, WARN = OK, CRITICAL_ERROR // Some things might rely on OK==1 (i.e. boolean "true") , CONDITION_TRUE, CONDITION_FALSE , LOOP_BREAK, LOOP_CONTINUE , EARLY_RETURN, EARLY_EXIT // EARLY_EXIT needs to be distinct from FAIL for ExitApp() and AutoExecSection(). , FAIL_OR_OK // For LineError/RuntimeError, error is continuable. }; typedef HRESULT FResult; enum ExcptModeType {EXCPTMODE_NONE = 0 //, EXCPTMODE_TRY = 1 // Currently unused: Try block present. , EXCPTMODE_CATCH = 2 // Exception will be suppressed or caught. , EXCPTMODE_DELETE = 4 // Unhandled exceptions will display ERR_ABORT_DELETE vs. ERR_ABORT. , EXCPTMODE_CAUGHT = 0x10 // An exception is already being handled within a CATCH, and is not shadowed by TRY. , EXCPTMODE_DEBUGGER = 0x20 // Debugger is evaluating a property and wants uncaught errors suppressed. }; #define SEND_MODES { _T("Event"), _T("Input"), _T("Play"), _T("InputThenPlay") } // Must match the enum below. enum SendModes {SM_EVENT, SM_INPUT, SM_PLAY, SM_INPUT_FALLBACK_TO_PLAY, SM_INVALID}; // SM_EVENT must be zero. // In above, SM_INPUT falls back to SM_EVENT when the SendInput mode would be defeated by the presence // of a keyboard/mouse hooks in another script (it does this because SendEvent is superior to a // crippled/interruptible SendInput due to SendEvent being able to dynamically adjust to changing // conditions [such as the user releasing a modifier key during the Send]). By contrast, // SM_INPUT_FALLBACK_TO_PLAY falls back to the SendPlay mode. SendInput has this extra fallback behavior // because it's likely to become the most popular sending method. enum SendRawModes {SCM_NOT_RAW = FALSE, SCM_RAW, SCM_RAW_TEXT}; typedef UCHAR SendRawType; enum ExitReasons {EXIT_CRITICAL = -2, EXIT_DESTROY = -1, EXIT_NONE = 0, EXIT_ERROR, EXIT_LOGOFF, EXIT_SHUTDOWN , EXIT_CLOSE, EXIT_MENU, EXIT_EXIT, EXIT_RELOAD, EXIT_SINGLEINSTANCE}; #define EXITREASON_MUST_EXIT(er) (static_cast<ExitReasons>(er) <= EXIT_DESTROY) enum WarnType {WARN_LOCAL_SAME_AS_GLOBAL, WARN_UNREACHABLE, WARN_VAR_UNSET, WARN_ALL, INVALID_WARN_TYPE}; #define WARN_TYPE_STRINGS _T("LocalSameAsGlobal"), _T("Unreachable"), _T("VarUnset"), _T("All") enum WarnMode {WARNMODE_OFF, WARNMODE_ON, WARNMODE_OUTPUTDEBUG, WARNMODE_MSGBOX, WARNMODE_STDOUT}; // WARNMODE_OFF must be zero. #define WARN_MODE_STRINGS _T("Off"), _T("On"), _T("OutputDebug"), _T("MsgBox"), _T("StdOut") enum SingleInstanceType {SINGLE_INSTANCE_OFF, SINGLE_INSTANCE_PROMPT, SINGLE_INSTANCE_REPLACE , SINGLE_INSTANCE_IGNORE }; // SINGLE_INSTANCE_OFF must be zero. enum MenuTypeType {MENU_TYPE_NONE, MENU_TYPE_POPUP, MENU_TYPE_BAR}; // NONE must be zero. // These are used for things that can be turned on, off, or left at a // neutral default value that is neither on nor off. INVALID must // be zero: enum ToggleValueType {TOGGLE_INVALID = 0, TOGGLED_ON, TOGGLED_OFF, ALWAYS_ON, ALWAYS_OFF, TOGGLE , NEUTRAL, TOGGLE_SEND, TOGGLE_MOUSE, TOGGLE_SENDANDMOUSE, TOGGLE_DEFAULT , TOGGLE_MOUSEMOVE, TOGGLE_MOUSEMOVEOFF}; // Some things (such as ListView sorting) rely on SCS_INSENSITIVE being zero. enum StringCaseSenseType {SCS_INSENSITIVE, SCS_SENSITIVE, SCS_INSENSITIVE_LOCALE, SCS_INSENSITIVE_LOGICAL, SCS_INVALID}; enum SymbolType // For use with ExpandExpression() and IsNumeric(). { // The sPrecedence array in ExpandExpression() must be kept in sync with any additions, removals, // or re-ordering of the below. When reordering or adding new symbols, take care not to break // the range checks in the various macros defined below. PURE_NOT_NUMERIC // Must be zero/false because callers rely on that. , PURE_INTEGER, PURE_FLOAT , SYM_STRING = PURE_NOT_NUMERIC, SYM_INTEGER = PURE_INTEGER, SYM_FLOAT = PURE_FLOAT // Specific operand types. #define IS_NUMERIC(symbol) ((symbol) == SYM_INTEGER || (symbol) == SYM_FLOAT) // Ordered for short-circuit performance. , SYM_MISSING // Only used in parameter lists. , SYM_VAR // An operand that is a variable's contents. , SYM_OBJECT // L31: Represents an IObject interface pointer. , SYM_DYNAMIC // A dynamic variable reference/double-deref. Also used in Object::Variant to identify dynamic properties. , SYM_SUPER // Special operand just for the "super" keyword. Should only ever appear as the target of SYM_FUNC with callsite->func == nullptr. #define SUPER_KEYWORD _T("Super") , SYM_OPERAND_END // Marks the symbol after the last operand. This value is used below. , SYM_BEGIN = SYM_OPERAND_END // SYM_BEGIN is a special marker to simplify the code. #define IS_OPERAND(symbol) ((symbol) < SYM_OPERAND_END) , SYM_POST_INCREMENT, SYM_POST_DECREMENT // Kept in this position for use by YIELDS_AN_OPERAND() [helps performance]. , SYM_MAYBE #define IS_POSTFIX_OPERATOR(symbol) ((symbol) <= SYM_MAYBE && (symbol) >= SYM_POST_INCREMENT) , SYM_DOT // DOT must precede SYM_OPAREN so YIELDS_AN_OPERAND(SYM_DOT) to get the right result (TRUE), since its RHS operand is embedded in the operator itself. , SYM_CPAREN, SYM_CBRACKET, SYM_CBRACE, SYM_OPAREN, SYM_OBRACKET, SYM_OBRACE, SYM_COMMA // CPAREN (close-paren)/CBRACKET/CBRACE must come right before OPAREN for YIELDS_AN_OPERAND. #define IS_OPAREN_LIKE(symbol) ((symbol) <= SYM_OBRACE && (symbol) >= SYM_OPAREN) #define IS_CPAREN_LIKE(symbol) ((symbol) <= SYM_CBRACE && (symbol) >= SYM_CPAREN) #define IS_OPAREN_MATCHING_CPAREN(sym_oparen, sym_cparen) ((sym_oparen - sym_cparen) == (SYM_OPAREN - SYM_CPAREN)) // Requires that (IS_OPAREN_LIKE(sym_oparen) || IS_CPAREN_LIKE(sym_cparen)) is true. #define SYM_CPAREN_FOR_OPAREN(symbol) ((symbol) - (SYM_OPAREN - SYM_CPAREN)) // Caller must confirm it is OPAREN or OBRACKET. #define SYM_OPAREN_FOR_CPAREN(symbol) ((symbol) + (SYM_OPAREN - SYM_CPAREN)) // Caller must confirm it is CPAREN or CBRACKET. #define YIELDS_AN_OPERAND(symbol) ((symbol) < SYM_OPAREN) // CPAREN also covers the tail end of a function call. Post-inc/dec yields an operand for things like Var++ + 2. Definitely needs the parentheses around symbol. , SYM_ASSIGN, SYM_ASSIGN_ADD, SYM_ASSIGN_SUBTRACT, SYM_ASSIGN_MULTIPLY, SYM_ASSIGN_DIVIDE, SYM_ASSIGN_INTEGERDIVIDE , SYM_ASSIGN_BITOR, SYM_ASSIGN_BITXOR, SYM_ASSIGN_BITAND, SYM_ASSIGN_BITSHIFTLEFT, SYM_ASSIGN_BITSHIFTRIGHT, SYM_ASSIGN_BITSHIFTRIGHT_LOGICAL // SYM_ASSIGN_BITSHIFTLEFT_LOGICAL doesn't exist but <<<= is the same as <<= , SYM_ASSIGN_MAYBE , SYM_ASSIGN_CONCAT // THIS MUST BE KEPT AS THE LAST (AND SYM_ASSIGN THE FIRST) BECAUSE THEY'RE USED IN A RANGE-CHECK. #define IS_ASSIGNMENT_EXCEPT_POST_AND_PRE(symbol) (symbol <= SYM_ASSIGN_CONCAT && symbol >= SYM_ASSIGN) // Check upper bound first for short-circuit performance. #define IS_ASSIGNMENT_OR_POST_OP(symbol) (IS_ASSIGNMENT_EXCEPT_POST_AND_PRE(symbol) || symbol == SYM_POST_INCREMENT || symbol == SYM_POST_DECREMENT) , SYM_IFF_ELSE, SYM_IFF_THEN // THESE TERNARY OPERATORS MUST BE KEPT IN THIS ORDER AND ADJACENT TO THE BELOW. , SYM_OR_MAYBE, SYM_OR, SYM_AND // MUST BE KEPT IN THIS ORDER AND ADJACENT TO THE ABOVE for the range checks below. #define IS_SHORT_CIRCUIT_OPERATOR(symbol) ((symbol) <= SYM_AND && ((symbol) >= SYM_IFF_THEN || (symbol) == SYM_MAYBE)) // Excludes SYM_IFF_ELSE, which acts as a simple jump after the THEN branch is evaluated. #define SYM_USES_CIRCUIT_TOKEN(symbol) ((symbol) <= SYM_AND && ((symbol) >= SYM_IFF_ELSE || (symbol) == SYM_MAYBE)) #define SYM_MAYBE_IGNORES_ON_STACK(symbol) (SYM_USES_CIRCUIT_TOKEN(symbol) && (symbol) != SYM_IFF_THEN || (symbol) == SYM_ASSIGN) , SYM_IS , SYM_EQUAL, SYM_EQUALCASE, SYM_NOTEQUAL, SYM_NOTEQUALCASE // =, ==, !=, !==... Keep this in sync with IS_RELATIONAL_OPERATOR() below. #define IS_EQUALITY_OPERATOR(symbol) (symbol >= SYM_EQUAL && symbol <= SYM_NOTEQUALCASE) , SYM_GT, SYM_LT, SYM_GTOE, SYM_LTOE // >, <, >=, <= ... Keep this in sync with IS_RELATIONAL_OPERATOR() below. #define IS_RELATIONAL_OPERATOR(symbol) (symbol >= SYM_EQUAL && symbol <= SYM_LTOE) , SYM_REGEXMATCH // ~=, equivalent to a RegExMatch call in two-parameter mode. , SYM_CONCAT , SYM_LOW_CONCAT // Zero-precedence concat, used so that "x%y=z%" is equivalent to "x%(y=z)%". // INTEGER OPERATORS START // Note that the below macro does not consider SYM_BITNOT or the bit-assignment operators. , SYM_BITOR // Seems more intuitive to have these higher in prec. than the above, unlike C and Perl, but like Python. , SYM_BITXOR // SYM_BITOR (ABOVE) MUST BE KEPT FIRST AMONG THE INTEGER OPERATORS BECAUSE IT'S USED IN A RANGE-CHECK (see IS_INTEGER_OPERATOR). , SYM_BITAND , SYM_BITSHIFTLEFT, SYM_BITSHIFTRIGHT, SYM_BITSHIFTRIGHT_LOGICAL // << >> >>>. <<< is the same as SYM_BITSHIFTLEFT , SYM_INTEGERDIVIDE // eg, x // y ALSO : SYM_INTEGERDIVIDE MUST BE KEPT LAST AMONG THE INTEGER OPERATORS BECAUSE IT'S USED IN A RANGE-CHECK (see IS_INTEGER_OPERATOR). #define IS_INTEGER_OPERATOR(symbol) ((symbol) <= SYM_INTEGERDIVIDE && (symbol) >= SYM_BITOR) // Currently not considered: SYM_BITNOT and the bit-assignment operators. // INTEGER OPERATORS END , SYM_ADD, SYM_SUBTRACT , SYM_MULTIPLY, SYM_DIVIDE , SYM_POWER , SYM_LOWNOT // LOWNOT is the word "not", the low precedence counterpart of ! , SYM_NEGATIVE, SYM_POSITIVE, SYM_REF, SYM_HIGHNOT, SYM_BITNOT // Don't change position or order of these because Infix-to-postfix converter's special handling for SYM_POWER relies on them being adjacent to each other. #define SYM_OVERRIDES_POWER_ON_STACK(symbol) ((symbol) >= SYM_LOWNOT && (symbol) <= SYM_BITNOT) // Check lower bound first for short-circuit performance. , SYM_ISSET , SYM_PRE_INCREMENT, SYM_PRE_DECREMENT // Must be kept after the post-ops and in this order relative to each other due to a range check in the code. #define SYM_INCREMENT_OR_DECREMENT_IS_PRE(symbol) ((symbol) >= SYM_PRE_INCREMENT) // Caller has verified symbol is an INCREMENT or DECREMENT operator. #define IS_PREFIX_OPERATOR(symbol) ((symbol) >= SYM_LOWNOT && (symbol) <= SYM_PRE_DECREMENT) , SYM_FUNC // A call to a function. , SYM_RESERVED_WORD, SYM_RESERVED_OPERATOR #define SYM_IS_RESERVED(symbol) ((symbol) >= SYM_RESERVED_WORD) // No need to exclude SYM_COUNT in this case. , SYM_COUNT // Must be last because it's the total symbol count for everything above. , SYM_INVALID = SYM_COUNT // Some callers may rely on YIELDS_AN_OPERAND(SYM_INVALID)==false. , SYM_TYPED_FIELD }; // This should include all operators which can produce SYM_VAR for a subsequent assignment: #define IS_OPERATOR_VALID_LVALUE(sym) \ (IS_ASSIGNMENT_EXCEPT_POST_AND_PRE(sym) \ || sym == SYM_PRE_INCREMENT || sym == SYM_PRE_DECREMENT) enum VarRefUsageType { VARREF_READ = 0, VARREF_ISSET, VARREF_READ_MAYBE , VARREF_REF, VARREF_LVALUE, VARREF_LVALUE_MAYBE, VARREF_LVALUE_ISSET, VARREF_OUTPUT_VAR }; #define VARREF_IS_WRITE(var_usage) ((var_usage) >= VARREF_REF) #define VARREF_IS_READ(var_usage) ((var_usage) == VARREF_READ || (var_usage) == VARREF_READ_MAYBE) // But not VARREF_ISSET. struct ExprTokenType; // Forward declarations for use below. struct ResultToken; struct IDebugProperties; class Object; // Must not be smaller than INT_PTR; see "(IntKeyType)(INT_PTR)". typedef __int64 IntKeyType; struct DECLSPEC_NOVTABLE IObject // L31: Abstract interface for "objects". : public IDispatch { #define IObject_Invoke_PARAMS_DECL \ ResultToken &aResultToken, int aFlags, LPTSTR aName, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount #define IObject_Invoke_PARAMS \ aResultToken, aFlags, aName, aThisToken, aParam, aParamCount virtual ResultType Invoke(IObject_Invoke_PARAMS_DECL) = 0; virtual LPTSTR Type() = 0; #define IObject_Type_Impl(name) \ LPTSTR Type() { return _T(name); } virtual Object *Base() = 0; virtual bool IsOfType(Object *aPrototype) = 0; }; struct DECLSPEC_NOVTABLE IObjectComCompatible : public IObject { STDMETHODIMP QueryInterface(REFIID riid, void **ppv); //STDMETHODIMP_(ULONG) AddRef() = 0; //STDMETHODIMP_(ULONG) Release() = 0; STDMETHODIMP GetTypeInfoCount(UINT *pctinfo); STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo **pptinfo); STDMETHODIMP GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); STDMETHODIMP Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); }; #ifdef CONFIG_DEBUGGER typedef void *DebugCookie; struct DECLSPEC_NOVTABLE IDebugProperties { // For simplicity/code size, the debugger handles failures internally // rather than returning an error code and requiring caller to handle it. virtual void WriteProperty(LPCSTR aName, ExprTokenType &aValue) = 0; virtual void WriteProperty(LPCWSTR aName, ExprTokenType &aValue) = 0; virtual void WriteProperty(ExprTokenType &aKey, ExprTokenType &aValue) = 0; virtual void WriteBaseProperty(IObject *aBase) = 0; virtual void WriteDynamicProperty(LPTSTR aName) = 0; virtual void WriteEnumItems(IObject *aEnumerable, int aStart, int aEnd) = 0; virtual void BeginProperty(LPCSTR aName, LPCSTR aType, int aNumChildren, DebugCookie &aCookie) = 0; virtual void EndProperty(DebugCookie aCookie) = 0; virtual ExprTokenType &ThisToken() = 0; }; #endif // Flags used when calling Invoke; also used by g_ObjGet etc.: #define IT_GET 0 #define IT_SET 1 #define IT_CALL 2 #define IT_BITMASK 3 // bit-mask for the above. #define BIMF_UNSET_ARG_1 8 // Flag used by BuiltInMethod. #define IF_BYPASS_METAFUNC 0x000010 // Skip invocation of meta-functions, such as when calling __Init or __Delete. #define IF_SUBSTITUTE_THIS 0x000020 // Target is a substitute object (i.e. ValueBase()), so refer to "aThisToken" instead of "this". #define IF_SUPER 0x000040 // super.something invocation. #define IF_NO_NEW_PROPS 0x000080 // Don't permit new properties. #define IF_NEWENUM 0x000200 // Workaround for COM objects which don't resolve "_NewEnum" to DISPID_NEWENUM. #define IF_BYPASS___VALUE 0x000400 #define EIF_VARIADIC 0x010000 #define EIF_STACK_MEMBER 0x020000 #define EIF_LEAVE_PARAMS 0x040000 #define EIF_UNSET_RETURN 0x100000 #define EIF_UNSET_PROP 0x200000 // Helper function for event handlers and __Delete: ResultType CallMethod(IObject *aInvokee, IObject *aThis, LPTSTR aMethodName , ExprTokenType *aParamValue = NULL, int aParamCount = 0, __int64 *aRetVal = NULL // For event handlers. , int aExtraFlags = 0 // For Object.__Delete(). , bool aReturnBoolean = false); struct DerefType; // Forward declarations for use below. struct CallSite; // class Var; // struct ExprTokenType // Something in the compiler hates the name TokenType, so using a different name. { // Due to the presence of 8-byte members (double and __int64) this entire struct is aligned on 8-byte // vs. 4-byte boundaries. The compiler defaults to this because otherwise an 8-byte member might // sometimes not start at an even address, which would hurt performance on Pentiums, etc. union // Which of its members is used depends on the value of symbol, below. { __int64 value_int64; // for SYM_INTEGER double value_double; // for SYM_FLOAT struct { union // These nested structs and unions minimize the token size by overlapping data. { IObject *object; CallSite *callsite; // for SYM_FUNC, and (while parsing) SYM_ASSIGN etc. DerefType *var_deref; // for SYM_VAR while parsing Var *var; // for SYM_VAR and SYM_DYNAMIC LPTSTR marker; // for SYM_STRING ExprTokenType *circuit_token; // for short-circuit operators }; union // Due to the outermost union, this doesn't increase the total size of the struct on x86 builds (but it does on x64). { LPCTSTR error_reporting_marker; // Used by ExpressionToPostfix() for binary and unary operators. size_t marker_length; VarRefUsageType var_usage; // for SYM_DYNAMIC and SYM_VAR (at load time) }; }; }; SymbolType symbol; ExprTokenType() {} ExprTokenType(int aValue) { SetValue(aValue); } ExprTokenType(__int64 aValue) { SetValue(aValue); } ExprTokenType(double aValue) { SetValue(aValue); } ExprTokenType(IObject *aValue) { SetValue(aValue); } ExprTokenType(LPTSTR aValue, size_t aLength = -1) { SetValue(aValue, aLength); } void SetValue(__int64 aValue) { symbol = SYM_INTEGER; value_int64 = aValue; } void SetValue(int aValue) { SetValue((__int64)aValue); } void SetValue(UINT aValue) { SetValue((__int64)aValue); } void SetValue(UINT64 aValue) { SetValue((__int64)aValue); } void SetValue(double aValue) { symbol = SYM_FLOAT; value_double = aValue; } void SetValue(LPTSTR aValue, size_t aLength = -1) { ASSERT(aValue); symbol = SYM_STRING; marker = aValue; marker_length = aLength; } void SetValue(IObject *aValue) // Caller must AddRef() if appropriate. { ASSERT(aValue); symbol = SYM_OBJECT; object = aValue; } inline void CopyValueFrom(ExprTokenType &other) // Copies the value of a token (by reference where applicable). Does not object->AddRef(). { value_int64 = other.value_int64; // Union copy. #ifdef _WIN64 // For simplicity/smaller code size, don't bother checking symbol == SYM_STRING. marker_length = other.marker_length; // Already covered by the above on x86. #endif symbol = other.symbol; } inline void CopyExprFrom(ExprTokenType &other) // Copies all fields typically needed in a postfix expression. { return CopyValueFrom(other); // Currently nothing needs to be done differently. } void SetVarRef(Var *aVar) { symbol = SYM_VAR; var = aVar; var_usage = VARREF_REF; } // Assignments yield a variable using this function so that it can be passed ByRef, // and because in some cases it avoids an extra memory allocation or string copy // (that would otherwise be necessary to ensure the string value is not freed or // overwritten by a subsequent concat/function call while still on the stack). // Yielding SYM_VAR means subsequent assignments may affect it, but in a safer way // that doesn't risk dangling pointers. void SetVar(Var *aVar, VarRefUsageType aRefType = VARREF_READ) { symbol = SYM_VAR; var = aVar; var_usage = aRefType; } bool IsOptimizedOutputVar() { return symbol == SYM_VAR && !VARREF_IS_READ(var_usage); // VARREF_ISSET is tolerated for use by IsSet(). } private: // Force code to use one of the CopyFrom() methods, for clarity. ExprTokenType & operator = (ExprTokenType &other) { return *this; } }; #define STACK_PUSH(token_ptr) stack[stack_count++] = token_ptr #define STACK_POP stack[--stack_count] // To be used as the r-value for an assignment. class Object; class BuiltInFunc; struct ResultToken : public ExprTokenType { LPTSTR buf; // Points to a buffer of _f_retval_buf_size characters for returning short strings and misc purposes. LPTSTR mem_to_free; // Callee stores memory allocated for the result here. Must be NULL or equal to marker. #ifdef ENABLE_HALF_BAKED_NAMED_PARAMS IObject *named_params; // Variadic callers may pass named parameters via properties of this. #endif // Utility function for initializing result tokens. void InitResult(LPTSTR aResultBuf) { symbol = SYM_STRING; marker = _T(""); marker_length = -1; // Helps code size to do this here instead of in ReturnPtr(), which should be inlined. buf = aResultBuf; mem_to_free = nullptr; #ifdef ENABLE_HALF_BAKED_NAMED_PARAMS named_params = nullptr; #endif result = OK; } // Utility function for properly freeing a token's contents. void Free() { // If the token contains an object, release it. if (symbol == SYM_OBJECT) object->Release(); // If the token has memory allocated for it, free it. if (mem_to_free) free(mem_to_free); } void AcceptMem(LPTSTR aNewMem, size_t aLength) { symbol = SYM_STRING; marker = mem_to_free = aNewMem; marker_length = aLength; } LPTSTR Malloc(LPTSTR aValue, size_t aLength); ResultType Return(LPTSTR aValue, size_t aLength = -1); ResultType ReturnPtr(LPTSTR aValue) // Return a null-terminated string which is already in persistent memory. { ASSERT(aValue); symbol = SYM_STRING; marker = aValue; //marker_length is left at its default value, -1. Caller will call _tcslen(). return OK; } ResultType ReturnPtr(LPTSTR aValue, size_t aLength) // Return a string which is already in persistent memory. { SetValue(aValue, aLength); return OK; } ResultType Return(__int64 aValue) { SetValue(aValue); return OK; } ResultType Return(int aValue) { return Return((__int64)aValue); } ResultType Return(UINT aValue) { return Return((__int64)aValue); } ResultType Return(DWORD aValue) { return Return((__int64)aValue); } ResultType Return(UINT64 aValue) { return Return((__int64)aValue); } ResultType Return(double aValue) { SetValue(aValue); return OK; } ResultType Return(IObject *aValue) // Caller must AddRef() if appropriate and must not pass NULL. { symbol = SYM_OBJECT; object = aValue; return OK; } ResultType SetExitResult(ResultType aResult) { ASSERT(aResult == FAIL || aResult == EARLY_EXIT); return result = aResult; } ResultType SetResult(ResultType aResult) // See comments for 'result' below. { return result = aResult; } bool Exited() { return result == FAIL || result == EARLY_EXIT; } ResultType Result() { return result; } ResultType SoftFail() { symbol = SYM_MISSING; // Caller may rely on FAIL to unwind stack, but this->result is still OK. return FAIL; } ResultType HardFail() { return SetExitResult(FAIL); } // Handle the result of calling a global Error function. // If FAIL (abort thread), sets internal result to FAIL and returns FAIL. // If OK (continue thread), sets return value to "" and returns FAIL. ResultType Fail(ResultType aResultOfShowError) { return aResultOfShowError == OK ? SoftFail() : HardFail(); } ResultType Error(LPCTSTR aErrorText); ResultType Error(LPCTSTR aErrorText, LPCTSTR aExtraInfo); ResultType Error(LPCTSTR aErrorText, Object *aPrototype); ResultType Error(LPCTSTR aErrorText, LPCTSTR aExtraInfo, Object *aPrototype); ResultType Error(LPCTSTR aErrorText, ExprTokenType &aExtraInfo, Object *aPrototype); ResultType MemoryError(); ResultType UnknownMemberError(ExprTokenType &aObject, int aFlags, LPCTSTR aMember); ResultType Win32Error(DWORD aError = GetLastError()); ResultType ValueError(LPCTSTR aErrorText); ResultType ValueError(LPCTSTR aErrorText, LPCTSTR aExtraInfo); ResultType TypeError(LPCTSTR aExpectedType, ExprTokenType &aActualValue); ResultType ParamError(int aIndex, ExprTokenType *aParam); ResultType ParamError(int aIndex, ExprTokenType *aParam, LPCTSTR aExpectedType); ResultType ParamError(int aIndex, ExprTokenType *aParam, LPCTSTR aExpectedType, LPCTSTR aFunction); BuiltInFunc *func; // For maintainability, this is separate from the ExprTokenType union. Its main uses are func->mID and func->mOutputVars. private: // Currently can't be included in the value union because meta-functions // need the EARLY_RETURN result *and* return value passed back. However, // probably best to keep it separate for code size and maintainability. // Struct size is a non-issue since there is only one ResultToken per // function call on the stack. ResultType result; }; #define BIF_DECL_PARAMS ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount // The following macro is used for definitions and declarations of built-in functions: #define BIF_DECL(name) void name(BIF_DECL_PARAMS) typedef BIF_DECL((* BuiltInFunctionType)); // But the array that goes with these actions is in globaldata.cpp because // otherwise it would be a little cumbersome to declare the extern version // of the array in here (since it's only extern to modules other than // script.cpp): enum enum_act { // Seems best to make ACT_INVALID zero so that it will be the ZeroMemory() default within // any POD structures that contain an action_type field: ACT_INVALID = FAIL // These should both be zero for initialization and function-return-value purposes. , ACT_ASSIGNEXPR , ACT_EXPRESSION // Keep ACT_BLOCK_BEGIN as the first "control flow" action, for range checks with ACT_FIRST_CONTROL_FLOW: , ACT_BLOCK_BEGIN, ACT_BLOCK_END , ACT_HOTKEY_IF // Must be before ACT_FIRST_COMMAND. , ACT_EXIT // Used with AddLine(), but excluded from the "named" range below so that the function is preferred. // ================================================================================ // Named actions recognized by ConvertActionType: , ACT_STATIC, ACT_EXPORT, ACT_GLOBAL, ACT_LOCAL , ACT_IF , ACT_ELSE , ACT_LOOP, ACT_LOOP_FILE, ACT_LOOP_REG, ACT_LOOP_READ, ACT_LOOP_PARSE , ACT_FOR, ACT_WHILE, ACT_UNTIL // Keep LOOP, FOR, WHILE and UNTIL together and in this order for range checks in various places. , ACT_BREAK, ACT_CONTINUE // Keep ACT_FOR..ACT_CONTINUE together for ACT_EXPANDS_ITS_OWN_ARGS. , ACT_GOTO , ACT_RETURN , ACT_TRY, ACT_CATCH, ACT_FINALLY // Keep TRY, CATCH and FINALLY together and in this order for range checks. , ACT_SWITCH, ACT_CASE // Keep ACT_TRY..ACT_CASE together for ACT_EXPANDS_ITS_OWN_ARGS. // ================================================================================ // All others are not included in g_act, and are only used for misc. purposes: , ACT_MOUSEMOVE, ACT_MOUSECLICK, ACT_MOUSECLICKDRAG // Used by PerformMouse(). // ================================================================================ // Aliases used for range checks: , ACT_FIRST_NAMED_ACTION = ACT_STATIC, ACT_LAST_NAMED_ACTION = ACT_CASE , ACT_FIRST_JUMP = ACT_BREAK, ACT_LAST_JUMP = ACT_GOTO // Actions which accept a label name. }; #define ACT_IS_IF(ActionType) (ActionType == ACT_IF) #define ACT_IS_LOOP(ActionType) (ActionType >= ACT_LOOP && ActionType <= ACT_WHILE) #define ACT_IS_LOOP_EXCLUDING_WHILE(ActionType) (ActionType >= ACT_LOOP && ActionType <= ACT_FOR) #define ACT_IS_LINE_PARENT(ActionType) (ACT_IS_IF(ActionType) || ActionType == ACT_ELSE \ || ACT_IS_LOOP(ActionType) || (ActionType >= ACT_TRY && ActionType <= ACT_FINALLY) \ || ActionType == ACT_SWITCH) #define ACT_IS_VAR_DECL(ActionType) ((ActionType) <= ACT_LOCAL && (ActionType) >= ACT_STATIC) // The following groups of action types do not need ExpandArgs() called by ExecUntil(), // for one of the following reasons: 1) action has no args, 2) action's args are // always fully resolved at load time, 3) action is never executed by ExecUntil(), // 4) action needs to be the one to call ExpandArgs(), or does so for optimization. #define ACT_EXPANDS_ITS_OWN_ARGS(ActionType) (ActionType == ACT_ASSIGNEXPR \ || (ActionType >= ACT_FOR && ActionType <= ACT_CONTINUE) \ || (ActionType >= ACT_TRY && ActionType <= ACT_CASE)) // For convenience in many places. Must cast to int to avoid loss of negative values. #define BUF_SPACE_REMAINING ((int)(aBufSize - (aBuf - aBuf_orig))) // MsgBox timeout value. This can't be zero because that is used as a failure indicator: // Also, this define is in this file to prevent problems with mutual // dependency between script.h and window.h. Update: It can't be -1 either because // that value is used to indicate failure by DialogBox(): #define AHK_TIMEOUT -2 #define AHK_TOO_MANY_MSGBOXES -3 // And these to prevent mutual dependency problem between window.h and globaldata.h: #define MAX_MSGBOXES 7 // Probably best not to change this because it's used by OurTimers to set the timer IDs, which should probably be kept the same for backward compatibility. #define MAX_MSG_MONITORS 500 // IMPORTANT: Before ever changing the below, note that it will impact the IDs of menu items created // with the MENU command, as well as the number of such menu items that are possible (currently about // 65500-11000=54500). See comments at ID_USER_FIRST for details: #define GUI_CONTROL_BLOCK_SIZE 1000 #define MAX_CONTROLS_PER_GUI (GUI_CONTROL_BLOCK_SIZE * 11) // Some things rely on this being less than 0xFFFF and an even multiple of GUI_CONTROL_BLOCK_SIZE. #define NO_CONTROL_INDEX MAX_CONTROLS_PER_GUI // Must be 0xFFFF or less. #define NO_EVENT_INFO 0 // For backward compatibility with documented contents of A_EventInfo, this should be kept as 0 vs. something more special like UINT_MAX. #define MAX_TOOLTIPS 20 #define MAX_TOOLTIPS_STR _T("20") // Keep this in sync with above. #define MAX_FILEDIALOGS 4 #define MAX_FOLDERDIALOGS 4 #define MAX_NUMBER_LENGTH 255 // Large enough to allow custom zero or space-padding via %10.2f, etc. #define MAX_NUMBER_SIZE (MAX_NUMBER_LENGTH + 1) // But not too large because some things might rely on this being fairly small. #define MAX_INTEGER_LENGTH 20 // Max length of a 64-bit number when expressed as decimal or #define MAX_INTEGER_SIZE (MAX_INTEGER_LENGTH + 1) // hex string; e.g. -9223372036854775808 or (unsigned) 18446744073709551616 or (hex) -0xFFFFFFFFFFFFFFFF. #define VARLIST_INITIAL_SIZE 32 #define SW_NONE -1 // Hot-strings: // memmove() and proper detection of long hotstrings rely on buf being at least this large: #define HS_BUF_SIZE (MAX_HOTSTRING_LENGTH * 2 + 10) #define HS_BUF_DELETE_COUNT (HS_BUF_SIZE / 2) #define HS_MAX_END_CHARS 100 // Bitwise storage of boolean flags. This section is kept in this file because // of mutual dependency problems between hook.h and other header files: typedef UCHAR HookType; #define HOOK_KEYBD 0x01 #define HOOK_MOUSE 0x02 #define HOOK_FAIL 0xFF #define EXTERN_G extern global_struct *g #define EXTERN_OSVER extern OS_Version g_os #define EXTERN_CLIPBOARD extern Clipboard g_clip #define EXTERN_SCRIPT extern Script g_script #define CLIPBOARD_CONTAINS_ONLY_FILES (!IsClipboardFormatAvailable(CF_NATIVETEXT) && IsClipboardFormatAvailable(CF_HDROP)) // These macros used to keep app responsive during a long operation. In v1.0.39, the // hooks have a dedicated thread. However, mLastPeekTime is still compared to 5 rather // than some higher value for the following reasons: // 1) Want hotkeys pressed during a long operation to take effect as quickly as possible. // For example, in games a hotkey's response time is critical. // 2) Benchmarking shows less than a 0.5% performance improvement from this comparing // to a higher value (even one as high as 500), even when the system is under heavy // load from other processes). // // mLastPeekTime is global/static so that recursive functions, such as FileSetAttrib(), // will sleep as often as intended even if the target files require frequent recursion. // The use of a global/static is not friendly to recursive calls to the function (i.e. calls // made as a consequence of the current script subroutine being interrupted by another during // this instance's MsgSleep()). However, it doesn't seem to be that much of a consequence // since the exact interval/period of the MsgSleep()'s isn't that important. It's also // pretty unlikely that the interrupting subroutine will also just happen to call the same // function rather than some other. // // Older comment that applies if there is ever again no dedicated thread for the hooks: // These macros were greatly simplified when it was discovered that PeekMessage(), when called // directly as below, is enough to prevent keyboard and mouse lag when the hooks are installed #define LONG_OPERATION_INIT MSG msg; DWORD tick_now; // MsgSleep() is used rather than SLEEP_WITHOUT_INTERRUPTION to allow other hotkeys to // launch and interrupt (suspend) the operation. It seems best to allow that, since // the user may want to press some fast window activation hotkeys, for example, during // the operation. The operation will be resumed after the interrupting subroutine finishes. // Notes applying to the macro: // Store tick_now for use later, in case the Peek() isn't done, though not all callers need it later. // ... // Since the Peek() will yield when there are no messages, it will often take 20ms or more to return // (UPDATE: this can't be reproduced with simple tests, so either the OS has changed through service // packs, or Peek() yields only when the OS detects that the app is calling it too often or calling // it in certain ways [PM_REMOVE vs. PM_NOREMOVE seems to make no difference: either way it doesn't yield]). // Therefore, must update tick_now again (its value is used by macro and possibly by its caller) // to avoid having to Peek() immediately after the next iteration. // ... // The code might bench faster when "g_script.mLastPeekTime = tick_now" is a separate operation rather // than combined in a chained assignment statement. #define LONG_OPERATION_UPDATE \ {\ tick_now = GetTickCount();\ if (tick_now - g_script.mLastPeekTime > ::g->PeekFrequency)\ {\ if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))\ MsgSleep(-1);\ tick_now = GetTickCount();\ g_script.mLastPeekTime = tick_now;\ }\ } // Same as the above except for SendKeys() and related functions (uses SLEEP_WITHOUT_INTERRUPTION vs. MsgSleep). #define LONG_OPERATION_UPDATE_FOR_SENDKEYS \ {\ tick_now = GetTickCount();\ if (tick_now - g_script.mLastPeekTime > ::g->PeekFrequency)\ {\ if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))\ SLEEP_WITHOUT_INTERRUPTION(-1) \ tick_now = GetTickCount();\ g_script.mLastPeekTime = tick_now;\ }\ } // Defining these here avoids awkwardness due to the fact that globaldata.cpp // does not (for design reasons) include globaldata.h: typedef UCHAR ActionTypeType; // If ever have more than 256 actions, will have to change this (but it would increase code size due to static data in g_act). #pragma pack(push, 1) // v1.0.45: Reduces code size a little without impacting runtime performance because this struct is hardly ever accessed during runtime. struct Action { LPTSTR Name; // Changing these from ints to chars greatly reduced code size since this struct is used // by g_act to build static data into the code. Testing shows that the compiler will // generate a warning even when not in debug mode in the unlikely event that a constant // larger than 127 is ever stored in one of these: char MinParams, MaxParams; }; #pragma pack(pop) // Values are hard-coded for some of the below because they must not deviate from the documented, numerical // TitleMatchModes: enum TitleMatchModes {MATCHMODE_INVALID = FAIL, FIND_IN_LEADING_PART = 1, FIND_ANYWHERE = 2, FIND_EXACT = 3, FIND_REGEX, FIND_FAST, FIND_SLOW}; typedef UINT GuiIndexType; // Some things rely on it being unsigned to avoid the need to check for less-than-zero. typedef UINT GuiEventType; // Made a UINT vs. enum so that illegal/underflow/overflow values are easier to detect. // The following array and enum must be kept in sync with each other: #define GUI_EVENT_NAMES { _T("") \ , _T("DropFiles"), _T("Close"), _T("Escape"), _T("Size"), _T("ContextMenu") \ , _T("Change") \ , _T("Click"), _T("DoubleClick"), _T("ColClick") \ , _T("ItemCheck"), _T("ItemSelect"), _T("ItemFocus"), _T("ItemExpand") \ , _T("ItemEdit") \ , _T("Focus"), _T("LoseFocus") \ } enum GuiEventTypes {GUI_EVENT_NONE // NONE must be zero for any uses of ZeroMemory(), synonymous with false, etc. , GUI_EVENT_DROPFILES, GUI_EVENT_CLOSE, GUI_EVENT_ESCAPE, GUI_EVENT_RESIZE, GUI_EVENT_CONTEXTMENU , GUI_EVENT_WINDOW_FIRST = GUI_EVENT_DROPFILES, GUI_EVENT_WINDOW_LAST = GUI_EVENT_CONTEXTMENU , GUI_EVENT_CONTROL_FIRST , GUI_EVENT_CHANGE = GUI_EVENT_CONTROL_FIRST , GUI_EVENT_CLICK, GUI_EVENT_DBLCLK, GUI_EVENT_COLCLK , GUI_EVENT_ITEMCHECK, GUI_EVENT_ITEMSELECT, GUI_EVENT_ITEMFOCUS, GUI_EVENT_ITEMEXPAND , GUI_EVENT_ITEMEDIT , GUI_EVENT_FOCUS, GUI_EVENT_LOSEFOCUS , GUI_EVENT_NAMED_COUNT // The rest don't have explicit names in GUI_EVENT_NAMES: , GUI_EVENT_WM_COMMAND = GUI_EVENT_NAMED_COUNT }; enum GuiEventKinds {GUI_EVENTKIND_EVENT = 0, GUI_EVENTKIND_NOTIFY, GUI_EVENTKIND_COMMAND, GUI_EVENTKIND_MESSAGE}; typedef USHORT CoordModeType; #define COORD_MODE_INVALID ((CoordModeType) -1) // Bit-field offsets: #define COORD_MODE_PIXEL 0 #define COORD_MODE_MOUSE 2 #define COORD_MODE_TOOLTIP 4 #define COORD_MODE_CARET 6 #define COORD_MODE_MENU 8 #define COORD_MODE_CLIENT 0 #define COORD_MODE_WINDOW 1 #define COORD_MODE_SCREEN 2 #define COORD_MODE_MASK 3 #define COORD_MODES { _T("Client"), _T("Window"), _T("Screen") } #define COORD_CENTERED (INT_MIN + 1) #define COORD_UNSPECIFIED INT_MIN #define COORD_UNSPECIFIED_SHORT SHRT_MIN // This essentially makes coord -32768 "reserved", but it seems acceptable given usefulness and the rarity of a real coord like that. typedef UINT_PTR EventInfoType; typedef UCHAR SendLevelType; // Setting the max level to 100 is somewhat arbitrary. It seems that typical usage would only // require a few levels at most. We do want to keep the max somewhat small to keep the range // for magic values that get used in dwExtraInfo to a minimum, to avoid conflicts with other // apps that may be using the field in other ways. const SendLevelType SendLevelMax = 100; // Using int as the type for level so this can be used as validation before converting to SendLevelType. inline bool SendLevelIsValid(int level) { return level >= 0 && level <= SendLevelMax; } class Line; // Forward declaration. typedef UCHAR HotCriterionType; enum HotCriterionEnum {HOT_NO_CRITERION, HOT_IF_ACTIVE, HOT_IF_NOT_ACTIVE, HOT_IF_EXIST, HOT_IF_NOT_EXIST // HOT_NO_CRITERION must be zero. , HOT_IF_CALLBACK}; #define HOT_IF_REQUIRES_EVAL(type) ((type) == HOT_IF_CALLBACK) struct HotkeyCriterion { HotCriterionType Type; LPTSTR WinTitle, WinText; LPTSTR OriginalExpr; // For finding expr in #HotIf expr IObject *Callback; HotkeyCriterion *NextCriterion, *NextExpr; ResultType Eval(LPTSTR aHotkeyName); // For HOT_IF_CALLBACK. }; class Func; // Forward declarations class UserFunc; // class Label; // struct RegItemStruct; // struct LoopFilesStruct; // struct LoopReadFileStruct; // class GuiType; // class ScriptTimer; // struct ScriptThreadState { __int64 mLoopIteration; // Signed, since script/ITOA64 aren't designed to handle unsigned. LoopFilesStruct *mLoopFile; // The file of the current file-loop, if applicable. RegItemStruct *mLoopRegItem; // The registry subkey or value of the current registry enumeration loop. LoopReadFileStruct *mLoopReadFile; // The file whose contents are currently being read by a File-Read Loop. LPTSTR mLoopField; // The field of the current string-parsing loop. UserFunc *CurrentFunc; // v1.0.46.16: The function whose body is currently being processed at load-time, or being run at runtime (if any). ScriptTimer *CurrentTimer; // The timer that launched this thread (if any). HWND hWndLastUsed; // In many cases, it's better to use GetValidLastUsedWindow() when referring to this. EventInfoType EventInfo; HWND DialogHWND; // MsgBox being shown by this thread. HWND DialogOwner; // This thread's dialog owner, if any. #define THREAD_DIALOG_OWNER (IsWindow(::g->DialogOwner) ? ::g->DialogOwner : (::g->DialogOwner = NULL)) // Reset to NULL if invalid to mitigate the risk of errors due to HWND reuse by the OS. ResultToken* ThrownToken; int ExcptMode; DWORD LastError; // The result of GetLastError() after the most recent DllCall or Run. int Priority; // This thread's priority relative to others. int UninterruptedLineCount; // Stored as a g-struct attribute in case OnExit func interrupts it while uninterruptible. int UninterruptibleDuration; // Must be int to preserve negative values found in g_script.mUninterruptibleTime. DWORD ThreadStartTime; bool IsPaused; bool MsgBoxTimedOut; // Meaningful only while a MsgBox call is in progress. bool AllowThreadToBeInterrupted; // Whether this thread can be interrupted by custom menu items, hotkeys, or timers. Separate from g_AllowInterruption because that's for use by ongoing operations, such as SendKeys, and should override the thread's setting. }; struct ScriptThreadSettings { HotkeyCriterion *HotCriterion; DWORD PeekFrequency; // DWORD vs. UCHAR might improve performance a little since it's checked so often. TitleMatchModes TitleMatchMode; int WinDelay; // negative values may be used as special flags. int ControlDelay; // negative values may be used as special flags. int KeyDelay; // int KeyDelayPlay; // int PressDuration; // The delay between the up-event and down-event of each keystroke. int PressDurationPlay; // int MouseDelay; // negative values may be used as special flags. int MouseDelayPlay; // DWORD RegView; SendModes SendMode; UINT Encoding; CoordModeType CoordMode; // Bitwise collection of flags. // All these one-byte members are kept adjacent to make the struct smaller, which helps conserve stack space: bool TitleFindFast; // Whether to use the fast mode of searching window text, or the more thorough slow mode. bool DetectHiddenWindows; // Whether to detect the titles of hidden parent windows. bool DetectHiddenText; // Whether to detect the text of hidden child windows. bool AllowTimers; // v1.0.40.01 Whether new timer threads are allowed to start during this thread. bool ThreadIsCritical; // Whether this thread has been marked (un)interruptible by the "Critical" command. UCHAR DefaultMouseSpeed; bool StoreCapslockMode; SendLevelType SendLevel; bool ListLinesIsEnabled; //inline bool InTryBlock() { return ExcptMode & EXCPTMODE_TRY; } // Currently unused. bool DetectWindow(HWND aWnd); }; // global_struct is a combination of thread state (things specific to a thread that // are reset for each new thread and should not be affected by the default thread) // and thread settings (which are copied from the default thread). // Each instance of this struct generally corresponds to a quasi-thread. struct global_struct : public ScriptThreadState, public ScriptThreadSettings { }; inline void global_maximize_interruptibility(ScriptThreadState &g) { //g.AllowThreadToBeInterrupted = true; // Not necessary since its value isn't used when !g_nThreads. #define PRIORITY_MINIMUM INT_MIN g.Priority = PRIORITY_MINIMUM; // Ensure minimum priority so that it can always be interrupted. // The following can't be reset because their values (as set by the auto-execute section) are // used by new threads. Instead, interruption and timers are always permitted when !g_nThreads. //g.ThreadIsCritical = false; //g.AllowTimers = true; } inline void global_clear_state(ScriptThreadState &g) // Reset those values that represent the condition or state created by previously executed commands // but that shouldn't be retained for future threads (e.g. SetTitleMatchMode should be retained for // future threads if it occurs in the auto-execute section, but A_ThisFunc shouldn't). { ZeroMemory(&g, sizeof(g)); g.AllowThreadToBeInterrupted = true; // All of the following are handled by zero-initialization above: //g.CurrentFunc = NULL; //g.hWndLastUsed = NULL; //g.IsPaused = false; //g.Priority = 0; //g.UninterruptedLineCount = 0; //g.DialogHWND = NULL; //g.DialogOwner = NULL; //g.mLoopIteration = 0; // Zero seems preferable to 1, to indicate "no loop currently running" when a thread first starts off. This should probably be left unchanged for backward compatibility (even though script's aren't supposed to rely on it). //g.mLoopFile = NULL; //g.mLoopRegItem = NULL; //g.mLoopReadFile = NULL; //g.mLoopField = NULL; //g.ThrownToken = NULL; //g.ExcptMode = EXCPTMODE_NONE; //g.LastError = 0; //g.EventInfo = NO_EVENT_INFO; } inline void global_set_defaults(ScriptThreadSettings &g) { // Init struct with application defaults. They're in a struct so that it's easier // to save and restore their values when one hotkey interrupts another, going into // deeper recursion. When the interrupting subroutine returns, the former // subroutine's values for these are restored prior to resuming execution: g.HotCriterion = NULL; g.SendMode = SM_INPUT; g.TitleMatchMode = FIND_ANYWHERE; g.TitleFindFast = true; // Since it's so much faster in many cases. g.DetectHiddenWindows = false; // Same as AutoIt2 but unlike AutoIt3; seems like a more intuitive default. g.DetectHiddenText = true; // Unlike AutoIt, which defaults to false. This setting performs better. #define DEFAULT_PEEK_FREQUENCY 5 // Default peek frequency for an interruptible/non-critical thread. #define UNINTERRUPTIBLE_PEEK_FREQUENCY 16 // Used during a thread's uninterruptible period to ensure it has a chance to call Critical() before MsgSleep() is called. g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; // v1.0.46. See comments in Critical(). g.AllowTimers = true; g.ThreadIsCritical = false; g.WinDelay = 100; g.ControlDelay = 20; g.KeyDelay = 10; g.KeyDelayPlay = -1; g.PressDuration = -1; g.PressDurationPlay = -1; g.MouseDelay = 10; g.MouseDelayPlay = -1; #define DEFAULT_MOUSE_SPEED 2 #define MAX_MOUSE_SPEED 100 g.DefaultMouseSpeed = DEFAULT_MOUSE_SPEED; g.CoordMode = 0; // All the flags it contains are off by default. g.StoreCapslockMode = true; // AutoIt2 (and probably 3's) default, and it makes a lot of sense. g.SendLevel = 0; g.ListLinesIsEnabled = true; g.Encoding = CP_ACP; } // Initialize g and set application defaults. This is called only once, since new // threads get a copy of the current settings of the auto-execute thread (g_array[0]) // combined with a cleared state. inline void global_init(global_struct &g) { global_clear_state(g); global_set_defaults(g); } #ifdef UNICODE #define WINAPI_SUFFIX "W" #define PROCESS_API_SUFFIX "W" // used by Process32First and Process32Next #else #define WINAPI_SUFFIX "A" #define PROCESS_API_SUFFIX #endif #define _TSIZE(a) ((a)*sizeof(TCHAR)) #define CP_AHKNOBOM 0x80000000 #define CP_AHKCP (~CP_AHKNOBOM) #ifndef CP_UTF16 #define CP_UTF16 1200 #endif // Use #pragma message(MY_WARN(nnnn) "warning messages") to generate a warning like a compiler's warning #define __S(x) #x #define _S(x) __S(x) #define MY_WARN(n) __FILE__ "(" _S(__LINE__) ") : warning C" __S(n) ": " // These will be removed when things are done. #ifdef CONFIG_UNICODE_CHECK #define UNICODE_CHECK __declspec(deprecated(_T("Please check what you want are bytes or characters."))) UNICODE_CHECK inline size_t CHECK_SIZEOF(size_t n) { return n; } #define SIZEOF(c) CHECK_SIZEOF(sizeof(c)) #pragma deprecated(memcpy, memset, memmove, malloc, realloc, _alloca, alloca, toupper, tolower) #else #define UNICODE_CHECK #endif #endif
50,796
C++
.h
936
52.446581
258
0.748592
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,141
application.h
AutoHotkey_AutoHotkey/source/application.h
/* AutoHotkey Copyright 2003-2009 Chris Mallett (support@autohotkey.com) This program 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 2 of the License, or (at your option) any later version. This program 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. */ #ifndef application_h #define application_h #include "defines.h" // Callers should note that using INTERVAL_UNSPECIFIED might not rest the CPU at all if there is // already at least one msg waiting in our thread's msg queue: // Use some negative value unlikely to ever be passed explicitly: #define INTERVAL_UNSPECIFIED (INT_MIN + 303) #define NO_SLEEP -1 enum MessageMode {WAIT_FOR_MESSAGES, RETURN_AFTER_MESSAGES, RETURN_AFTER_MESSAGES_SPECIAL_FILTER}; bool MsgSleep(int aSleepDuration = INTERVAL_UNSPECIFIED, MessageMode aMode = RETURN_AFTER_MESSAGES); // This macro is used to Sleep without the possibility of a new hotkey subroutine being launched. // Timed subroutines will also be prevented from running while it is enabled. // It should be used when an operation needs to sleep, but doesn't want to be interrupted (suspended) // by any hotkeys the user might press during that time. Reasons why the caller wouldn't want to // be suspended: // 1) If it's doing something with a window -- such as sending keys or clicking the mouse or trying // to activate it -- that might get messed up if a new hotkey fires in the middle of the operation. // 2) If its a command that's still using some of its parameters that might reside in the deref buffer. // In this case, the launching of a new hotkey would likely overwrite those values, causing // unpredictable behavior. #define SLEEP_WITHOUT_INTERRUPTION(aSleepTime) \ {\ g_AllowInterruption = FALSE;\ MsgSleep(aSleepTime);\ g_AllowInterruption = TRUE;\ } // Have this be dynamically resolved each time. For example, when MsgSleep() uses this // while in mode WAIT_FOR_MESSSAGES, its msg loop should use this macro in case the // value of g_AllowInterruption changes from one iteration to the next. Thankfully, // MS made WM_HOTKEY have a very high value, so filtering in this way should not exclude // any other important types of messages: #define MSG_FILTER_MAX (IsInterruptible() ? 0 : WM_HOTKEY - 1) #define INTERRUPTIBLE_IN_EMERGENCY (g_AllowInterruption && !g_MenuIsVisible) #define DoWinDelay \ if (::g->WinDelay > -1)\ {\ MsgSleep(::g->WinDelay);\ } #define DoControlDelay \ if (g->ControlDelay > -1)\ {\ MsgSleep(g->ControlDelay);\ } ResultType IsCycleComplete(int aSleepDuration, DWORD aStartTime, bool aAllowEarlyReturn); // These should only be called from MsgSleep() (or something called by MsgSleep()) because // we don't want to be in the situation where a thread launched by CheckScriptTimers() returns // first to a dialog's message pump rather than MsgSleep's pump. That's because our thread // might then have queued messages that would be stuck in the queue (due to the possible absence // of the main timer) until the dialog's msg pump ended. bool CheckScriptTimers(); #define CHECK_SCRIPT_TIMERS_IF_NEEDED if (g_script.mTimerEnabledCount && CheckScriptTimers()) return_value = true; // Change the existing value only if it returned true. void PollJoysticks(); #define POLL_JOYSTICK_IF_NEEDED if (Hotkey::sJoyHotkeyCount) PollJoysticks(); bool MsgMonitor(HWND aWnd, UINT aMsg, WPARAM awParam, LPARAM alParam, MSG *apMsg, LRESULT &aMsgReply); void InitNewThread(int aPriority, bool aSkipUninterruptible, bool aIncrementThreadCountAndUpdateTrayIcon , bool aIsCritical = false); void ResumeUnderlyingThread(); BOOL IsInterruptible(); void MsgWaitUnpause(); VOID CALLBACK MsgBoxTimeout(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); VOID CALLBACK InputTimeout(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); VOID CALLBACK RefreshInterruptibility(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); void InitMenuPopup(HMENU aMenu); void UninitMenuPopup(HMENU aMenu); bool MenuIsModeless(HMENU aMenu); #endif
4,293
C++
.h
78
53.576923
169
0.788695
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,142
abi.h
AutoHotkey_AutoHotkey/source/abi.h
#pragma once #include "StrRet.h" // Marks functions which are called by script, for clarity and possible future use. #define bif_impl constexpr int FR_OUR_FLAG = 0x20000000; constexpr int FR_INT_FLAG = 0x40000000; constexpr int FR_FACILITY_CONTROL = 0; constexpr int FR_FACILITY_INT = 9; constexpr int FR_FACILITY_ARG = 0xA; constexpr int FR_FACILITY_ERR = 0xE; constexpr FResult FR_FAIL = FR_OUR_FLAG | MAKE_HRESULT(SEVERITY_ERROR, FR_FACILITY_CONTROL, 0); // Error already shown/thrown. constexpr FResult FR_ABORTED = FR_OUR_FLAG | MAKE_HRESULT(SEVERITY_SUCCESS, FR_FACILITY_CONTROL, 0); // Continuing after an error; return blank. constexpr FResult FR_E_WIN32 = FR_OUR_FLAG | MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0); // 0xA0070000 #define FR_E_WIN32(n) (FR_E_WIN32 | (n)) constexpr FResult FR_E_ARG_ZERO = FR_OUR_FLAG | MAKE_HRESULT(SEVERITY_ERROR, FR_FACILITY_ARG, 0); // 0xA00A0000 #define FR_E_ARG(n) (FR_E_ARG_ZERO | (n)) constexpr FResult FR_E_ARGS = FR_E_ARG(0xFFFF); #define FR_THROW_INT(n) ((n) & 0xF0000000 ? FR_E_FAILED \ : ((SEVERITY_ERROR << 31) | FR_OUR_FLAG | FR_INT_FLAG | (n))) // Throw an Error where Extra = an int in the range 0..0x0FFFFFFF. #define FR_GET_THROWN_INT(fr) ((fr) & 0x0FFFFFFF) constexpr int FR_ERR_BASE = FR_OUR_FLAG | MAKE_HRESULT(SEVERITY_ERROR, FR_FACILITY_ERR, 0); // 0xA00E0000 constexpr int FR_E_OUTOFMEM = FR_ERR_BASE | 1; constexpr int FR_E_FAILED = FR_ERR_BASE | 2; typedef LPCTSTR StrArg; template<typename T> class optl { const T *_value; public: optl(const T &&v) : _value {&v} {} optl(const T &v) : _value {&v} {} optl(T &v) : _value {&v} {} optl(nullptr_t) : _value {nullptr} {} bool has_value() { return _value != nullptr; } T operator* () { return *_value; } T value() { return *_value; } T value_or(T aDefault) { return _value ? *_value : aDefault; } }; template<> class optl<StrArg> { const StrArg _value; public: optl(StrArg v) : _value {v} {} bool has_value() { return _value != nullptr; } bool has_nonempty_value() { return _value && *_value; } bool is_blank() { return _value && !*_value; } bool is_blank_or_omitted() { return !has_nonempty_value(); } StrArg value() { ASSERT(_value); return _value; } StrArg value_or(StrArg aDefault) { return _value ? _value : aDefault; } StrArg value_or_null() { return _value; } StrArg value_or_empty() { return _value ? _value : _T(""); } }; template<> class optl<IObject *> { IObject *_value; public: optl(IObject *v) : _value {v} {} optl(nullptr_t) : _value {nullptr} {} bool has_value() { return _value != nullptr; } IObject *value() { return _value; } }; struct VariantParams { ExprTokenType **value; int count; };
2,664
C++
.h
65
39.369231
144
0.693349
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,143
MdFunc.h
AutoHotkey_AutoHotkey/source/MdFunc.h
#pragma once #include "script.h" #include "MdType.h" void TypedPtrToToken(MdType aType, void *aPtr, ExprTokenType &aToken); class MdFunc : public NativeFunc { void *mMcFunc; // Pointer to native function. Object *mPrototype; // Prototype object used for type checking; a non-null value implies mMcFunc is a member function. MdType *mArgType; // Sequence of native arg types and modifiers. MdType mRetType; // Type of native return value (not necessarily the script return value). UINT8 mMaxResultTokens; // Number of ResultTokens that might be allocated for conversions. UINT8 mArgSlots; // Number of DWORD_PTRs needed for the parameter list. bool mThisCall; public: MdFunc(LPCTSTR aName, void *aMcFunc, MdType aRetType, MdType *aArg, UINT aArgSize, Object *aPrototype = nullptr); bool Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount) override; bool ArgIsOutputVar(int aIndex) override; bool ArgIsOptional(int aIndex) override; };
973
C++
.h
19
49.315789
119
0.791139
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,146
config.h
AutoHotkey_AutoHotkey/source/config.h
#pragma once // This file defines some macros for compile-time configurations. // (Like many projects on *nix that using autotools.) #if defined(WIN32) && !defined(_WIN64) #define WIN32_PLATFORM #endif #ifdef _MSC_VER #if defined(WIN32_PLATFORM) || defined(_WIN64) #define ENABLE_DLLCALL #define ENABLE_REGISTERCALLBACK #endif #endif #if !defined(_MBCS) && !defined(_UNICODE) && !defined(UNICODE) // If not set in project settings... // L: Comment out the next line to enable UNICODE: //#define _MBCS #ifndef _MBCS #define _UNICODE #define UNICODE #endif #endif #ifndef AUTOHOTKEYSC // DBGp #define CONFIG_DEBUGGER #endif // Generates warnings to help we check whether the codes are ready to handle Unicode or not. //#define CONFIG_UNICODE_CHECK // This is now defined via Config.vcxproj if supported by the current platform toolset. //#ifndef _WIN64 //#define CONFIG_WIN2K //#endif
897
C++
.h
30
28.433333
99
0.770128
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,147
functions.h
AutoHotkey_AutoHotkey/source/lib/functions.h
#ifndef MD_WINTITLE_ARGS #define MD_WINTITLE_ARGS (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText) #define MD_CONTROL_ARGS (In, Variant, Control), MD_WINTITLE_ARGS #define MD_CONTROL_ARGS_OPT (In_Opt, Variant, Control), MD_WINTITLE_ARGS #endif md_func_x(BlockInput, ScriptBlockInput, FResult, (In, String, Mode)) #ifdef ENABLE_REGISTERCALLBACK md_func(CallbackCreate, (In, Object, Function), (In_Opt, String, Options), (In_Opt, Int32, ParamCount), (Ret, UIntPtr, RetVal)) md_func(CallbackFree, (In, UIntPtr, Callback)) #endif md_func_x(CaretGetPos, CaretGetPos, Bool32, (Out_Opt, Variant, X), (Out_Opt, Variant, Y)) md_func(ClipWait, (In_Opt, Float64, Timeout), (In_Opt, Int32, AnyType), (Ret, Bool32, RetVal)) md_func(ControlAddItem, (In, String, Value), MD_CONTROL_ARGS, (Ret, IntPtr, Index)) md_func(ControlChooseIndex, (In, IntPtr, Index), MD_CONTROL_ARGS) md_func(ControlChooseString, (In, String, Value), MD_CONTROL_ARGS, (Ret, IntPtr, Index)) md_func(ControlClick, (In_Opt, Variant, Control), (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, String, Button), (In_Opt, Int32, Count), (In_Opt, String, Options), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText)) md_func(ControlDeleteItem, (In, IntPtr, Index), MD_CONTROL_ARGS) md_func(ControlFindItem, (In, String, Item), MD_CONTROL_ARGS, (Ret, IntPtr, Index)) md_func(ControlFocus, MD_CONTROL_ARGS) md_func(ControlGetChecked, MD_CONTROL_ARGS, (Ret, Bool32, RetVal)) md_func(ControlGetChoice, MD_CONTROL_ARGS, (Ret, String, RetVal)) md_func(ControlGetClassNN, MD_CONTROL_ARGS, (Ret, String, ClassNN)) md_func(ControlGetEnabled, MD_CONTROL_ARGS, (Ret, Bool32, RetVal)) md_func(ControlGetExStyle, MD_CONTROL_ARGS, (Ret, UInt32, RetVal)) md_func(ControlGetFocus, MD_WINTITLE_ARGS, (Ret, UInt32, Hwnd)) md_func(ControlGetHwnd, MD_CONTROL_ARGS, (Ret, UInt32, Hwnd)) md_func(ControlGetIndex, MD_CONTROL_ARGS, (Ret, IntPtr, Index)) md_func(ControlGetItems, MD_CONTROL_ARGS, (Ret, Object, StringArray)) md_func(ControlGetPos, (Out_Opt, Int32, X), (Out_Opt, Int32, Y), (Out_Opt, Int32, Width), (Out_Opt, Int32, Height), MD_CONTROL_ARGS) md_func(ControlGetStyle, MD_CONTROL_ARGS, (Ret, UInt32, RetVal)) md_func(ControlGetText, MD_CONTROL_ARGS, (Ret, String, Text)) md_func(ControlGetVisible, MD_CONTROL_ARGS, (Ret, Bool32, RetVal)) md_func(ControlHide, MD_CONTROL_ARGS) md_func(ControlHideDropDown, MD_CONTROL_ARGS) md_func(ControlMove, (In_Opt, Int32, X), (In_Opt, Int32, Y), (In_Opt, Int32, Width), (In_Opt, Int32, Height), MD_CONTROL_ARGS) md_func(ControlSend, (In, String, Keys), MD_CONTROL_ARGS_OPT) md_func(ControlSendText, (In, String, Keys), MD_CONTROL_ARGS_OPT) md_func(ControlSetChecked, (In, Int32, Value), MD_CONTROL_ARGS) md_func(ControlSetEnabled, (In, Int32, Value), MD_CONTROL_ARGS) md_func(ControlSetExStyle, (In, String, Value), MD_CONTROL_ARGS) md_func(ControlSetStyle, (In, String, Value), MD_CONTROL_ARGS) md_func(ControlSetText, (In, String, NewText), MD_CONTROL_ARGS) md_func(ControlShow, MD_CONTROL_ARGS) md_func(ControlShowDropDown, MD_CONTROL_ARGS) md_func(CoordMode, (In, String, TargetType), (In_Opt, String, RelativeTo), (Ret, String, RetVal)) md_func_v(Critical, (In_Opt, String, OnOffNumber), (Ret, Int32, RetVal)) md_func(DateAdd, (In, String, DateTime), (In, Float64, Time), (In, String, TimeUnits), (Ret, String, RetVal)) md_func(DateDiff, (In, String, DateTime1), (In, String, DateTime2), (In, String, TimeUnits), (Ret, Int64, RetVal)) md_func_v(DetectHiddenText, (In, Bool32, Mode), (Ret, Bool32, RetVal)) md_func_v(DetectHiddenWindows, (In, Bool32, Mode), (Ret, Bool32, RetVal)) md_func(DirCopy, (In, String, Source), (In, String, Dest), (In_Opt, Int32, Overwrite)) md_func(DirCreate, (In, String, Path)) md_func(DirDelete, (In, String, Path), (In_Opt, Bool32, Recurse)) md_func_v(DirExist, (In, String, Pattern), (Ret, String, RetVal)) md_func(DirMove, (In, String, Source), (In, String, Dest), (In_Opt, String, Flag)) md_func(DirSelect, (In_Opt, String, StartingFolder), (In_Opt, Int32, Options), (In_Opt, String, Prompt), (Ret, String, RetVal)) md_func(Download, (In, String, URL), (In, String, Path)) md_func(DriveEject, (In_Opt, String, Drive)) md_func(DriveGetCapacity, (In, String, Path), (Ret, Int64, RetVal)) md_func(DriveGetFilesystem, (In, String, Drive), (Ret, String, RetVal)) md_func(DriveGetLabel, (In, String, Drive), (Ret, String, RetVal)) md_func(DriveGetList, (In_Opt, String, Type), (Ret, String, RetVal)) md_func(DriveGetSerial, (In, String, Drive), (Ret, Int64, RetVal)) md_func(DriveGetSpaceFree, (In, String, Path), (Ret, Int64, RetVal)) md_func(DriveGetStatus, (In, String, Path), (Ret, String, RetVal)) md_func(DriveGetStatusCD, (In_Opt, String, Drive), (Ret, String, RetVal)) md_func(DriveGetType, (In, String, Path), (Ret, String, RetVal)) md_func(DriveLock, (In, String, Drive)) md_func(DriveRetract, (In_Opt, String, Drive)) md_func(DriveSetLabel, (In, String, Drive), (In_Opt, String, Label)) md_func(DriveUnlock, (In, String, Drive)) md_func_v(Edit, (In_Opt, String, Filename)) md_func(EditGetCurrentCol, MD_CONTROL_ARGS, (Ret, UInt32, Index)) md_func(EditGetCurrentLine, MD_CONTROL_ARGS, (Ret, UIntPtr, Index)) md_func(EditGetLine, (In, IntPtr, Index), MD_CONTROL_ARGS, (Ret, String, RetVal)) md_func(EditGetLineCount, MD_CONTROL_ARGS, (Ret, UIntPtr, Index)) md_func(EditGetSelectedText, MD_CONTROL_ARGS, (Ret, String, RetVal)) md_func(EditPaste, (In, String, Value), MD_CONTROL_ARGS) md_func(EnvGet, (In, String, VarName), (Ret, String, RetVal)) md_func(EnvSet, (In, String, VarName), (In_Opt, String, Value)) md_func_x(Exit, Exit, ResultType, (In_Opt, Int32, ExitCode)) md_func_x(ExitApp, ExitApp, ResultType, (In_Opt, Int32, ExitCode)) md_func(FileAppend, (In, Variant, Value), (In_Opt, String, Path), (In_Opt, String, Options)) md_func(FileCopy, (In, String, Source), (In, String, Dest), (In_Opt, Int32, Overwrite)) md_func(FileCreateShortcut, (In, String, Target), (In, String, LinkFile), (In_Opt, String, WorkingDir), (In_Opt, String, Args), (In_Opt, String, Description), (In_Opt, String, IconFile), (In_Opt, String, ShortcutKey), (In_Opt, Int32, IconNumber), (In_Opt, Int32, RunState)) md_func(FileDelete, (In, String, Pattern)) md_func(FileEncoding, (In, String, Encoding), (Ret, Variant, RetVal)) md_func_v(FileExist, (In, String, Pattern), (Ret, String, RetVal)) md_func(FileGetAttrib, (In_Opt, String, Path), (Ret, String, RetVal)) md_func(FileGetShortcut, (In, String, LinkFile), (Out_Opt, String, Target), (Out_Opt, String, WorkingDir), (Out_Opt, String, Args), (Out_Opt, String, Description), (Out_Opt, String, IconFile), (Out_Opt, Variant, IconNum), (Out_Opt, Int32, RunState)) md_func(FileGetSize, (In_Opt, String, Path), (In_Opt, String, Units), (Ret, Int64, RetVal)) md_func(FileGetTime, (In_Opt, String, Path), (In_Opt, String, WhichTime), (Ret, String, RetVal)) md_func(FileGetVersion, (In_Opt, String, Path), (Ret, String, RetVal)) md_func(FileInstall, (In, String, Source), (In, String, Dest), (In_Opt, Int32, Overwrite)) md_func(FileMove, (In, String, Source), (In, String, Dest), (In_Opt, Int32, Overwrite)) md_func(FileRead, (In, String, Path), (In_Opt, String, Options), (Ret, Variant, RetVal)) md_func(FileRecycle, (In, String, Pattern)) md_func(FileRecycleEmpty, (In_Opt, String, Drive)) md_func(FileSelect, (In_Opt, String, Options), (In_Opt, String, RootDirFileName), (In_Opt, String, Title), (In_Opt, String, Filter), (Ret, Variant, RetVal)) md_func(FileSetAttrib, (In, String, Attributes), (In_Opt, String, Pattern), (In_Opt, String, Mode)) md_func(FileSetTime, (In_Opt, String, YYYYMMDD), (In_Opt, String, Pattern), (In_Opt, String, WhichTime), (In_Opt, String, Mode)) md_func_v(GetKeyName, (In, String, KeyName), (Ret, String, RetVal)) md_func_x(GetKeySC, GetKeySC, Int32, (In, String, KeyName)) md_func(GetKeyState, (In, String, KeyName), (In_Opt, String, Mode), (Ret, Variant, RetVal)) md_func_x(GetKeyVK, GetKeyVK, Int32, (In, String, KeyName)) md_func(GroupActivate, (In, String, GroupName), (In_Opt, String, Mode), (Ret, UInt32, RetVal)) md_func(GroupAdd, (In, String, GroupName), (In_Opt, String, WinTitle), (In_Opt, String, WinText), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText)) md_func(GroupClose, (In, String, GroupName), (In_Opt, String, Mode)) md_func(GroupDeactivate, (In, String, GroupName), (In_Opt, String, Mode)) md_func_v(GuiCtrlFromHwnd, (In, UInt32, Hwnd), (Ret, Object, Gui)) md_func_v(GuiFromHwnd, (In, UInt32, Hwnd), (In_Opt, Bool32, Recurse), (Ret, Object, Gui)) md_func(HotIf, (In_Opt, Variant, Criterion), (Ret, Variant, RetVal)) md_func(HotIfWinActive, (In_Opt, String, WinTitle), (In_Opt, String, WinText), (Ret, Variant, RetVal)) md_func(HotIfWinExist, (In_Opt, String, WinTitle), (In_Opt, String, WinText), (Ret, Variant, RetVal)) md_func(HotIfWinNotActive, (In_Opt, String, WinTitle), (In_Opt, String, WinText), (Ret, Variant, RetVal)) md_func(HotIfWinNotExist, (In_Opt, String, WinTitle), (In_Opt, String, WinText), (Ret, Variant, RetVal)) md_func_x(Hotkey, BIF_Hotkey, FResult, (In, String, KeyName), (In_Opt, Variant, Action), (In_Opt, String, Options)) md_func_x(Hotstring, BIF_Hotstring, FResult, (In, String, String), (In_Opt, Variant, Replacement), (In_Opt, String, OnOffToggle), (Ret, Variant, RetVal)) md_func(IL_Add, (In, UIntPtr, ImageList), (In, String, Filename), (In_Opt, Int32, IconNumber), (In_Opt, Bool32, ResizeNonIcon), (Ret, Int32, Index)) md_func_x(IL_Create, IL_Create, UIntPtr, (In_Opt, Int32, InitialCount), (In_Opt, Int32, GrowCount), (In_Opt, Bool32, LargeIcons)) md_func_x(IL_Destroy, IL_Destroy, Bool32, (In, UIntPtr, ImageList)) md_func(ImageSearch, (Out_Opt, Variant, X), (Out_Opt, Variant, Y), (In, Int32, X1), (In, Int32, Y1), (In, Int32, X2), (In, Int32, Y2), (In, String, Image), (Ret, Bool32, Found)) md_func(IniDelete, (In, String, Path), (In, String, Section), (In_Opt, String, Key)) md_func(IniRead, (In, String, Path), (In_Opt, String, Section), (In_Opt, String, Key), (In_Opt, String, Default), (Ret, String, RetVal)) md_func(IniWrite, (In, String, Value), (In, String, Path), (In, String, Section), (In_Opt, String, Key)) md_func(InputBox, (In_Opt, String, Prompt), (In_Opt, String, Title), (In_Opt, String, Options), (In_Opt, String, Default), (Ret, Object, RetVal)) md_func_v(InstallKeybdHook, (In_Opt, Bool32, Install), (In_Opt, Bool32, Force)) md_func_v(InstallMouseHook, (In_Opt, Bool32, Install), (In_Opt, Bool32, Force)) md_func_x(IsLabel, IsLabel, Bool32, (In, String, Name)) md_func(KeyHistory, (In_Opt, Int32, MaxEvents)) md_func(KeyWait, (In, String, KeyName), (In_Opt, String, Options), (Ret, Bool32, RetVal)) md_func_v(ListHotkeys, md_arg_none) md_func_v(ListLines, (In_Opt, Int32, Mode), (Ret, Int32, RetVal)) md_func_v(ListVars, md_arg_none) md_func(ListViewGetContent, (In_Opt, String, Options), MD_CONTROL_ARGS, (Ret, Variant, RetVal)) md_func(LoadPicture, (In, String, Filename), (In_Opt, String, Options), (Out_Opt, Int32, ImageType), (Ret, UIntPtr, Handle)) md_func_v(MenuFromHandle, (In, UIntPtr, Handle), (Ret, Object, Menu)) md_func(MenuSelect, (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In, String, Menu) , (In_Opt, String, SubMenu1), (In_Opt, String, SubMenu2), (In_Opt, String, SubMenu3), (In_Opt, String, SubMenu4), (In_Opt, String, SubMenu5), (In_Opt, String, SubMenu6) , (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText)) md_func(MonitorGet, (In_Opt, Int32, N), (Out_Opt, Int32, Left), (Out_Opt, Int32, Top), (Out_Opt, Int32, Right), (Out_Opt, Int32, Bottom), (Ret, Int32, RetVal)) md_func_x(MonitorGetCount, MonitorGetCount, Int32, md_arg_none) md_func(MonitorGetName, (In_Opt, Int32, N), (Ret, String, RetVal)) md_func_x(MonitorGetPrimary, MonitorGetPrimary, Int32, md_arg_none) md_func(MonitorGetWorkArea, (In_Opt, Int32, N), (Out_Opt, Int32, Left), (Out_Opt, Int32, Top), (Out_Opt, Int32, Right), (Out_Opt, Int32, Bottom), (Ret, Int32, RetVal)) md_func(MouseClick, (In_Opt, String, Button), (In_Opt, Int32, X), (In_Opt, Int32, Y), (In_Opt, Int32, ClickCount), (In_Opt, Int32, Speed), (In_Opt, String, DownOrUp), (In_Opt, String, Relative)) md_func(MouseClickDrag, (In_Opt, String, Button), (In_Opt, Int32, X1), (In_Opt, Int32, Y1), (In, Int32, X2), (In, Int32, Y2), (In_Opt, Int32, Speed), (In_Opt, String, Relative)) md_func(MouseGetPos, (Out_Opt, Int32, X), (Out_Opt, Int32, Y), (Out_Opt, Variant, Win), (Out_Opt, Variant, Control), (In_Opt, Int32, Flag)) md_func(MouseMove, (In, Int32, X), (In, Int32, Y), (In_Opt, Int32, Speed), (In_Opt, String, Relative)) md_func(MsgBox, (In_Opt, String, Text), (In_Opt, String, Title), (In_Opt, String, Options), (Ret, String, RetVal)) #ifdef ENABLE_OBJALLOCDATA md_func(ObjAllocData, (In, Object, Obj), (In, UIntPtr, Size)) md_func(ObjFreeData, (In, Object, Obj)) #endif md_func(ObjGetDataPtr, (In, Object, Obj), (Ret, UIntPtr, Ptr)) md_func(ObjGetDataSize, (In, Object, Obj), (Ret, UIntPtr, Size)) md_func(ObjSetDataPtr, (In, Object, Obj), (In, UIntPtr, Ptr)) md_func(OnClipboardChange, (In, Object, Function), (In_Opt, Int32, AddRemove)) md_func(OnError, (In, Object, Function), (In_Opt, Int32, AddRemove)) md_func(OnExit, (In, Object, Function), (In_Opt, Int32, AddRemove)) md_func(OnMessage, (In, UInt32, Number), (In, Object, Function), (In_Opt, Int32, MaxThreads)) md_func_v(OutputDebug, (In, String, Text)) md_func(Pause, (In_Opt, Int32, NewState)) md_func_v(Persistent, (In_Opt, Bool32, NewValue), (Ret, Bool32, OldValue)) md_func(PixelGetColor, (In, Int32, X), (In, Int32, Y), (In_Opt, String, Mode), (Ret, String, Color)) md_func(PixelSearch, (Ret, Bool32, Found), (Out_Opt, Variant, X), (Out_Opt, Variant, Y), (In, Int32, X1), (In, Int32, Y1), (In, Int32, X2), (In, Int32, Y2), (In, UInt32, Color), (In_Opt, Int32, Variation)) #undef PostMessage md_func_x(PostMessage, ScriptPostMessage, FResult, (In, UInt32, Msg), (In_Opt, Variant, wParam), (In_Opt, Variant, lParam), MD_CONTROL_ARGS_OPT) md_func(ProcessClose, (In, String, Process), (Ret, UInt32, ClosedPID)) md_func_x(ProcessExist, ProcessExist, UInt32, (In_Opt, String, Process)) md_func(ProcessGetName, (In_Opt, String, Process), (Ret, String, Name)) md_func_x(ProcessGetParent, ProcessGetParent, UInt32, (In_Opt, String, Process)) md_func(ProcessGetPath, (In_Opt, String, Process), (Ret, String, Path)) md_func(ProcessSetPriority, (In, String, Priority), (In_Opt, String, Process), (Ret, UInt32, FoundPID)) md_func(ProcessWait, (In, String, Process), (In_Opt, Float64, Timeout), (Ret, UInt32, FoundPID)) md_func(ProcessWaitClose, (In, String, Process), (In_Opt, Float64, Timeout), (Ret, UInt32, UnclosedPID)) md_func(RegExMatch, (In, Variant, Haystack), (In, String, Needle), (Out_Opt, Object, Match), (In_Opt, Int32, StartingPos), (Ret, Int32, FoundPos)) md_func(RegExReplace, (In, Variant, Haystack), (In, String, Needle), (In_Opt, Variant, Replacement), (Out_Opt, Int32, Count), (In_Opt, Int32, Limit), (In_Opt, Int32, StartingPos), (Ret, Variant, RetVal)) md_func(Reload, md_arg_none) md_func(Run, (In, String, Target), (In_Opt, String, WorkingDir), (In_Opt, String, Options), (Out_Opt, Variant, PID)) md_func_v(RunAs, (In_Opt, String, User), (In_Opt, String, Password), (In_Opt, String, Domain)) md_func_x(RunWait, RunWait, ResultType, (In, String, Target), (In_Opt, String, WorkingDir), (In_Opt, String, Options), (In_Opt, Object, PID), (Ret, Int32, ExitCode)) md_func_v(Send, (In, String, Keys)) md_func_v(SendEvent, (In, String, Keys)) md_func_v(SendInput, (In, String, Keys)) md_func(SendLevel, (In, Int32, Level), (Ret, Int32, RetVal)) #undef SendMessage md_func_x(SendMessage, ScriptSendMessage, FResult, (In, UInt32, Msg), (In_Opt, Variant, wParam), (In_Opt, Variant, lParam), MD_CONTROL_ARGS_OPT, (In_Opt, Int32, Timeout), (Ret, UIntPtr, RetVal)) md_func(SendMode, (In, String, Mode), (Ret, Variant, RetVal)) md_func_v(SendPlay, (In, String, Keys)) md_func_v(SendText, (In, String, Text)) md_func(SetCapsLockState, (In_Opt, String, State)) md_func(SetControlDelay, (In, Int32, Delay), (Ret, Int32, RetVal)) md_func(SetDefaultMouseSpeed, (In, Int32, Speed), (Ret, Int32, RetVal)) md_func(SetKeyDelay, (In_Opt, Int32, Delay), (In_Opt, Int32, Duration), (In_Opt, String, Mode)) md_func(SetMouseDelay, (In, Int32, Delay), (In_Opt, String, Mode), (Ret, Int32, RetVal)) md_func(SetNumLockState, (In_Opt, String, State)) md_func(SetRegView, (In, String, RegView), (Ret, Variant, RetVal)) md_func(SetScrollLockState, (In_Opt, String, State)) md_func_v(SetStoreCapsLockMode, (In, Bool32, Mode), (Ret, Bool32, RetVal)) md_func(SetTimer, (In_Opt, Object, Function), (In_Opt, Int64, Period), (In_Opt, Int32, Priority)) md_func(SetTitleMatchMode, (In, String, Mode), (Ret, Variant, RetVal)) md_func(SetWinDelay, (In, Int32, Delay), (Ret, Int32, RetVal)) md_func(SetWorkingDir, (In, String, Path)) md_func(Shutdown, (In, Int32, Flags)) md_func_x(Sleep, ScriptSleep, Void, (In, Int32, Delay)) md_func_v(SoundBeep, (In_Opt, Int32, Duration), (In_Opt, Int32, Frequency)) md_func(SoundPlay, (In, String, Path), (In_Opt, String, Wait)) md_func(SplitPath, (In, String, Path), (Out_Opt, String, Name), (Out_Opt, String, Dir), (Out_Opt, String, Ext), (Out_Opt, String, NameNoExt), (Out_Opt, String, Drive)) md_func(StatusBarGetText, (In_Opt, Int32, Part), MD_WINTITLE_ARGS, (Ret, String, RetVal)) md_func(StatusBarWait, (In_Opt, String, Text), (In_Opt, Float64, Timeout), (In_Opt, Int32, Part), (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, Int32, Interval), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText), (Ret, Bool32, RetVal)) md_func(StrReplace, (In, Variant, Haystack), (In, String, Needle), (In_Opt, String, ReplaceText), (In_Opt, Variant, CaseSense), (Out_Opt, UInt32, Count), (In_Opt, UInt32, Limit), (Ret, Variant, RetVal)) md_func(StrSplit, (In, String, String), (In_Opt, Variant, Delimiters), (In_Opt, String, OmitChars), (In_Opt, Int32, MaxParts), (Ret, Object, RetVal)) md_func(Suspend, (In_Opt, Int32, Mode)) md_func_x(SysGet, SysGet, Int32, (In, Int32, Index)) md_func(SysGetIPAddresses, (Ret, Object, RetVal)) md_func(Thread, (In, String, Command), (In_Opt, Int32, Value1), (In_Opt, Int32, Value2)) md_func(ToolTip, (In_Opt, String, Text), (In_Opt, Int32, X), (In_Opt, Int32, Y), (In_Opt, Int32, Index), (Ret, UInt32, Hwnd)) md_func(TraySetIcon, (In_Opt, String, File), (In_Opt, Int32, Number), (In_Opt, Bool32, Freeze)) md_func(TrayTip, (In_Opt, String, Text), (In_Opt, String, Title), (In_Opt, String, Options)) md_func(WinActivate, MD_WINTITLE_ARGS) md_func(WinActivateBottom, MD_WINTITLE_ARGS) md_func(WinClose, (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, Float64, WaitTime), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText)) md_func(WinGetAlwaysOnTop, MD_WINTITLE_ARGS, (Ret, Bool32, RetVal)) md_func(WinGetClass, MD_WINTITLE_ARGS, (Ret, String, Class)) md_func(WinGetClientPos, (Out_Opt, Int32, X), (Out_Opt, Int32, Y), (Out_Opt, Int32, Width), (Out_Opt, Int32, Height), MD_WINTITLE_ARGS) md_func(WinGetControls, MD_WINTITLE_ARGS, (Ret, Object, ClassNNArray)) md_func(WinGetControlsHwnd, MD_WINTITLE_ARGS, (Ret, Object, HwndArray)) md_func(WinGetCount, MD_WINTITLE_ARGS, (Ret, Int32, Count)) md_func(WinGetEnabled, MD_WINTITLE_ARGS, (Ret, Bool32, Enabled)) md_func(WinGetExStyle, MD_WINTITLE_ARGS, (Ret, UInt32, ExStyle)) md_func(WinGetID, MD_WINTITLE_ARGS, (Ret, UInt32, Hwnd)) md_func(WinGetIDLast, MD_WINTITLE_ARGS, (Ret, UInt32, Hwnd)) md_func(WinGetList, MD_WINTITLE_ARGS, (Ret, Object, HwndArray)) md_func(WinGetMinMax, MD_WINTITLE_ARGS, (Ret, Int32, RetVal)) md_func(WinGetPID, MD_WINTITLE_ARGS, (Ret, UInt32, PID)) md_func(WinGetPos, (Out_Opt, Int32, X), (Out_Opt, Int32, Y), (Out_Opt, Int32, Width), (Out_Opt, Int32, Height), MD_WINTITLE_ARGS) md_func(WinGetProcessName, MD_WINTITLE_ARGS, (Ret, String, Name)) md_func(WinGetProcessPath, MD_WINTITLE_ARGS, (Ret, String, Path)) md_func(WinGetStyle, MD_WINTITLE_ARGS, (Ret, UInt32, Style)) md_func(WinGetText, MD_WINTITLE_ARGS, (Ret, String, Title)) md_func(WinGetTitle, MD_WINTITLE_ARGS, (Ret, String, Title)) md_func(WinGetTransColor, MD_WINTITLE_ARGS, (Ret, String, Color)) md_func(WinGetTransparent, MD_WINTITLE_ARGS, (Ret, Variant, RetVal)) md_func(WinHide, MD_WINTITLE_ARGS) md_func(WinKill, (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, Float64, WaitTime), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText)) md_func(WinMaximize, MD_WINTITLE_ARGS) md_func(WinMinimize, MD_WINTITLE_ARGS) md_func_v(WinMinimizeAll, md_arg_none) md_func_v(WinMinimizeAllUndo, md_arg_none) md_func(WinMove, (In_Opt, Int32, X), (In_Opt, Int32, Y), (In_Opt, Int32, Width), (In_Opt, Int32, Height), MD_WINTITLE_ARGS) md_func(WinMoveBottom, MD_WINTITLE_ARGS) md_func(WinMoveTop, MD_WINTITLE_ARGS) md_func(WinRedraw, MD_WINTITLE_ARGS) md_func(WinRestore, MD_WINTITLE_ARGS) md_func(WinSetAlwaysOnTop, (In_Opt, Int32, Value), MD_WINTITLE_ARGS) md_func(WinSetEnabled, (In, Int32, Value), MD_WINTITLE_ARGS) md_func(WinSetExStyle, (In, String, Style), MD_WINTITLE_ARGS) md_func(WinSetRegion, (In_Opt, String, Options), MD_WINTITLE_ARGS) md_func(WinSetStyle, (In, String, Style), MD_WINTITLE_ARGS) md_func(WinSetTitle, (In, String, NewTitle), MD_WINTITLE_ARGS) md_func(WinSetTransColor, (In, Variant, Value), MD_WINTITLE_ARGS) md_func(WinSetTransparent, (In, String, Value), MD_WINTITLE_ARGS) md_func(WinShow, MD_WINTITLE_ARGS) md_func(WinWait, (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, Float64, Timeout), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText), (Ret, UInt32, Hwnd)) md_func(WinWaitActive, (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, Float64, Timeout), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText), (Ret, UInt32, Hwnd)) md_func(WinWaitClose, (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, Float64, Timeout), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText), (Ret, UInt32, RetVal)) md_func(WinWaitNotActive, (In_Opt, Variant, WinTitle), (In_Opt, String, WinText), (In_Opt, Float64, Timeout), (In_Opt, String, ExcludeTitle), (In_Opt, String, ExcludeText), (Ret, UInt32, RetVal))
22,224
C++
.h
286
76.409091
266
0.712888
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,148
resource.h
AutoHotkey_AutoHotkey/source/resources/resource.h
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by AutoHotkey.rc // #define VS_VERSION_INFO 1 #define IDS_PROJNAME 100 #define IDR_WMDMLOGGER 101 #define IDI_MAIN 159 #define IDI_FILETYPE 160 #define IDS_LOG_SEV_INFO 201 #define IDC_INPUTEDIT 201 #define IDS_LOG_SEV_WARN 202 #define IDR_MENU1 202 #define IDS_LOG_SEV_ERROR 203 #define IDS_LOG_DATETIME 204 #define IDC_INPUTPROMPT 204 #define IDS_LOG_SRCNAME 205 #define IDD_INPUTBOX 205 #define IDI_SUSPEND 206 #define IDI_PAUSE 207 #define IDI_PAUSE_SUSPEND 208 #define IDR_MENU_MAIN 211 #define IDR_ACCELERATOR1 212 #define IDS_DEF_LOGFILE 301 #define IDS_DEF_MAXSIZE 302 #define IDS_DEF_SHRINKTOSIZE 303 #define IDS_DEF_LOGENABLED 304 #define IDS_MUTEX_TIMEOUT 401 #define ID_FILE_RELOADSCRIPT 65400 #define ID_FILE_EDITSCRIPT 65401 #define ID_FILE_WINDOWSPY 65402 #define ID_FILE_PAUSE 65403 #define ID_FILE_SUSPEND 65404 #define ID_FILE_EXIT 65405 #define ID_VIEW_LINES 65406 #define ID_VIEW_VARIABLES 65407 #define ID_VIEW_HOTKEYS 65408 #define ID_VIEW_KEYHISTORY 65409 #define ID_VIEW_REFRESH 65410 #define ID_HELP_USERMANUAL 65411 #define ID_HELP_WEBSITE 65412 #define IDD_ERRORBOX 500 #define IDC_ERR_EDIT 501 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 236 #define _APS_NEXT_COMMAND_VALUE 65414 #define _APS_NEXT_CONTROL_VALUE 206 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif #ifdef _WIN64 #define AHK_BIT "64-bit" #else #define AHK_BIT "32-bit" #endif #define AHK_DESCRIPTION "AutoHotkey " AHK_BIT
2,262
C++
.h
59
37.186441
47
0.563098
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,149
ucp.h
AutoHotkey_AutoHotkey/source/lib_pcre/pcre/ucp.h
/************************************************* * Unicode Property Table handler * *************************************************/ #ifndef _UCP_H #define _UCP_H /* This file contains definitions of the property values that are returned by the UCD access macros. New values that are added for new releases of Unicode should always be at the end of each enum, for backwards compatibility. */ /* These are the general character categories. */ enum { ucp_C, /* Other */ ucp_L, /* Letter */ ucp_M, /* Mark */ ucp_N, /* Number */ ucp_P, /* Punctuation */ ucp_S, /* Symbol */ ucp_Z /* Separator */ }; /* These are the particular character types. */ enum { ucp_Cc, /* Control */ ucp_Cf, /* Format */ ucp_Cn, /* Unassigned */ ucp_Co, /* Private use */ ucp_Cs, /* Surrogate */ ucp_Ll, /* Lower case letter */ ucp_Lm, /* Modifier letter */ ucp_Lo, /* Other letter */ ucp_Lt, /* Title case letter */ ucp_Lu, /* Upper case letter */ ucp_Mc, /* Spacing mark */ ucp_Me, /* Enclosing mark */ ucp_Mn, /* Non-spacing mark */ ucp_Nd, /* Decimal number */ ucp_Nl, /* Letter number */ ucp_No, /* Other number */ ucp_Pc, /* Connector punctuation */ ucp_Pd, /* Dash punctuation */ ucp_Pe, /* Close punctuation */ ucp_Pf, /* Final punctuation */ ucp_Pi, /* Initial punctuation */ ucp_Po, /* Other punctuation */ ucp_Ps, /* Open punctuation */ ucp_Sc, /* Currency symbol */ ucp_Sk, /* Modifier symbol */ ucp_Sm, /* Mathematical symbol */ ucp_So, /* Other symbol */ ucp_Zl, /* Line separator */ ucp_Zp, /* Paragraph separator */ ucp_Zs /* Space separator */ }; /* These are the script identifications. */ enum { ucp_Arabic, ucp_Armenian, ucp_Bengali, ucp_Bopomofo, ucp_Braille, ucp_Buginese, ucp_Buhid, ucp_Canadian_Aboriginal, ucp_Cherokee, ucp_Common, ucp_Coptic, ucp_Cypriot, ucp_Cyrillic, ucp_Deseret, ucp_Devanagari, ucp_Ethiopic, ucp_Georgian, ucp_Glagolitic, ucp_Gothic, ucp_Greek, ucp_Gujarati, ucp_Gurmukhi, ucp_Han, ucp_Hangul, ucp_Hanunoo, ucp_Hebrew, ucp_Hiragana, ucp_Inherited, ucp_Kannada, ucp_Katakana, ucp_Kharoshthi, ucp_Khmer, ucp_Lao, ucp_Latin, ucp_Limbu, ucp_Linear_B, ucp_Malayalam, ucp_Mongolian, ucp_Myanmar, ucp_New_Tai_Lue, ucp_Ogham, ucp_Old_Italic, ucp_Old_Persian, ucp_Oriya, ucp_Osmanya, ucp_Runic, ucp_Shavian, ucp_Sinhala, ucp_Syloti_Nagri, ucp_Syriac, ucp_Tagalog, ucp_Tagbanwa, ucp_Tai_Le, ucp_Tamil, ucp_Telugu, ucp_Thaana, ucp_Thai, ucp_Tibetan, ucp_Tifinagh, ucp_Ugaritic, ucp_Yi, /* New for Unicode 5.0: */ ucp_Balinese, ucp_Cuneiform, ucp_Nko, ucp_Phags_Pa, ucp_Phoenician, /* New for Unicode 5.1: */ ucp_Carian, ucp_Cham, ucp_Kayah_Li, ucp_Lepcha, ucp_Lycian, ucp_Lydian, ucp_Ol_Chiki, ucp_Rejang, ucp_Saurashtra, ucp_Sundanese, ucp_Vai, /* New for Unicode 5.2: */ ucp_Avestan, ucp_Bamum, ucp_Egyptian_Hieroglyphs, ucp_Imperial_Aramaic, ucp_Inscriptional_Pahlavi, ucp_Inscriptional_Parthian, ucp_Javanese, ucp_Kaithi, ucp_Lisu, ucp_Meetei_Mayek, ucp_Old_South_Arabian, ucp_Old_Turkic, ucp_Samaritan, ucp_Tai_Tham, ucp_Tai_Viet, /* New for Unicode 6.0.0: */ ucp_Batak, ucp_Brahmi, ucp_Mandaic }; #endif /* End of ucp.h */
3,463
C++
.h
155
19.503226
77
0.623672
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
16,150
pcre.h
AutoHotkey_AutoHotkey/source/lib_pcre/pcre/pcre.h
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* This is the public header file for the PCRE library, to be #included by applications that call the PCRE functions. Copyright (c) 1997-2012 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ #ifndef _PCRE_H #define _PCRE_H /* The current PCRE version information. */ #define PCRE_MAJOR 8 #define PCRE_MINOR 30 #define PCRE_PRERELEASE #define PCRE_DATE 2012-02-04 /* When an application links to a PCRE DLL in Windows, the symbols that are imported have to be identified as such. When building PCRE, the appropriate export setting is defined in pcre_internal.h, which includes this file. So we don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. */ #if defined(_WIN32) && !defined(PCRE_STATIC) # ifndef PCRE_EXP_DECL # define PCRE_EXP_DECL extern __declspec(dllimport) # endif # ifdef __cplusplus # ifndef PCRECPP_EXP_DECL # define PCRECPP_EXP_DECL extern __declspec(dllimport) # endif # ifndef PCRECPP_EXP_DEFN # define PCRECPP_EXP_DEFN __declspec(dllimport) # endif # endif #endif /* By default, we use the standard "extern" declarations. */ #ifndef PCRE_EXP_DECL # ifdef __cplusplus # define PCRE_EXP_DECL extern "C" # else # define PCRE_EXP_DECL extern # endif #endif #ifdef __cplusplus # ifndef PCRECPP_EXP_DECL # define PCRECPP_EXP_DECL extern # endif # ifndef PCRECPP_EXP_DEFN # define PCRECPP_EXP_DEFN # endif #endif /* Have to include stdlib.h in order to ensure that size_t is defined; it is needed here for malloc. */ #include <stdlib.h> /* Allow for C++ users */ #ifdef __cplusplus extern "C" { #endif /* Options. Some are compile-time only, some are run-time only, and some are both, so we keep them all distinct. However, almost all the bits in the options word are now used. In the long run, we may have to re-use some of the compile-time only bits for runtime options, or vice versa. In the comments below, "compile", "exec", and "DFA exec" mean that the option is permitted to be set for those functions; "used in" means that an option may be set only for compile, but is subsequently referenced in exec and/or DFA exec. Any of the compile-time options may be inspected during studying (and therefore JIT compiling). */ #define PCRE_CASELESS 0x00000001 /* Compile */ #define PCRE_MULTILINE 0x00000002 /* Compile */ #define PCRE_DOTALL 0x00000004 /* Compile */ #define PCRE_EXTENDED 0x00000008 /* Compile */ #define PCRE_ANCHORED 0x00000010 /* Compile, exec, DFA exec */ #define PCRE_DOLLAR_ENDONLY 0x00000020 /* Compile, used in exec, DFA exec */ #define PCRE_EXTRA 0x00000040 /* Compile */ #define PCRE_NOTBOL 0x00000080 /* Exec, DFA exec */ #define PCRE_NOTEOL 0x00000100 /* Exec, DFA exec */ #define PCRE_UNGREEDY 0x00000200 /* Compile */ #define PCRE_NOTEMPTY 0x00000400 /* Exec, DFA exec */ /* The next two are also used in exec and DFA exec */ #define PCRE_UTF8 0x00000800 /* Compile (same as PCRE_UTF16) */ #define PCRE_UTF16 0x00000800 /* Compile (same as PCRE_UTF8) */ #define PCRE_NO_AUTO_CAPTURE 0x00001000 /* Compile */ /* The next two are also used in exec and DFA exec */ #define PCRE_NO_UTF8_CHECK 0x00002000 /* Compile (same as PCRE_NO_UTF16_CHECK) */ #define PCRE_NO_UTF16_CHECK 0x00002000 /* Compile (same as PCRE_NO_UTF8_CHECK) */ #define PCRE_AUTO_CALLOUT 0x00004000 /* Compile */ #define PCRE_PARTIAL_SOFT 0x00008000 /* Exec, DFA exec */ #define PCRE_PARTIAL 0x00008000 /* Backwards compatible synonym */ #define PCRE_DFA_SHORTEST 0x00010000 /* DFA exec */ #define PCRE_DFA_RESTART 0x00020000 /* DFA exec */ #define PCRE_FIRSTLINE 0x00040000 /* Compile, used in exec, DFA exec */ #define PCRE_DUPNAMES 0x00080000 /* Compile */ #define PCRE_NEWLINE_CR 0x00100000 /* Compile, exec, DFA exec */ #define PCRE_NEWLINE_LF 0x00200000 /* Compile, exec, DFA exec */ #define PCRE_NEWLINE_CRLF 0x00300000 /* Compile, exec, DFA exec */ #define PCRE_NEWLINE_ANY 0x00400000 /* Compile, exec, DFA exec */ #define PCRE_NEWLINE_ANYCRLF 0x00500000 /* Compile, exec, DFA exec */ #define PCRE_BSR_ANYCRLF 0x00800000 /* Compile, exec, DFA exec */ #define PCRE_BSR_UNICODE 0x01000000 /* Compile, exec, DFA exec */ #define PCRE_JAVASCRIPT_COMPAT 0x02000000 /* Compile, used in exec */ #define PCRE_NO_START_OPTIMIZE 0x04000000 /* Compile, exec, DFA exec */ #define PCRE_NO_START_OPTIMISE 0x04000000 /* Synonym */ #define PCRE_PARTIAL_HARD 0x08000000 /* Exec, DFA exec */ #define PCRE_NOTEMPTY_ATSTART 0x10000000 /* Exec, DFA exec */ #define PCRE_UCP 0x20000000 /* Compile, used in exec, DFA exec */ /* Exec-time and get/set-time error codes */ #define PCRE_ERROR_NOMATCH (-1) #define PCRE_ERROR_NULL (-2) #define PCRE_ERROR_BADOPTION (-3) #define PCRE_ERROR_BADMAGIC (-4) #define PCRE_ERROR_UNKNOWN_OPCODE (-5) #define PCRE_ERROR_UNKNOWN_NODE (-5) /* For backward compatibility */ #define PCRE_ERROR_NOMEMORY (-6) #define PCRE_ERROR_NOSUBSTRING (-7) #define PCRE_ERROR_MATCHLIMIT (-8) #define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ #define PCRE_ERROR_BADUTF8 (-10) /* Same for 8/16 */ #define PCRE_ERROR_BADUTF16 (-10) /* Same for 8/16 */ #define PCRE_ERROR_BADUTF8_OFFSET (-11) /* Same for 8/16 */ #define PCRE_ERROR_BADUTF16_OFFSET (-11) /* Same for 8/16 */ #define PCRE_ERROR_PARTIAL (-12) #define PCRE_ERROR_BADPARTIAL (-13) #define PCRE_ERROR_INTERNAL (-14) #define PCRE_ERROR_BADCOUNT (-15) #define PCRE_ERROR_DFA_UITEM (-16) #define PCRE_ERROR_DFA_UCOND (-17) #define PCRE_ERROR_DFA_UMLIMIT (-18) #define PCRE_ERROR_DFA_WSSIZE (-19) #define PCRE_ERROR_DFA_RECURSE (-20) #define PCRE_ERROR_RECURSIONLIMIT (-21) #define PCRE_ERROR_NULLWSLIMIT (-22) /* No longer actually used */ #define PCRE_ERROR_BADNEWLINE (-23) #define PCRE_ERROR_BADOFFSET (-24) #define PCRE_ERROR_SHORTUTF8 (-25) #define PCRE_ERROR_SHORTUTF16 (-25) /* Same for 8/16 */ #define PCRE_ERROR_RECURSELOOP (-26) #define PCRE_ERROR_JIT_STACKLIMIT (-27) #define PCRE_ERROR_BADMODE (-28) #define PCRE_ERROR_BADENDIANNESS (-29) /* Specific error codes for UTF-8 validity checks */ #define PCRE_UTF8_ERR0 0 #define PCRE_UTF8_ERR1 1 #define PCRE_UTF8_ERR2 2 #define PCRE_UTF8_ERR3 3 #define PCRE_UTF8_ERR4 4 #define PCRE_UTF8_ERR5 5 #define PCRE_UTF8_ERR6 6 #define PCRE_UTF8_ERR7 7 #define PCRE_UTF8_ERR8 8 #define PCRE_UTF8_ERR9 9 #define PCRE_UTF8_ERR10 10 #define PCRE_UTF8_ERR11 11 #define PCRE_UTF8_ERR12 12 #define PCRE_UTF8_ERR13 13 #define PCRE_UTF8_ERR14 14 #define PCRE_UTF8_ERR15 15 #define PCRE_UTF8_ERR16 16 #define PCRE_UTF8_ERR17 17 #define PCRE_UTF8_ERR18 18 #define PCRE_UTF8_ERR19 19 #define PCRE_UTF8_ERR20 20 #define PCRE_UTF8_ERR21 21 /* Specific error codes for UTF-16 validity checks */ #define PCRE_UTF16_ERR0 0 #define PCRE_UTF16_ERR1 1 #define PCRE_UTF16_ERR2 2 #define PCRE_UTF16_ERR3 3 #define PCRE_UTF16_ERR4 4 /* Request types for pcre_fullinfo() */ #define PCRE_INFO_OPTIONS 0 #define PCRE_INFO_SIZE 1 #define PCRE_INFO_CAPTURECOUNT 2 #define PCRE_INFO_BACKREFMAX 3 #define PCRE_INFO_FIRSTBYTE 4 #define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ #define PCRE_INFO_FIRSTTABLE 5 #define PCRE_INFO_LASTLITERAL 6 #define PCRE_INFO_NAMEENTRYSIZE 7 #define PCRE_INFO_NAMECOUNT 8 #define PCRE_INFO_NAMETABLE 9 #define PCRE_INFO_STUDYSIZE 10 #define PCRE_INFO_DEFAULT_TABLES 11 #define PCRE_INFO_OKPARTIAL 12 #define PCRE_INFO_JCHANGED 13 #define PCRE_INFO_HASCRORLF 14 #define PCRE_INFO_MINLENGTH 15 #define PCRE_INFO_JIT 16 #define PCRE_INFO_JITSIZE 17 /* Request types for pcre_config(). Do not re-arrange, in order to remain compatible. */ #define PCRE_CONFIG_UTF8 0 #define PCRE_CONFIG_NEWLINE 1 #define PCRE_CONFIG_LINK_SIZE 2 #define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 #define PCRE_CONFIG_MATCH_LIMIT 4 #define PCRE_CONFIG_STACKRECURSE 5 #define PCRE_CONFIG_UNICODE_PROPERTIES 6 #define PCRE_CONFIG_MATCH_LIMIT_RECURSION 7 #define PCRE_CONFIG_BSR 8 #define PCRE_CONFIG_JIT 9 #define PCRE_CONFIG_UTF16 10 #define PCRE_CONFIG_JITTARGET 11 /* Request types for pcre_study(). Do not re-arrange, in order to remain compatible. */ #define PCRE_STUDY_JIT_COMPILE 0x0001 /* Bit flags for the pcre[16]_extra structure. Do not re-arrange or redefine these bits, just add new ones on the end, in order to remain compatible. */ #define PCRE_EXTRA_STUDY_DATA 0x0001 #define PCRE_EXTRA_MATCH_LIMIT 0x0002 #define PCRE_EXTRA_CALLOUT_DATA 0x0004 #define PCRE_EXTRA_TABLES 0x0008 #define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0x0010 #define PCRE_EXTRA_MARK 0x0020 #define PCRE_EXTRA_EXECUTABLE_JIT 0x0040 /* Types */ struct real_pcre; /* declaration; the definition is private */ typedef struct real_pcre pcre; struct real_pcre16; /* declaration; the definition is private */ typedef struct real_pcre16 pcre16; struct real_pcre_jit_stack; /* declaration; the definition is private */ typedef struct real_pcre_jit_stack pcre_jit_stack; struct real_pcre16_jit_stack; /* declaration; the definition is private */ typedef struct real_pcre16_jit_stack pcre16_jit_stack; /* If PCRE is compiled with 16 bit character support, PCRE_UCHAR16 must contain a 16 bit wide signed data type. Otherwise it can be a dummy data type since pcre16 functions are not implemented. There is a check for this in pcre_internal.h. */ #ifndef PCRE_UCHAR16 #define PCRE_UCHAR16 wchar_t #endif #ifndef PCRE_SPTR16 #define PCRE_SPTR16 const PCRE_UCHAR16 * #endif /* When PCRE is compiled as a C++ library, the subject pointer type can be replaced with a custom type. For conventional use, the public interface is a const char *. */ #ifndef PCRE_SPTR #define PCRE_SPTR const char * #endif /* The structure for passing additional data to pcre_exec(). This is defined in such as way as to be extensible. Always add new fields at the end, in order to remain compatible. */ typedef struct pcre_extra { unsigned long int flags; /* Bits for which fields are set */ void *study_data; /* Opaque data from pcre_study() */ unsigned long int match_limit; /* Maximum number of calls to match() */ void *callout_data; /* Data passed back in callouts */ const unsigned char *tables; /* Pointer to character tables */ unsigned long int match_limit_recursion; /* Max recursive calls to match() */ unsigned char **mark; /* For passing back a mark pointer */ void *executable_jit; /* Contains a pointer to a compiled jit code */ } pcre_extra; /* Same structure as above, but with 16 bit char pointers. */ typedef struct pcre16_extra { unsigned long int flags; /* Bits for which fields are set */ void *study_data; /* Opaque data from pcre_study() */ unsigned long int match_limit; /* Maximum number of calls to match() */ void *callout_data; /* Data passed back in callouts */ const unsigned char *tables; /* Pointer to character tables */ unsigned long int match_limit_recursion; /* Max recursive calls to match() */ PCRE_UCHAR16 **mark; /* For passing back a mark pointer */ void *executable_jit; /* Contains a pointer to a compiled jit code */ } pcre16_extra; /* The structure for passing out data via the pcre_callout_function. We use a structure so that new fields can be added on the end in future versions, without changing the API of the function, thereby allowing old clients to work without modification. */ typedef struct pcre_callout_block { int version; /* Identifies version of block */ /* ------------------------ Version 0 ------------------------------- */ int callout_number; /* Number compiled into pattern */ int *offset_vector; /* The offset vector */ PCRE_SPTR subject; /* The subject being matched */ int subject_length; /* The length of the subject */ int start_match; /* Offset to start of this match attempt */ int current_position; /* Where we currently are in the subject */ int capture_top; /* Max current capture */ int capture_last; /* Most recently closed capture */ void *callout_data; /* Data passed in with the call */ /* ------------------- Added for Version 1 -------------------------- */ int pattern_position; /* Offset to next item in the pattern */ int next_item_length; /* Length of next item in the pattern */ /* ------------------- Added for Version 2 -------------------------- */ const unsigned char *mark; /* Pointer to current mark or NULL */ /* ------------------- Added for AutoHotkey ------------------------- */ const unsigned char *user_callout; /* ------------------------------------------------------------------ */ } pcre_callout_block; /* Same structure as above, but with 16 bit char pointers. */ typedef struct pcre16_callout_block { int version; /* Identifies version of block */ /* ------------------------ Version 0 ------------------------------- */ int callout_number; /* Number compiled into pattern */ int *offset_vector; /* The offset vector */ PCRE_SPTR16 subject; /* The subject being matched */ int subject_length; /* The length of the subject */ int start_match; /* Offset to start of this match attempt */ int current_position; /* Where we currently are in the subject */ int capture_top; /* Max current capture */ int capture_last; /* Most recently closed capture */ void *callout_data; /* Data passed in with the call */ /* ------------------- Added for Version 1 -------------------------- */ int pattern_position; /* Offset to next item in the pattern */ int next_item_length; /* Length of next item in the pattern */ /* ------------------- Added for Version 2 -------------------------- */ const PCRE_UCHAR16 *mark; /* Pointer to current mark or NULL */ /* ------------------- Added for AutoHotkey ------------------------- */ const PCRE_UCHAR16 *user_callout; /* ------------------------------------------------------------------ */ } pcre16_callout_block; /* Indirection for store get and free functions. These can be set to alternative malloc/free functions if required. Special ones are used in the non-recursive case for "frames". There is also an optional callout function that is triggered by the (?) regex item. For Virtual Pascal, these definitions have to take another form. */ #ifndef VPCOMPAT PCRE_EXP_DECL void *(*pcre_malloc)(size_t); PCRE_EXP_DECL void (*pcre_free)(void *); PCRE_EXP_DECL void *(*pcre_stack_malloc)(size_t); PCRE_EXP_DECL void (*pcre_stack_free)(void *); PCRE_EXP_DECL int (*pcre_callout)(pcre_callout_block *); PCRE_EXP_DECL void *(*pcre16_malloc)(size_t); PCRE_EXP_DECL void (*pcre16_free)(void *); PCRE_EXP_DECL void *(*pcre16_stack_malloc)(size_t); PCRE_EXP_DECL void (*pcre16_stack_free)(void *); PCRE_EXP_DECL int (*pcre16_callout)(pcre16_callout_block *); #else /* VPCOMPAT */ PCRE_EXP_DECL void *pcre_malloc(size_t); PCRE_EXP_DECL void pcre_free(void *); PCRE_EXP_DECL void *pcre_stack_malloc(size_t); PCRE_EXP_DECL void pcre_stack_free(void *); PCRE_EXP_DECL int pcre_callout(pcre_callout_block *); PCRE_EXP_DECL void *pcre16_malloc(size_t); PCRE_EXP_DECL void pcre16_free(void *); PCRE_EXP_DECL void *pcre16_stack_malloc(size_t); PCRE_EXP_DECL void pcre16_stack_free(void *); PCRE_EXP_DECL int pcre16_callout(pcre16_callout_block *); #endif /* VPCOMPAT */ /* User defined callback which provides a stack just before the match starts. */ typedef pcre_jit_stack *(*pcre_jit_callback)(void *); typedef pcre16_jit_stack *(*pcre16_jit_callback)(void *); /* Exported PCRE functions */ PCRE_EXP_DECL pcre *pcre_compile(const char *, int, const char **, int *, const unsigned char *); PCRE_EXP_DECL pcre16 *pcre16_compile(PCRE_SPTR16, int, const char **, int *, const unsigned char *); PCRE_EXP_DECL pcre *pcre_compile2(const char *, int, int *, const char **, int *, const unsigned char *); PCRE_EXP_DECL pcre16 *pcre16_compile2(PCRE_SPTR16, int, int *, const char **, int *, const unsigned char *); PCRE_EXP_DECL int pcre_config(int, void *); PCRE_EXP_DECL int pcre16_config(int, void *); PCRE_EXP_DECL int pcre_copy_named_substring(const pcre *, const char *, int *, int, const char *, char *, int); PCRE_EXP_DECL int pcre16_copy_named_substring(const pcre16 *, PCRE_SPTR16, int *, int, PCRE_SPTR16, PCRE_UCHAR16 *, int); PCRE_EXP_DECL int pcre_copy_substring(const char *, int *, int, int, char *, int); PCRE_EXP_DECL int pcre16_copy_substring(PCRE_SPTR16, int *, int, int, PCRE_UCHAR16 *, int); PCRE_EXP_DECL int pcre_dfa_exec(const pcre *, const pcre_extra *, const char *, int, int, int, int *, int , int *, int); PCRE_EXP_DECL int pcre16_dfa_exec(const pcre16 *, const pcre16_extra *, PCRE_SPTR16, int, int, int, int *, int , int *, int); PCRE_EXP_DECL int pcre_exec(const pcre *, const pcre_extra *, PCRE_SPTR, int, int, int, int *, int); PCRE_EXP_DECL int pcre16_exec(const pcre16 *, const pcre16_extra *, PCRE_SPTR16, int, int, int, int *, int); PCRE_EXP_DECL void pcre_free_substring(const char *); PCRE_EXP_DECL void pcre16_free_substring(PCRE_SPTR16); PCRE_EXP_DECL void pcre_free_substring_list(const char **); PCRE_EXP_DECL void pcre16_free_substring_list(PCRE_SPTR16 *); PCRE_EXP_DECL int pcre_fullinfo(const pcre *, const pcre_extra *, int, void *); PCRE_EXP_DECL int pcre16_fullinfo(const pcre16 *, const pcre16_extra *, int, void *); PCRE_EXP_DECL int pcre_get_named_substring(const pcre *, const char *, int *, int, const char *, const char **); PCRE_EXP_DECL int pcre16_get_named_substring(const pcre16 *, PCRE_SPTR16, int *, int, PCRE_SPTR16, PCRE_SPTR16 *); PCRE_EXP_DECL int pcre_get_stringnumber(const pcre *, const char *); PCRE_EXP_DECL int pcre16_get_stringnumber(const pcre16 *, PCRE_SPTR16); PCRE_EXP_DECL int pcre_get_first_set(const pcre *, const char *, int *); /* AutoHotkey */ PCRE_EXP_DECL int pcre16_get_first_set(const pcre16 *, PCRE_SPTR16, int *); /* AutoHotkey */ PCRE_EXP_DECL int pcre_get_stringtable_entries(const pcre *, const char *, char **, char **); PCRE_EXP_DECL int pcre16_get_stringtable_entries(const pcre16 *, PCRE_SPTR16, PCRE_UCHAR16 **, PCRE_UCHAR16 **); PCRE_EXP_DECL int pcre_get_substring(const char *, int *, int, int, const char **); PCRE_EXP_DECL int pcre16_get_substring(PCRE_SPTR16, int *, int, int, PCRE_SPTR16 *); PCRE_EXP_DECL int pcre_get_substring_list(const char *, int *, int, const char ***); PCRE_EXP_DECL int pcre16_get_substring_list(PCRE_SPTR16, int *, int, PCRE_SPTR16 **); PCRE_EXP_DECL const unsigned char *pcre_maketables(void); PCRE_EXP_DECL const unsigned char *pcre16_maketables(void); PCRE_EXP_DECL int pcre_refcount(pcre *, int); PCRE_EXP_DECL int pcre16_refcount(pcre16 *, int); PCRE_EXP_DECL pcre_extra *pcre_study(const pcre *, int, const char **); PCRE_EXP_DECL pcre16_extra *pcre16_study(const pcre16 *, int, const char **); PCRE_EXP_DECL void pcre_free_study(pcre_extra *); PCRE_EXP_DECL void pcre16_free_study(pcre16_extra *); PCRE_EXP_DECL const char *pcre_version(void); PCRE_EXP_DECL const char *pcre16_version(void); /* Utility functions for byte order swaps. */ PCRE_EXP_DECL int pcre_pattern_to_host_byte_order(pcre *, pcre_extra *, const unsigned char *); PCRE_EXP_DECL int pcre16_pattern_to_host_byte_order(pcre16 *, pcre16_extra *, const unsigned char *); PCRE_EXP_DECL int pcre16_utf16_to_host_byte_order(PCRE_UCHAR16 *, PCRE_SPTR16, int, int *, int); /* JIT compiler related functions. */ PCRE_EXP_DECL pcre_jit_stack *pcre_jit_stack_alloc(int, int); PCRE_EXP_DECL pcre16_jit_stack *pcre16_jit_stack_alloc(int, int); PCRE_EXP_DECL void pcre_jit_stack_free(pcre_jit_stack *); PCRE_EXP_DECL void pcre16_jit_stack_free(pcre16_jit_stack *); PCRE_EXP_DECL void pcre_assign_jit_stack(pcre_extra *, pcre_jit_callback, void *); PCRE_EXP_DECL void pcre16_assign_jit_stack(pcre16_extra *, pcre16_jit_callback, void *); #include "pcret.h" #ifdef __cplusplus } /* extern "C" */ #endif #endif /* End of pcre.h */
23,611
C++
.h
445
50.435955
93
0.649537
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
16,151
pcre_internal.h
AutoHotkey_AutoHotkey/source/lib_pcre/pcre/pcre_internal.h
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2012 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* This header contains definitions that are shared between the different modules, but which are not relevant to the exported API. This includes some functions whose names all begin with "_pcre_" or "_pcre16_" depending on the PRIV macro. */ #ifndef PCRE_INTERNAL_H #define PCRE_INTERNAL_H /* Define PCRE_DEBUG to get debugging output on stdout. */ #if 0 #define PCRE_DEBUG #endif /* PCRE is compiled as an 8 bit library if it is not requested otherwise. */ #ifndef COMPILE_PCRE16 #define COMPILE_PCRE8 #endif /* If SUPPORT_UCP is defined, SUPPORT_UTF must also be defined. The "configure" script ensures this, but not everybody uses "configure". */ #if defined SUPPORT_UCP && !(defined SUPPORT_UTF) #define SUPPORT_UTF 1 #endif /* We define SUPPORT_UTF if SUPPORT_UTF8 is enabled for compatibility reasons with existing code. */ #if defined SUPPORT_UTF8 && !(defined SUPPORT_UTF) #define SUPPORT_UTF 1 #endif /* Fixme: SUPPORT_UTF8 should be eventually disappear from the code. Until then we define it if SUPPORT_UTF is defined. */ #if defined SUPPORT_UTF && !(defined SUPPORT_UTF8) #define SUPPORT_UTF8 1 #endif /* AutoHotkey: UTF mode is always enabled in some builds and never enabled in others. This macros is used to aid the compiler to reduce code size. */ #if defined SUPPORT_UTF_OPTION && defined SUPPORT_UTF # define UTF_ENABLED(flag) flag #else # ifdef SUPPORT_UTF # define UTF_ENABLED(flag) TRUE # else # define UTF_ENABLED(flag) FALSE # endif #endif /* We do not support both EBCDIC and UTF-8/16 at the same time. The "configure" script prevents both being selected, but not everybody uses "configure". */ #if defined EBCDIC && defined SUPPORT_UTF #error The use of both EBCDIC and SUPPORT_UTF8/16 is not supported. #endif /* Use a macro for debugging printing, 'cause that eliminates the use of #ifdef inline, and there are *still* stupid compilers about that don't like indented pre-processor statements, or at least there were when I first wrote this. After all, it had only been about 10 years then... It turns out that the Mac Debugging.h header also defines the macro DPRINTF, so be absolutely sure we get our version. */ #undef DPRINTF #ifdef PCRE_DEBUG #define DPRINTF(p) printf p #else #define DPRINTF(p) /* Nothing */ #endif /* Standard C headers plus the external interface definition. The only time setjmp and stdarg are used is when NO_RECURSE is set. */ #include <ctype.h> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* When compiling a DLL for Windows, the exported symbols have to be declared using some MS magic. I found some useful information on this web page: http://msdn2.microsoft.com/en-us/library/y4h7bcy6(VS.80).aspx. According to the information there, using __declspec(dllexport) without "extern" we have a definition; with "extern" we have a declaration. The settings here override the setting in pcre.h (which is included below); it defines only PCRE_EXP_DECL, which is all that is needed for applications (they just import the symbols). We use: PCRE_EXP_DECL for declarations PCRE_EXP_DEFN for definitions of exported functions PCRE_EXP_DATA_DEFN for definitions of exported variables The reason for the two DEFN macros is that in non-Windows environments, one does not want to have "extern" before variable definitions because it leads to compiler warnings. So we distinguish between functions and variables. In Windows, the two should always be the same. The reason for wrapping this in #ifndef PCRE_EXP_DECL is so that pcretest, which is an application, but needs to import this file in order to "peek" at internals, can #include pcre.h first to get an application's-eye view. In principle, people compiling for non-Windows, non-Unix-like (i.e. uncommon, special-purpose environments) might want to stick other stuff in front of exported symbols. That's why, in the non-Windows case, we set PCRE_EXP_DEFN and PCRE_EXP_DATA_DEFN only if they are not already set. */ #ifndef PCRE_EXP_DECL # ifdef _WIN32 # ifndef PCRE_STATIC # define PCRE_EXP_DECL extern __declspec(dllexport) # define PCRE_EXP_DEFN __declspec(dllexport) # define PCRE_EXP_DATA_DEFN __declspec(dllexport) # else # define PCRE_EXP_DECL extern # define PCRE_EXP_DEFN # define PCRE_EXP_DATA_DEFN # endif # else # ifdef __cplusplus # define PCRE_EXP_DECL extern "C" # else # define PCRE_EXP_DECL extern # endif # ifndef PCRE_EXP_DEFN # define PCRE_EXP_DEFN PCRE_EXP_DECL # endif # ifndef PCRE_EXP_DATA_DEFN # define PCRE_EXP_DATA_DEFN # endif # endif #endif /* When compiling with the MSVC compiler, it is sometimes necessary to include a "calling convention" before exported function names. (This is secondhand information; I know nothing about MSVC myself). For example, something like void __cdecl function(....) might be needed. In order so make this easy, all the exported functions have PCRE_CALL_CONVENTION just before their names. It is rarely needed; if not set, we ensure here that it has no effect. */ #ifndef PCRE_CALL_CONVENTION #define PCRE_CALL_CONVENTION #endif /* We need to have types that specify unsigned 8, 16 and 32-bit integers. We cannot determine these outside the compilation (e.g. by running a program as part of "configure") because PCRE is often cross-compiled for use on other systems. Instead we make use of the maximum sizes that are available at preprocessor time in standard C environments. */ typedef unsigned char pcre_uint8; #if USHRT_MAX == 65535 typedef unsigned short pcre_uint16; typedef short pcre_int16; #elif UINT_MAX == 65535 typedef unsigned int pcre_uint16; typedef int pcre_int16; #else #error Cannot determine a type for 16-bit unsigned integers #endif #if UINT_MAX == 4294967295 typedef unsigned int pcre_uint32; typedef int pcre_int32; #elif ULONG_MAX == 4294967295 typedef unsigned long int pcre_uint32; typedef long int pcre_int32; #else #error Cannot determine a type for 32-bit unsigned integers #endif /* When checking for integer overflow in pcre_compile(), we need to handle large integers. If a 64-bit integer type is available, we can use that. Otherwise we have to cast to double, which of course requires floating point arithmetic. Handle this by defining a macro for the appropriate type. If stdint.h is available, include it; it may define INT64_MAX. Systems that do not have stdint.h (e.g. Solaris) may have inttypes.h. The macro int64_t may be set by "configure". */ #if HAVE_STDINT_H #include <stdint.h> #elif HAVE_INTTYPES_H #include <inttypes.h> #endif #if defined INT64_MAX || defined int64_t #define INT64_OR_DOUBLE int64_t #else #define INT64_OR_DOUBLE double #endif /* All character handling must be done as unsigned characters. Otherwise there are problems with top-bit-set characters and functions such as isspace(). However, we leave the interface to the outside world as char * or short *, because that should make things easier for callers. This character type is called pcre_uchar. The IN_UCHARS macro multiply its argument with the byte size of the current pcre_uchar type. Useful for memcpy and such operations, whose require the byte size of their input/output buffers. The MAX_255 macro checks whether its pcre_uchar input is less than 256. The TABLE_GET macro is designed for accessing elements of tables whose contain exactly 256 items. When the character is able to contain more than 256 items, some check is needed before accessing these tables. */ #ifdef COMPILE_PCRE8 typedef unsigned char pcre_uchar; #define IN_UCHARS(x) (x) #define MAX_255(c) 1 #define TABLE_GET(c, table, default) ((table)[c]) #else #ifdef COMPILE_PCRE16 #if USHRT_MAX != 65535 /* This is a warning message. Change PCRE_UCHAR16 to a 16 bit data type in pcre.h(.in) and disable (comment out) this message. */ #error Warning: PCRE_UCHAR16 is not a 16 bit data type. #endif typedef pcre_uint16 pcre_uchar; #define IN_UCHARS(x) ((x) << 1) #define MAX_255(c) ((c) <= 255u) #define TABLE_GET(c, table, default) (MAX_255(c)? ((table)[c]):(default)) #else #error Unsupported compiling mode #endif /* COMPILE_PCRE16 */ #endif /* COMPILE_PCRE8 */ /* This is an unsigned int value that no character can ever have. UTF-8 characters only go up to 0x7fffffff (though Unicode doesn't go beyond 0x0010ffff). */ #define NOTACHAR 0xffffffff /* PCRE is able to support several different kinds of newline (CR, LF, CRLF, "any" and "anycrlf" at present). The following macros are used to package up testing for newlines. NLBLOCK, PSSTART, and PSEND are defined in the various modules to indicate in which datablock the parameters exist, and what the start/end of string field names are. */ #define NLTYPE_FIXED 0 /* Newline is a fixed length string */ #define NLTYPE_ANY 1 /* Newline is any Unicode line ending */ #define NLTYPE_ANYCRLF 2 /* Newline is CR, LF, or CRLF */ /* This macro checks for a newline at the given position */ #define IS_NEWLINE(p) \ ((NLBLOCK->nltype != NLTYPE_FIXED)? \ ((p) < NLBLOCK->PSEND && \ PRIV(is_newline)((p), NLBLOCK->nltype, NLBLOCK->PSEND, \ &(NLBLOCK->nllen), utf)) \ : \ ((p) <= NLBLOCK->PSEND - NLBLOCK->nllen && \ (p)[0] == NLBLOCK->nl[0] && \ (NLBLOCK->nllen == 1 || (p)[1] == NLBLOCK->nl[1]) \ ) \ ) /* This macro checks for a newline immediately preceding the given position */ #define WAS_NEWLINE(p) \ ((NLBLOCK->nltype != NLTYPE_FIXED)? \ ((p) > NLBLOCK->PSSTART && \ PRIV(was_newline)((p), NLBLOCK->nltype, NLBLOCK->PSSTART, \ &(NLBLOCK->nllen), utf)) \ : \ ((p) >= NLBLOCK->PSSTART + NLBLOCK->nllen && \ (p)[-NLBLOCK->nllen] == NLBLOCK->nl[0] && \ (NLBLOCK->nllen == 1 || (p)[-NLBLOCK->nllen+1] == NLBLOCK->nl[1]) \ ) \ ) /* When PCRE is compiled as a C++ library, the subject pointer can be replaced with a custom type. This makes it possible, for example, to allow pcre_exec() to process subject strings that are discontinuous by using a smart pointer class. It must always be possible to inspect all of the subject string in pcre_exec() because of the way it backtracks. Two macros are required in the normal case, for sign-unspecified and unsigned char pointers. The former is used for the external interface and appears in pcre.h, which is why its name must begin with PCRE_. */ #ifdef CUSTOM_SUBJECT_PTR #define PCRE_PUCHAR CUSTOM_SUBJECT_PTR #else #define PCRE_PUCHAR const pcre_uchar * #endif /* Include the public PCRE header and the definitions of UCP character property values. */ #include "pcre.h" #include "ucp.h" /* When compiling for use with the Virtual Pascal compiler, these functions need to have their names changed. PCRE must be compiled with the -DVPCOMPAT option on the command line. */ #ifdef VPCOMPAT #define strlen(s) _strlen(s) #define strncmp(s1,s2,m) _strncmp(s1,s2,m) #define memcmp(s,c,n) _memcmp(s,c,n) #define memcpy(d,s,n) _memcpy(d,s,n) #define memmove(d,s,n) _memmove(d,s,n) #define memset(s,c,n) _memset(s,c,n) #else /* VPCOMPAT */ /* To cope with SunOS4 and other systems that lack memmove() but have bcopy(), define a macro for memmove() if HAVE_MEMMOVE is false, provided that HAVE_BCOPY is set. Otherwise, include an emulating function for those systems that have neither (there some non-Unix environments where this is the case). */ #ifndef HAVE_MEMMOVE #undef memmove /* some systems may have a macro */ #ifdef HAVE_BCOPY #define memmove(a, b, c) bcopy(b, a, c) #else /* HAVE_BCOPY */ static void * pcre_memmove(void *d, const void *s, size_t n) { size_t i; unsigned char *dest = (unsigned char *)d; const unsigned char *src = (const unsigned char *)s; if (dest > src) { dest += n; src += n; for (i = 0; i < n; ++i) *(--dest) = *(--src); return (void *)dest; } else { for (i = 0; i < n; ++i) *dest++ = *src++; return (void *)(dest - n); } } #define memmove(a, b, c) pcre_memmove(a, b, c) #endif /* not HAVE_BCOPY */ #endif /* not HAVE_MEMMOVE */ #endif /* not VPCOMPAT */ /* PCRE keeps offsets in its compiled code as 2-byte quantities (always stored in big-endian order) by default. These are used, for example, to link from the start of a subpattern to its alternatives and its end. The use of 2 bytes per offset limits the size of the compiled regex to around 64K, which is big enough for almost everybody. However, I received a request for an even bigger limit. For this reason, and also to make the code easier to maintain, the storing and loading of offsets from the byte string is now handled by the macros that are defined here. The macros are controlled by the value of LINK_SIZE. This defaults to 2 in the config.h file, but can be overridden by using -D on the command line. This is automated on Unix systems via the "configure" command. */ #ifdef COMPILE_PCRE8 #if LINK_SIZE == 2 #define PUT(a,n,d) \ (a[n] = (d) >> 8), \ (a[(n)+1] = (d) & 255) #define GET(a,n) \ (((a)[n] << 8) | (a)[(n)+1]) #define MAX_PATTERN_SIZE (1 << 16) #elif LINK_SIZE == 3 #define PUT(a,n,d) \ (a[n] = (d) >> 16), \ (a[(n)+1] = (d) >> 8), \ (a[(n)+2] = (d) & 255) #define GET(a,n) \ (((a)[n] << 16) | ((a)[(n)+1] << 8) | (a)[(n)+2]) #define MAX_PATTERN_SIZE (1 << 24) #elif LINK_SIZE == 4 #define PUT(a,n,d) \ (a[n] = (d) >> 24), \ (a[(n)+1] = (d) >> 16), \ (a[(n)+2] = (d) >> 8), \ (a[(n)+3] = (d) & 255) #define GET(a,n) \ (((a)[n] << 24) | ((a)[(n)+1] << 16) | ((a)[(n)+2] << 8) | (a)[(n)+3]) /* Keep it positive */ #define MAX_PATTERN_SIZE (1 << 30) #else #error LINK_SIZE must be either 2, 3, or 4 #endif #else /* COMPILE_PCRE8 */ #ifdef COMPILE_PCRE16 #if LINK_SIZE == 2 #undef LINK_SIZE #define LINK_SIZE 1 #define PUT(a,n,d) \ (a[n] = (d)) #define GET(a,n) \ (a[n]) #define MAX_PATTERN_SIZE (1 << 16) #elif LINK_SIZE == 3 || LINK_SIZE == 4 #undef LINK_SIZE #define LINK_SIZE 2 #define PUT(a,n,d) \ (a[n] = (d) >> 16), \ (a[(n)+1] = (d) & 65535) #define GET(a,n) \ (((a)[n] << 16) | (a)[(n)+1]) /* Keep it positive */ #define MAX_PATTERN_SIZE (1 << 30) #else #error LINK_SIZE must be either 2, 3, or 4 #endif #else #error Unsupported compiling mode #endif /* COMPILE_PCRE16 */ #endif /* COMPILE_PCRE8 */ /* Convenience macro defined in terms of the others */ #define PUTINC(a,n,d) PUT(a,n,d), a += LINK_SIZE /* PCRE uses some other 2-byte quantities that do not change when the size of offsets changes. There are used for repeat counts and for other things such as capturing parenthesis numbers in back references. */ #ifdef COMPILE_PCRE8 #define IMM2_SIZE 2 #define IMMPTR_SIZE sizeof(void *) #define PUT2(a,n,d) \ a[n] = (d) >> 8; \ a[(n)+1] = (d) & 255 #define GET2(a,n) \ (((a)[n] << 8) | (a)[(n)+1]) #else /* COMPILE_PCRE8 */ #ifdef COMPILE_PCRE16 #define IMM2_SIZE 1 #define IMMPTR_SIZE (sizeof(void *) / 2) #define PUT2(a,n,d) \ a[n] = d #define GET2(a,n) \ a[n] #else #error Unsupported compiling mode #endif /* COMPILE_PCRE16 */ #endif /* COMPILE_PCRE8 */ #define PUT2INC(a,n,d) PUT2(a,n,d), a += IMM2_SIZE /* When UTF encoding is being used, a character is no longer just a single character. The macros for character handling generate simple sequences when used in character-mode, and more complicated ones for UTF characters. GETCHARLENTEST and other macros are not used when UTF is not supported, so they are not defined. To make sure they can never even appear when UTF support is omitted, we don't even define them. */ #ifndef SUPPORT_UTF /* #define MAX_VALUE_FOR_SINGLE_CHAR */ /* #define HAS_EXTRALEN(c) */ /* #define GET_EXTRALEN(c) */ /* #define NOT_FIRSTCHAR(c) */ #define GETCHAR(c, eptr) c = *eptr; #define GETCHARTEST(c, eptr) c = *eptr; #define GETCHARINC(c, eptr) c = *eptr++; #define GETCHARINCTEST(c, eptr) c = *eptr++; #define GETCHARLEN(c, eptr, len) c = *eptr; /* #define GETCHARLENTEST(c, eptr, len) */ /* #define BACKCHAR(eptr) */ /* #define FORWARDCHAR(eptr) */ /* #define ACROSSCHAR(condition, eptr, action) */ #else /* SUPPORT_UTF */ #ifdef COMPILE_PCRE8 /* These macros were originally written in the form of loops that used data from the tables whose names start with PRIV(utf8_table). They were rewritten by a user so as not to use loops, because in some environments this gives a significant performance advantage, and it seems never to do any harm. */ /* Tells the biggest code point which can be encoded as a single character. */ #define MAX_VALUE_FOR_SINGLE_CHAR 127 /* Tests whether the code point needs extra characters to decode. */ #define HAS_EXTRALEN(c) ((c) >= 0xc0) /* Returns with the additional number of characters if IS_MULTICHAR(c) is TRUE. Otherwise it has an undefined behaviour. */ #define GET_EXTRALEN(c) (PRIV(utf8_table4)[(c) & 0x3f]) /* Returns TRUE, if the given character is not the first character of a UTF sequence. */ #define NOT_FIRSTCHAR(c) (((c) & 0xc0) == 0x80) /* Base macro to pick up the remaining bytes of a UTF-8 character, not advancing the pointer. */ #define GETUTF8(c, eptr) \ { \ if ((c & 0x20) == 0) \ c = ((c & 0x1f) << 6) | (eptr[1] & 0x3f); \ else if ((c & 0x10) == 0) \ c = ((c & 0x0f) << 12) | ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ else if ((c & 0x08) == 0) \ c = ((c & 0x07) << 18) | ((eptr[1] & 0x3f) << 12) | \ ((eptr[2] & 0x3f) << 6) | (eptr[3] & 0x3f); \ else if ((c & 0x04) == 0) \ c = ((c & 0x03) << 24) | ((eptr[1] & 0x3f) << 18) | \ ((eptr[2] & 0x3f) << 12) | ((eptr[3] & 0x3f) << 6) | \ (eptr[4] & 0x3f); \ else \ c = ((c & 0x01) << 30) | ((eptr[1] & 0x3f) << 24) | \ ((eptr[2] & 0x3f) << 18) | ((eptr[3] & 0x3f) << 12) | \ ((eptr[4] & 0x3f) << 6) | (eptr[5] & 0x3f); \ } /* Get the next UTF-8 character, not advancing the pointer. This is called when we know we are in UTF-8 mode. */ #define GETCHAR(c, eptr) \ c = *eptr; \ if (c >= 0xc0) GETUTF8(c, eptr); /* Get the next UTF-8 character, testing for UTF-8 mode, and not advancing the pointer. */ #define GETCHARTEST(c, eptr) \ c = *eptr; \ if (utf && c >= 0xc0) GETUTF8(c, eptr); /* Base macro to pick up the remaining bytes of a UTF-8 character, advancing the pointer. */ #define GETUTF8INC(c, eptr) \ { \ if ((c & 0x20) == 0) \ c = ((c & 0x1f) << 6) | (*eptr++ & 0x3f); \ else if ((c & 0x10) == 0) \ { \ c = ((c & 0x0f) << 12) | ((*eptr & 0x3f) << 6) | (eptr[1] & 0x3f); \ eptr += 2; \ } \ else if ((c & 0x08) == 0) \ { \ c = ((c & 0x07) << 18) | ((*eptr & 0x3f) << 12) | \ ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ eptr += 3; \ } \ else if ((c & 0x04) == 0) \ { \ c = ((c & 0x03) << 24) | ((*eptr & 0x3f) << 18) | \ ((eptr[1] & 0x3f) << 12) | ((eptr[2] & 0x3f) << 6) | \ (eptr[3] & 0x3f); \ eptr += 4; \ } \ else \ { \ c = ((c & 0x01) << 30) | ((*eptr & 0x3f) << 24) | \ ((eptr[1] & 0x3f) << 18) | ((eptr[2] & 0x3f) << 12) | \ ((eptr[3] & 0x3f) << 6) | (eptr[4] & 0x3f); \ eptr += 5; \ } \ } /* Get the next UTF-8 character, advancing the pointer. This is called when we know we are in UTF-8 mode. */ #define GETCHARINC(c, eptr) \ c = *eptr++; \ if (c >= 0xc0) GETUTF8INC(c, eptr); /* Get the next character, testing for UTF-8 mode, and advancing the pointer. This is called when we don't know if we are in UTF-8 mode. */ #define GETCHARINCTEST(c, eptr) \ c = *eptr++; \ if (utf && c >= 0xc0) GETUTF8INC(c, eptr); /* Base macro to pick up the remaining bytes of a UTF-8 character, not advancing the pointer, incrementing the length. */ #define GETUTF8LEN(c, eptr, len) \ { \ if ((c & 0x20) == 0) \ { \ c = ((c & 0x1f) << 6) | (eptr[1] & 0x3f); \ len++; \ } \ else if ((c & 0x10) == 0) \ { \ c = ((c & 0x0f) << 12) | ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ len += 2; \ } \ else if ((c & 0x08) == 0) \ {\ c = ((c & 0x07) << 18) | ((eptr[1] & 0x3f) << 12) | \ ((eptr[2] & 0x3f) << 6) | (eptr[3] & 0x3f); \ len += 3; \ } \ else if ((c & 0x04) == 0) \ { \ c = ((c & 0x03) << 24) | ((eptr[1] & 0x3f) << 18) | \ ((eptr[2] & 0x3f) << 12) | ((eptr[3] & 0x3f) << 6) | \ (eptr[4] & 0x3f); \ len += 4; \ } \ else \ {\ c = ((c & 0x01) << 30) | ((eptr[1] & 0x3f) << 24) | \ ((eptr[2] & 0x3f) << 18) | ((eptr[3] & 0x3f) << 12) | \ ((eptr[4] & 0x3f) << 6) | (eptr[5] & 0x3f); \ len += 5; \ } \ } /* Get the next UTF-8 character, not advancing the pointer, incrementing length if there are extra bytes. This is called when we know we are in UTF-8 mode. */ #define GETCHARLEN(c, eptr, len) \ c = *eptr; \ if (c >= 0xc0) GETUTF8LEN(c, eptr, len); /* Get the next UTF-8 character, testing for UTF-8 mode, not advancing the pointer, incrementing length if there are extra bytes. This is called when we do not know if we are in UTF-8 mode. */ #define GETCHARLENTEST(c, eptr, len) \ c = *eptr; \ if (utf && c >= 0xc0) GETUTF8LEN(c, eptr, len); /* If the pointer is not at the start of a character, move it back until it is. This is called only in UTF-8 mode - we don't put a test within the macro because almost all calls are already within a block of UTF-8 only code. */ #define BACKCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr-- /* Same as above, just in the other direction. */ #define FORWARDCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr++ /* Same as above, but it allows a fully customizable form. */ #define ACROSSCHAR(condition, eptr, action) \ while((condition) && ((eptr) & 0xc0) == 0x80) action #else /* COMPILE_PCRE8 */ #ifdef COMPILE_PCRE16 /* Tells the biggest code point which can be encoded as a single character. */ #define MAX_VALUE_FOR_SINGLE_CHAR 65535 /* Tests whether the code point needs extra characters to decode. */ #define HAS_EXTRALEN(c) (((c) & 0xfc00) == 0xd800) /* Returns with the additional number of characters if IS_MULTICHAR(c) is TRUE. Otherwise it has an undefined behaviour. */ #define GET_EXTRALEN(c) 1 /* Returns TRUE, if the given character is not the first character of a UTF sequence. */ #define NOT_FIRSTCHAR(c) (((c) & 0xfc00) == 0xdc00) /* Base macro to pick up the low surrogate of a UTF-16 character, not advancing the pointer. */ #define GETUTF16(c, eptr) \ { c = (((c & 0x3ff) << 10) | (eptr[1] & 0x3ff)) + 0x10000; } /* Get the next UTF-16 character, not advancing the pointer. This is called when we know we are in UTF-16 mode. */ #define GETCHAR(c, eptr) \ c = *eptr; \ if ((c & 0xfc00) == 0xd800) GETUTF16(c, eptr); /* Get the next UTF-16 character, testing for UTF-16 mode, and not advancing the pointer. */ #define GETCHARTEST(c, eptr) \ c = *eptr; \ if (utf && (c & 0xfc00) == 0xd800) GETUTF16(c, eptr); /* Base macro to pick up the low surrogate of a UTF-16 character, advancing the pointer. */ #define GETUTF16INC(c, eptr) \ { c = (((c & 0x3ff) << 10) | (*eptr++ & 0x3ff)) + 0x10000; } /* Get the next UTF-16 character, advancing the pointer. This is called when we know we are in UTF-16 mode. */ #define GETCHARINC(c, eptr) \ c = *eptr++; \ if ((c & 0xfc00) == 0xd800) GETUTF16INC(c, eptr); /* Get the next character, testing for UTF-16 mode, and advancing the pointer. This is called when we don't know if we are in UTF-16 mode. */ #define GETCHARINCTEST(c, eptr) \ c = *eptr++; \ if (utf && (c & 0xfc00) == 0xd800) GETUTF16INC(c, eptr); /* Base macro to pick up the low surrogate of a UTF-16 character, not advancing the pointer, incrementing the length. */ #define GETUTF16LEN(c, eptr, len) \ { c = (((c & 0x3ff) << 10) | (eptr[1] & 0x3ff)) + 0x10000; len++; } /* Get the next UTF-16 character, not advancing the pointer, incrementing length if there is a low surrogate. This is called when we know we are in UTF-16 mode. */ #define GETCHARLEN(c, eptr, len) \ c = *eptr; \ if ((c & 0xfc00) == 0xd800) GETUTF16LEN(c, eptr, len); /* Get the next UTF-816character, testing for UTF-16 mode, not advancing the pointer, incrementing length if there is a low surrogate. This is called when we do not know if we are in UTF-16 mode. */ #define GETCHARLENTEST(c, eptr, len) \ c = *eptr; \ if (utf && (c & 0xfc00) == 0xd800) GETUTF16LEN(c, eptr, len); /* If the pointer is not at the start of a character, move it back until it is. This is called only in UTF-16 mode - we don't put a test within the macro because almost all calls are already within a block of UTF-16 only code. */ #define BACKCHAR(eptr) if ((*eptr & 0xfc00) == 0xdc00) eptr-- /* Same as above, just in the other direction. */ #define FORWARDCHAR(eptr) if ((*eptr & 0xfc00) == 0xdc00) eptr++ /* Same as above, but it allows a fully customizable form. */ #define ACROSSCHAR(condition, eptr, action) \ if ((condition) && ((eptr) & 0xfc00) == 0xdc00) action #endif #endif /* COMPILE_PCRE8 */ #endif /* SUPPORT_UTF */ /* In case there is no definition of offsetof() provided - though any proper Standard C system should have one. */ #ifndef offsetof #define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field)) #endif /* Private flags containing information about the compiled regex. They used to live at the top end of the options word, but that got almost full, so now they are in a 16-bit flags word. From release 8.00, PCRE_NOPARTIAL is unused, as the restrictions on partial matching have been lifted. It remains for backwards compatibility. */ #ifdef COMPILE_PCRE8 #define PCRE_MODE 0x0001 /* compiled in 8 bit mode */ #endif #ifdef COMPILE_PCRE16 #define PCRE_MODE 0x0002 /* compiled in 16 bit mode */ #endif #define PCRE_FIRSTSET 0x0010 /* first_char is set */ #define PCRE_FCH_CASELESS 0x0020 /* caseless first char */ #define PCRE_REQCHSET 0x0040 /* req_byte is set */ #define PCRE_RCH_CASELESS 0x0080 /* caseless requested char */ #define PCRE_STARTLINE 0x0100 /* start after \n for multiline */ #define PCRE_NOPARTIAL 0x0200 /* can't use partial with this regex */ #define PCRE_JCHANGED 0x0400 /* j option used in regex */ #define PCRE_HASCRORLF 0x0800 /* explicit \r or \n in pattern */ #define PCRE_HASTHEN 0x1000 /* pattern contains (*THEN) */ /* Flags for the "extra" block produced by pcre_study(). */ #define PCRE_STUDY_MAPPED 0x0001 /* a map of starting chars exists */ #define PCRE_STUDY_MINLEN 0x0002 /* a minimum length field exists */ /* Masks for identifying the public options that are permitted at compile time, run time, or study time, respectively. */ #define PCRE_NEWLINE_BITS (PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|PCRE_NEWLINE_ANY| \ PCRE_NEWLINE_ANYCRLF) #define PUBLIC_COMPILE_OPTIONS \ (PCRE_CASELESS|PCRE_EXTENDED|PCRE_ANCHORED|PCRE_MULTILINE| \ PCRE_DOTALL|PCRE_DOLLAR_ENDONLY|PCRE_EXTRA|PCRE_UNGREEDY|PCRE_UTF8| \ PCRE_NO_AUTO_CAPTURE|PCRE_NO_UTF8_CHECK|PCRE_AUTO_CALLOUT|PCRE_FIRSTLINE| \ PCRE_DUPNAMES|PCRE_NEWLINE_BITS|PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE| \ PCRE_JAVASCRIPT_COMPAT|PCRE_UCP|PCRE_NO_START_OPTIMIZE) #define PUBLIC_EXEC_OPTIONS \ (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NOTEMPTY_ATSTART| \ PCRE_NO_UTF8_CHECK|PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT|PCRE_NEWLINE_BITS| \ PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE|PCRE_NO_START_OPTIMIZE) #define PUBLIC_DFA_EXEC_OPTIONS \ (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NOTEMPTY_ATSTART| \ PCRE_NO_UTF8_CHECK|PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT|PCRE_DFA_SHORTEST| \ PCRE_DFA_RESTART|PCRE_NEWLINE_BITS|PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE| \ PCRE_NO_START_OPTIMIZE) #define PUBLIC_STUDY_OPTIONS \ PCRE_STUDY_JIT_COMPILE /* Magic number to provide a small check against being handed junk. */ #define MAGIC_NUMBER 0x50435245UL /* 'PCRE' */ /* This variable is used to detect a loaded regular expression in different endianness. */ #define REVERSED_MAGIC_NUMBER 0x45524350UL /* 'ERCP' */ /* Negative values for the firstchar and reqchar variables */ #define REQ_UNSET (-2) #define REQ_NONE (-1) /* The maximum remaining length of subject we are prepared to search for a req_byte match. */ #define REQ_BYTE_MAX 1000 /* Miscellaneous definitions. The #ifndef is to pacify compiler warnings in environments where these macros are defined elsewhere. Unfortunately, there is no way to do the same for the typedef. */ typedef int BOOL; #ifndef FALSE #define FALSE 0 #define TRUE 1 #endif /* If PCRE is to support UTF-8 on EBCDIC platforms, we cannot use normal character constants like '*' because the compiler would emit their EBCDIC code, which is different from their ASCII/UTF-8 code. Instead we define macros for the characters so that they always use the ASCII/UTF-8 code when UTF-8 support is enabled. When UTF-8 support is not enabled, the definitions use character literals. Both character and string versions of each character are needed, and there are some longer strings as well. This means that, on EBCDIC platforms, the PCRE library can handle either EBCDIC, or UTF-8, but not both. To support both in the same compiled library would need different lookups depending on whether PCRE_UTF8 was set or not. This would make it impossible to use characters in switch/case statements, which would reduce performance. For a theoretical use (which nobody has asked for) in a minority area (EBCDIC platforms), this is not sensible. Any application that did need both could compile two versions of the library, using macros to give the functions distinct names. */ #ifndef SUPPORT_UTF /* UTF-8 support is not enabled; use the platform-dependent character literals so that PCRE works on both ASCII and EBCDIC platforms, in non-UTF-mode only. */ #define CHAR_HT '\t' #define CHAR_VT '\v' #define CHAR_FF '\f' #define CHAR_CR '\r' #define CHAR_NL '\n' #define CHAR_BS '\b' #define CHAR_BEL '\a' #ifdef EBCDIC #define CHAR_ESC '\047' #define CHAR_DEL '\007' #else #define CHAR_ESC '\033' #define CHAR_DEL '\177' #endif #define CHAR_SPACE ' ' #define CHAR_EXCLAMATION_MARK '!' #define CHAR_QUOTATION_MARK '"' #define CHAR_NUMBER_SIGN '#' #define CHAR_DOLLAR_SIGN '$' #define CHAR_PERCENT_SIGN '%' #define CHAR_AMPERSAND '&' #define CHAR_APOSTROPHE '\'' #define CHAR_LEFT_PARENTHESIS '(' #define CHAR_RIGHT_PARENTHESIS ')' #define CHAR_ASTERISK '*' #define CHAR_PLUS '+' #define CHAR_COMMA ',' #define CHAR_MINUS '-' #define CHAR_DOT '.' #define CHAR_SLASH '/' #define CHAR_0 '0' #define CHAR_1 '1' #define CHAR_2 '2' #define CHAR_3 '3' #define CHAR_4 '4' #define CHAR_5 '5' #define CHAR_6 '6' #define CHAR_7 '7' #define CHAR_8 '8' #define CHAR_9 '9' #define CHAR_COLON ':' #define CHAR_SEMICOLON ';' #define CHAR_LESS_THAN_SIGN '<' #define CHAR_EQUALS_SIGN '=' #define CHAR_GREATER_THAN_SIGN '>' #define CHAR_QUESTION_MARK '?' #define CHAR_COMMERCIAL_AT '@' #define CHAR_A 'A' #define CHAR_B 'B' #define CHAR_C 'C' #define CHAR_D 'D' #define CHAR_E 'E' #define CHAR_F 'F' #define CHAR_G 'G' #define CHAR_H 'H' #define CHAR_I 'I' #define CHAR_J 'J' #define CHAR_K 'K' #define CHAR_L 'L' #define CHAR_M 'M' #define CHAR_N 'N' #define CHAR_O 'O' #define CHAR_P 'P' #define CHAR_Q 'Q' #define CHAR_R 'R' #define CHAR_S 'S' #define CHAR_T 'T' #define CHAR_U 'U' #define CHAR_V 'V' #define CHAR_W 'W' #define CHAR_X 'X' #define CHAR_Y 'Y' #define CHAR_Z 'Z' #define CHAR_LEFT_SQUARE_BRACKET '[' #define CHAR_BACKSLASH '\\' #define CHAR_RIGHT_SQUARE_BRACKET ']' #define CHAR_CIRCUMFLEX_ACCENT '^' #define CHAR_UNDERSCORE '_' #define CHAR_GRAVE_ACCENT '`' #define CHAR_a 'a' #define CHAR_b 'b' #define CHAR_c 'c' #define CHAR_d 'd' #define CHAR_e 'e' #define CHAR_f 'f' #define CHAR_g 'g' #define CHAR_h 'h' #define CHAR_i 'i' #define CHAR_j 'j' #define CHAR_k 'k' #define CHAR_l 'l' #define CHAR_m 'm' #define CHAR_n 'n' #define CHAR_o 'o' #define CHAR_p 'p' #define CHAR_q 'q' #define CHAR_r 'r' #define CHAR_s 's' #define CHAR_t 't' #define CHAR_u 'u' #define CHAR_v 'v' #define CHAR_w 'w' #define CHAR_x 'x' #define CHAR_y 'y' #define CHAR_z 'z' #define CHAR_LEFT_CURLY_BRACKET '{' #define CHAR_VERTICAL_LINE '|' #define CHAR_RIGHT_CURLY_BRACKET '}' #define CHAR_TILDE '~' #define STR_HT "\t" #define STR_VT "\v" #define STR_FF "\f" #define STR_CR "\r" #define STR_NL "\n" #define STR_BS "\b" #define STR_BEL "\a" #ifdef EBCDIC #define STR_ESC "\047" #define STR_DEL "\007" #else #define STR_ESC "\033" #define STR_DEL "\177" #endif #define STR_SPACE " " #define STR_EXCLAMATION_MARK "!" #define STR_QUOTATION_MARK "\"" #define STR_NUMBER_SIGN "#" #define STR_DOLLAR_SIGN "$" #define STR_PERCENT_SIGN "%" #define STR_AMPERSAND "&" #define STR_APOSTROPHE "'" #define STR_LEFT_PARENTHESIS "(" #define STR_RIGHT_PARENTHESIS ")" #define STR_ASTERISK "*" #define STR_PLUS "+" #define STR_COMMA "," #define STR_MINUS "-" #define STR_DOT "." #define STR_SLASH "/" #define STR_0 "0" #define STR_1 "1" #define STR_2 "2" #define STR_3 "3" #define STR_4 "4" #define STR_5 "5" #define STR_6 "6" #define STR_7 "7" #define STR_8 "8" #define STR_9 "9" #define STR_COLON ":" #define STR_SEMICOLON ";" #define STR_LESS_THAN_SIGN "<" #define STR_EQUALS_SIGN "=" #define STR_GREATER_THAN_SIGN ">" #define STR_QUESTION_MARK "?" #define STR_COMMERCIAL_AT "@" #define STR_A "A" #define STR_B "B" #define STR_C "C" #define STR_D "D" #define STR_E "E" #define STR_F "F" #define STR_G "G" #define STR_H "H" #define STR_I "I" #define STR_J "J" #define STR_K "K" #define STR_L "L" #define STR_M "M" #define STR_N "N" #define STR_O "O" #define STR_P "P" #define STR_Q "Q" #define STR_R "R" #define STR_S "S" #define STR_T "T" #define STR_U "U" #define STR_V "V" #define STR_W "W" #define STR_X "X" #define STR_Y "Y" #define STR_Z "Z" #define STR_LEFT_SQUARE_BRACKET "[" #define STR_BACKSLASH "\\" #define STR_RIGHT_SQUARE_BRACKET "]" #define STR_CIRCUMFLEX_ACCENT "^" #define STR_UNDERSCORE "_" #define STR_GRAVE_ACCENT "`" #define STR_a "a" #define STR_b "b" #define STR_c "c" #define STR_d "d" #define STR_e "e" #define STR_f "f" #define STR_g "g" #define STR_h "h" #define STR_i "i" #define STR_j "j" #define STR_k "k" #define STR_l "l" #define STR_m "m" #define STR_n "n" #define STR_o "o" #define STR_p "p" #define STR_q "q" #define STR_r "r" #define STR_s "s" #define STR_t "t" #define STR_u "u" #define STR_v "v" #define STR_w "w" #define STR_x "x" #define STR_y "y" #define STR_z "z" #define STR_LEFT_CURLY_BRACKET "{" #define STR_VERTICAL_LINE "|" #define STR_RIGHT_CURLY_BRACKET "}" #define STR_TILDE "~" #define STRING_ACCEPT0 "ACCEPT\0" #define STRING_COMMIT0 "COMMIT\0" #define STRING_F0 "F\0" #define STRING_FAIL0 "FAIL\0" #define STRING_MARK0 "MARK\0" #define STRING_PRUNE0 "PRUNE\0" #define STRING_SKIP0 "SKIP\0" #define STRING_THEN "THEN" #define STRING_alpha0 "alpha\0" #define STRING_lower0 "lower\0" #define STRING_upper0 "upper\0" #define STRING_alnum0 "alnum\0" #define STRING_ascii0 "ascii\0" #define STRING_blank0 "blank\0" #define STRING_cntrl0 "cntrl\0" #define STRING_digit0 "digit\0" #define STRING_graph0 "graph\0" #define STRING_print0 "print\0" #define STRING_punct0 "punct\0" #define STRING_space0 "space\0" #define STRING_word0 "word\0" #define STRING_xdigit "xdigit" #define STRING_DEFINE "DEFINE" #define STRING_CR_RIGHTPAR "CR)" #define STRING_LF_RIGHTPAR "LF)" #define STRING_CRLF_RIGHTPAR "CRLF)" #define STRING_ANY_RIGHTPAR "ANY)" #define STRING_ANYCRLF_RIGHTPAR "ANYCRLF)" #define STRING_BSR_ANYCRLF_RIGHTPAR "BSR_ANYCRLF)" #define STRING_BSR_UNICODE_RIGHTPAR "BSR_UNICODE)" #ifdef COMPILE_PCRE8 #define STRING_UTF_RIGHTPAR "UTF8)" #endif #ifdef COMPILE_PCRE16 #define STRING_UTF_RIGHTPAR "UTF16)" #endif #define STRING_UCP_RIGHTPAR "UCP)" #define STRING_NO_START_OPT_RIGHTPAR "NO_START_OPT)" #else /* SUPPORT_UTF */ /* UTF-8 support is enabled; always use UTF-8 (=ASCII) character codes. This works in both modes non-EBCDIC platforms, and on EBCDIC platforms in UTF-8 mode only. */ #define CHAR_HT '\011' #define CHAR_VT '\013' #define CHAR_FF '\014' #define CHAR_CR '\015' #define CHAR_NL '\012' #define CHAR_BS '\010' #define CHAR_BEL '\007' #define CHAR_ESC '\033' #define CHAR_DEL '\177' #define CHAR_SPACE '\040' #define CHAR_EXCLAMATION_MARK '\041' #define CHAR_QUOTATION_MARK '\042' #define CHAR_NUMBER_SIGN '\043' #define CHAR_DOLLAR_SIGN '\044' #define CHAR_PERCENT_SIGN '\045' #define CHAR_AMPERSAND '\046' #define CHAR_APOSTROPHE '\047' #define CHAR_LEFT_PARENTHESIS '\050' #define CHAR_RIGHT_PARENTHESIS '\051' #define CHAR_ASTERISK '\052' #define CHAR_PLUS '\053' #define CHAR_COMMA '\054' #define CHAR_MINUS '\055' #define CHAR_DOT '\056' #define CHAR_SLASH '\057' #define CHAR_0 '\060' #define CHAR_1 '\061' #define CHAR_2 '\062' #define CHAR_3 '\063' #define CHAR_4 '\064' #define CHAR_5 '\065' #define CHAR_6 '\066' #define CHAR_7 '\067' #define CHAR_8 '\070' #define CHAR_9 '\071' #define CHAR_COLON '\072' #define CHAR_SEMICOLON '\073' #define CHAR_LESS_THAN_SIGN '\074' #define CHAR_EQUALS_SIGN '\075' #define CHAR_GREATER_THAN_SIGN '\076' #define CHAR_QUESTION_MARK '\077' #define CHAR_COMMERCIAL_AT '\100' #define CHAR_A '\101' #define CHAR_B '\102' #define CHAR_C '\103' #define CHAR_D '\104' #define CHAR_E '\105' #define CHAR_F '\106' #define CHAR_G '\107' #define CHAR_H '\110' #define CHAR_I '\111' #define CHAR_J '\112' #define CHAR_K '\113' #define CHAR_L '\114' #define CHAR_M '\115' #define CHAR_N '\116' #define CHAR_O '\117' #define CHAR_P '\120' #define CHAR_Q '\121' #define CHAR_R '\122' #define CHAR_S '\123' #define CHAR_T '\124' #define CHAR_U '\125' #define CHAR_V '\126' #define CHAR_W '\127' #define CHAR_X '\130' #define CHAR_Y '\131' #define CHAR_Z '\132' #define CHAR_LEFT_SQUARE_BRACKET '\133' #define CHAR_BACKSLASH '\134' #define CHAR_RIGHT_SQUARE_BRACKET '\135' #define CHAR_CIRCUMFLEX_ACCENT '\136' #define CHAR_UNDERSCORE '\137' #define CHAR_GRAVE_ACCENT '\140' #define CHAR_a '\141' #define CHAR_b '\142' #define CHAR_c '\143' #define CHAR_d '\144' #define CHAR_e '\145' #define CHAR_f '\146' #define CHAR_g '\147' #define CHAR_h '\150' #define CHAR_i '\151' #define CHAR_j '\152' #define CHAR_k '\153' #define CHAR_l '\154' #define CHAR_m '\155' #define CHAR_n '\156' #define CHAR_o '\157' #define CHAR_p '\160' #define CHAR_q '\161' #define CHAR_r '\162' #define CHAR_s '\163' #define CHAR_t '\164' #define CHAR_u '\165' #define CHAR_v '\166' #define CHAR_w '\167' #define CHAR_x '\170' #define CHAR_y '\171' #define CHAR_z '\172' #define CHAR_LEFT_CURLY_BRACKET '\173' #define CHAR_VERTICAL_LINE '\174' #define CHAR_RIGHT_CURLY_BRACKET '\175' #define CHAR_TILDE '\176' #define STR_HT "\011" #define STR_VT "\013" #define STR_FF "\014" #define STR_CR "\015" #define STR_NL "\012" #define STR_BS "\010" #define STR_BEL "\007" #define STR_ESC "\033" #define STR_DEL "\177" #define STR_SPACE "\040" #define STR_EXCLAMATION_MARK "\041" #define STR_QUOTATION_MARK "\042" #define STR_NUMBER_SIGN "\043" #define STR_DOLLAR_SIGN "\044" #define STR_PERCENT_SIGN "\045" #define STR_AMPERSAND "\046" #define STR_APOSTROPHE "\047" #define STR_LEFT_PARENTHESIS "\050" #define STR_RIGHT_PARENTHESIS "\051" #define STR_ASTERISK "\052" #define STR_PLUS "\053" #define STR_COMMA "\054" #define STR_MINUS "\055" #define STR_DOT "\056" #define STR_SLASH "\057" #define STR_0 "\060" #define STR_1 "\061" #define STR_2 "\062" #define STR_3 "\063" #define STR_4 "\064" #define STR_5 "\065" #define STR_6 "\066" #define STR_7 "\067" #define STR_8 "\070" #define STR_9 "\071" #define STR_COLON "\072" #define STR_SEMICOLON "\073" #define STR_LESS_THAN_SIGN "\074" #define STR_EQUALS_SIGN "\075" #define STR_GREATER_THAN_SIGN "\076" #define STR_QUESTION_MARK "\077" #define STR_COMMERCIAL_AT "\100" #define STR_A "\101" #define STR_B "\102" #define STR_C "\103" #define STR_D "\104" #define STR_E "\105" #define STR_F "\106" #define STR_G "\107" #define STR_H "\110" #define STR_I "\111" #define STR_J "\112" #define STR_K "\113" #define STR_L "\114" #define STR_M "\115" #define STR_N "\116" #define STR_O "\117" #define STR_P "\120" #define STR_Q "\121" #define STR_R "\122" #define STR_S "\123" #define STR_T "\124" #define STR_U "\125" #define STR_V "\126" #define STR_W "\127" #define STR_X "\130" #define STR_Y "\131" #define STR_Z "\132" #define STR_LEFT_SQUARE_BRACKET "\133" #define STR_BACKSLASH "\134" #define STR_RIGHT_SQUARE_BRACKET "\135" #define STR_CIRCUMFLEX_ACCENT "\136" #define STR_UNDERSCORE "\137" #define STR_GRAVE_ACCENT "\140" #define STR_a "\141" #define STR_b "\142" #define STR_c "\143" #define STR_d "\144" #define STR_e "\145" #define STR_f "\146" #define STR_g "\147" #define STR_h "\150" #define STR_i "\151" #define STR_j "\152" #define STR_k "\153" #define STR_l "\154" #define STR_m "\155" #define STR_n "\156" #define STR_o "\157" #define STR_p "\160" #define STR_q "\161" #define STR_r "\162" #define STR_s "\163" #define STR_t "\164" #define STR_u "\165" #define STR_v "\166" #define STR_w "\167" #define STR_x "\170" #define STR_y "\171" #define STR_z "\172" #define STR_LEFT_CURLY_BRACKET "\173" #define STR_VERTICAL_LINE "\174" #define STR_RIGHT_CURLY_BRACKET "\175" #define STR_TILDE "\176" #define STRING_ACCEPT0 STR_A STR_C STR_C STR_E STR_P STR_T "\0" #define STRING_COMMIT0 STR_C STR_O STR_M STR_M STR_I STR_T "\0" #define STRING_F0 STR_F "\0" #define STRING_FAIL0 STR_F STR_A STR_I STR_L "\0" #define STRING_MARK0 STR_M STR_A STR_R STR_K "\0" #define STRING_PRUNE0 STR_P STR_R STR_U STR_N STR_E "\0" #define STRING_SKIP0 STR_S STR_K STR_I STR_P "\0" #define STRING_THEN STR_T STR_H STR_E STR_N #define STRING_alpha0 STR_a STR_l STR_p STR_h STR_a "\0" #define STRING_lower0 STR_l STR_o STR_w STR_e STR_r "\0" #define STRING_upper0 STR_u STR_p STR_p STR_e STR_r "\0" #define STRING_alnum0 STR_a STR_l STR_n STR_u STR_m "\0" #define STRING_ascii0 STR_a STR_s STR_c STR_i STR_i "\0" #define STRING_blank0 STR_b STR_l STR_a STR_n STR_k "\0" #define STRING_cntrl0 STR_c STR_n STR_t STR_r STR_l "\0" #define STRING_digit0 STR_d STR_i STR_g STR_i STR_t "\0" #define STRING_graph0 STR_g STR_r STR_a STR_p STR_h "\0" #define STRING_print0 STR_p STR_r STR_i STR_n STR_t "\0" #define STRING_punct0 STR_p STR_u STR_n STR_c STR_t "\0" #define STRING_space0 STR_s STR_p STR_a STR_c STR_e "\0" #define STRING_word0 STR_w STR_o STR_r STR_d "\0" #define STRING_xdigit STR_x STR_d STR_i STR_g STR_i STR_t #define STRING_DEFINE STR_D STR_E STR_F STR_I STR_N STR_E #define STRING_CR_RIGHTPAR STR_C STR_R STR_RIGHT_PARENTHESIS #define STRING_LF_RIGHTPAR STR_L STR_F STR_RIGHT_PARENTHESIS #define STRING_CRLF_RIGHTPAR STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS #define STRING_ANY_RIGHTPAR STR_A STR_N STR_Y STR_RIGHT_PARENTHESIS #define STRING_ANYCRLF_RIGHTPAR STR_A STR_N STR_Y STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS #define STRING_BSR_ANYCRLF_RIGHTPAR STR_B STR_S STR_R STR_UNDERSCORE STR_A STR_N STR_Y STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS #define STRING_BSR_UNICODE_RIGHTPAR STR_B STR_S STR_R STR_UNDERSCORE STR_U STR_N STR_I STR_C STR_O STR_D STR_E STR_RIGHT_PARENTHESIS #ifdef COMPILE_PCRE8 #define STRING_UTF_RIGHTPAR STR_U STR_T STR_F STR_8 STR_RIGHT_PARENTHESIS #endif #ifdef COMPILE_PCRE16 #define STRING_UTF_RIGHTPAR STR_U STR_T STR_F STR_1 STR_6 STR_RIGHT_PARENTHESIS #endif #define STRING_UCP_RIGHTPAR STR_U STR_C STR_P STR_RIGHT_PARENTHESIS #define STRING_NO_START_OPT_RIGHTPAR STR_N STR_O STR_UNDERSCORE STR_S STR_T STR_A STR_R STR_T STR_UNDERSCORE STR_O STR_P STR_T STR_RIGHT_PARENTHESIS #endif /* SUPPORT_UTF */ /* Escape items that are just an encoding of a particular data value. */ #ifndef ESC_e #define ESC_e CHAR_ESC #endif #ifndef ESC_f #define ESC_f CHAR_FF #endif #ifndef ESC_n #define ESC_n CHAR_NL #endif #ifndef ESC_r #define ESC_r CHAR_CR #endif /* We can't officially use ESC_t because it is a POSIX reserved identifier (presumably because of all the others like size_t). */ #ifndef ESC_tee #define ESC_tee CHAR_HT #endif /* Codes for different types of Unicode property */ #define PT_ANY 0 /* Any property - matches all chars */ #define PT_LAMP 1 /* L& - the union of Lu, Ll, Lt */ #define PT_GC 2 /* Specified general characteristic (e.g. L) */ #define PT_PC 3 /* Specified particular characteristic (e.g. Lu) */ #define PT_SC 4 /* Script (e.g. Han) */ #define PT_ALNUM 5 /* Alphanumeric - the union of L and N */ #define PT_SPACE 6 /* Perl space - Z plus 9,10,12,13 */ #define PT_PXSPACE 7 /* POSIX space - Z plus 9,10,11,12,13 */ #define PT_WORD 8 /* Word - L plus N plus underscore */ /* Flag bits and data types for the extended class (OP_XCLASS) for classes that contain characters with values greater than 255. */ #define XCL_NOT 0x01 /* Flag: this is a negative class */ #define XCL_MAP 0x02 /* Flag: a 32-byte map is present */ #define XCL_END 0 /* Marks end of individual items */ #define XCL_SINGLE 1 /* Single item (one multibyte char) follows */ #define XCL_RANGE 2 /* A range (two multibyte chars) follows */ #define XCL_PROP 3 /* Unicode property (2-byte property code follows) */ #define XCL_NOTPROP 4 /* Unicode inverted property (ditto) */ /* These are escaped items that aren't just an encoding of a particular data value such as \n. They must have non-zero values, as check_escape() returns their negation. Also, they must appear in the same order as in the opcode definitions below, up to ESC_z. There's a dummy for OP_ALLANY because it corresponds to "." in DOTALL mode rather than an escape sequence. It is also used for [^] in JavaScript compatibility mode, and for \C in non-utf mode. In non-DOTALL mode, "." behaves like \N. The special values ESC_DU, ESC_du, etc. are used instead of ESC_D, ESC_d, etc. when PCRE_UCP is set, when replacement of \d etc by \p sequences is required. They must be contiguous, and remain in order so that the replacements can be looked up from a table. The final escape must be ESC_REF as subsequent values are used for backreferences (\1, \2, \3, etc). There are two tests in the code for an escape greater than ESC_b and less than ESC_Z to detect the types that may be repeated. These are the types that consume characters. If any new escapes are put in between that don't consume a character, that code will have to change. */ enum { ESC_A = 1, ESC_G, ESC_K, ESC_B, ESC_b, ESC_D, ESC_d, ESC_S, ESC_s, ESC_W, ESC_w, ESC_N, ESC_dum, ESC_C, ESC_P, ESC_p, ESC_R, ESC_H, ESC_h, ESC_V, ESC_v, ESC_X, ESC_Z, ESC_z, ESC_E, ESC_Q, ESC_g, ESC_k, ESC_DU, ESC_du, ESC_SU, ESC_su, ESC_WU, ESC_wu, ESC_REF }; /* Opcode table: Starting from 1 (i.e. after OP_END), the values up to OP_EOD must correspond in order to the list of escapes immediately above. *** NOTE NOTE NOTE *** Whenever this list is updated, the two macro definitions that follow must also be updated to match. There are also tables called "coptable" and "poptable" in pcre_dfa_exec.c that must be updated. */ enum { OP_END, /* 0 End of pattern */ /* Values corresponding to backslashed metacharacters */ OP_SOD, /* 1 Start of data: \A */ OP_SOM, /* 2 Start of match (subject + offset): \G */ OP_SET_SOM, /* 3 Set start of match (\K) */ OP_NOT_WORD_BOUNDARY, /* 4 \B */ OP_WORD_BOUNDARY, /* 5 \b */ OP_NOT_DIGIT, /* 6 \D */ OP_DIGIT, /* 7 \d */ OP_NOT_WHITESPACE, /* 8 \S */ OP_WHITESPACE, /* 9 \s */ OP_NOT_WORDCHAR, /* 10 \W */ OP_WORDCHAR, /* 11 \w */ OP_ANY, /* 12 Match any character except newline */ OP_ALLANY, /* 13 Match any character */ OP_ANYBYTE, /* 14 Match any byte (\C); different to OP_ANY for UTF-8 */ OP_NOTPROP, /* 15 \P (not Unicode property) */ OP_PROP, /* 16 \p (Unicode property) */ OP_ANYNL, /* 17 \R (any newline sequence) */ OP_NOT_HSPACE, /* 18 \H (not horizontal whitespace) */ OP_HSPACE, /* 19 \h (horizontal whitespace) */ OP_NOT_VSPACE, /* 20 \V (not vertical whitespace) */ OP_VSPACE, /* 21 \v (vertical whitespace) */ OP_EXTUNI, /* 22 \X (extended Unicode sequence */ OP_EODN, /* 23 End of data or \n at end of data: \Z. */ OP_EOD, /* 24 End of data: \z */ OP_CIRC, /* 25 Start of line - not multiline */ OP_CIRCM, /* 26 Start of line - multiline */ OP_DOLL, /* 27 End of line - not multiline */ OP_DOLLM, /* 28 End of line - multiline */ OP_CHAR, /* 29 Match one character, casefully */ OP_CHARI, /* 30 Match one character, caselessly */ OP_NOT, /* 31 Match one character, not the given one, casefully */ OP_NOTI, /* 32 Match one character, not the given one, caselessly */ /* The following sets of 13 opcodes must always be kept in step because the offset from the first one is used to generate the others. */ /**** Single characters, caseful, must precede the caseless ones ****/ OP_STAR, /* 33 The maximizing and minimizing versions of */ OP_MINSTAR, /* 34 these six opcodes must come in pairs, with */ OP_PLUS, /* 35 the minimizing one second. */ OP_MINPLUS, /* 36 */ OP_QUERY, /* 37 */ OP_MINQUERY, /* 38 */ OP_UPTO, /* 39 From 0 to n matches of one character, caseful*/ OP_MINUPTO, /* 40 */ OP_EXACT, /* 41 Exactly n matches */ OP_POSSTAR, /* 42 Possessified star, caseful */ OP_POSPLUS, /* 43 Possessified plus, caseful */ OP_POSQUERY, /* 44 Posesssified query, caseful */ OP_POSUPTO, /* 45 Possessified upto, caseful */ /**** Single characters, caseless, must follow the caseful ones */ OP_STARI, /* 46 */ OP_MINSTARI, /* 47 */ OP_PLUSI, /* 48 */ OP_MINPLUSI, /* 49 */ OP_QUERYI, /* 50 */ OP_MINQUERYI, /* 51 */ OP_UPTOI, /* 52 From 0 to n matches of one character, caseless */ OP_MINUPTOI, /* 53 */ OP_EXACTI, /* 54 */ OP_POSSTARI, /* 55 Possessified star, caseless */ OP_POSPLUSI, /* 56 Possessified plus, caseless */ OP_POSQUERYI, /* 57 Posesssified query, caseless */ OP_POSUPTOI, /* 58 Possessified upto, caseless */ /**** The negated ones must follow the non-negated ones, and match them ****/ /**** Negated single character, caseful; must precede the caseless ones ****/ OP_NOTSTAR, /* 59 The maximizing and minimizing versions of */ OP_NOTMINSTAR, /* 60 these six opcodes must come in pairs, with */ OP_NOTPLUS, /* 61 the minimizing one second. They must be in */ OP_NOTMINPLUS, /* 62 exactly the same order as those above. */ OP_NOTQUERY, /* 63 */ OP_NOTMINQUERY, /* 64 */ OP_NOTUPTO, /* 65 From 0 to n matches, caseful */ OP_NOTMINUPTO, /* 66 */ OP_NOTEXACT, /* 67 Exactly n matches */ OP_NOTPOSSTAR, /* 68 Possessified versions, caseful */ OP_NOTPOSPLUS, /* 69 */ OP_NOTPOSQUERY, /* 70 */ OP_NOTPOSUPTO, /* 71 */ /**** Negated single character, caseless; must follow the caseful ones ****/ OP_NOTSTARI, /* 72 */ OP_NOTMINSTARI, /* 73 */ OP_NOTPLUSI, /* 74 */ OP_NOTMINPLUSI, /* 75 */ OP_NOTQUERYI, /* 76 */ OP_NOTMINQUERYI, /* 77 */ OP_NOTUPTOI, /* 78 From 0 to n matches, caseless */ OP_NOTMINUPTOI, /* 79 */ OP_NOTEXACTI, /* 80 Exactly n matches */ OP_NOTPOSSTARI, /* 81 Possessified versions, caseless */ OP_NOTPOSPLUSI, /* 82 */ OP_NOTPOSQUERYI, /* 83 */ OP_NOTPOSUPTOI, /* 84 */ /**** Character types ****/ OP_TYPESTAR, /* 85 The maximizing and minimizing versions of */ OP_TYPEMINSTAR, /* 86 these six opcodes must come in pairs, with */ OP_TYPEPLUS, /* 87 the minimizing one second. These codes must */ OP_TYPEMINPLUS, /* 88 be in exactly the same order as those above. */ OP_TYPEQUERY, /* 89 */ OP_TYPEMINQUERY, /* 90 */ OP_TYPEUPTO, /* 91 From 0 to n matches */ OP_TYPEMINUPTO, /* 92 */ OP_TYPEEXACT, /* 93 Exactly n matches */ OP_TYPEPOSSTAR, /* 94 Possessified versions */ OP_TYPEPOSPLUS, /* 95 */ OP_TYPEPOSQUERY, /* 96 */ OP_TYPEPOSUPTO, /* 97 */ /* These are used for character classes and back references; only the first six are the same as the sets above. */ OP_CRSTAR, /* 98 The maximizing and minimizing versions of */ OP_CRMINSTAR, /* 99 all these opcodes must come in pairs, with */ OP_CRPLUS, /* 100 the minimizing one second. These codes must */ OP_CRMINPLUS, /* 101 be in exactly the same order as those above. */ OP_CRQUERY, /* 102 */ OP_CRMINQUERY, /* 103 */ OP_CRRANGE, /* 104 These are different to the three sets above. */ OP_CRMINRANGE, /* 105 */ /* End of quantifier opcodes */ OP_CLASS, /* 106 Match a character class, chars < 256 only */ OP_NCLASS, /* 107 Same, but the bitmap was created from a negative class - the difference is relevant only when a character > 255 is encountered. */ OP_XCLASS, /* 108 Extended class for handling > 255 chars within the class. This does both positive and negative. */ OP_REF, /* 109 Match a back reference, casefully */ OP_REFI, /* 110 Match a back reference, caselessly */ OP_RECURSE, /* 111 Match a numbered subpattern (possibly recursive) */ OP_CALLOUT, /* 112 Call out to external function if provided */ OP_ALT, /* 113 Start of alternation */ OP_KET, /* 114 End of group that doesn't have an unbounded repeat */ OP_KETRMAX, /* 115 These two must remain together and in this */ OP_KETRMIN, /* 116 order. They are for groups the repeat for ever. */ OP_KETRPOS, /* 117 Possessive unlimited repeat. */ /* The assertions must come before BRA, CBRA, ONCE, and COND, and the four asserts must remain in order. */ OP_REVERSE, /* 118 Move pointer back - used in lookbehind assertions */ OP_ASSERT, /* 119 Positive lookahead */ OP_ASSERT_NOT, /* 120 Negative lookahead */ OP_ASSERTBACK, /* 121 Positive lookbehind */ OP_ASSERTBACK_NOT, /* 122 Negative lookbehind */ /* ONCE, ONCE_NC, BRA, BRAPOS, CBRA, CBRAPOS, and COND must come immediately after the assertions, with ONCE first, as there's a test for >= ONCE for a subpattern that isn't an assertion. The POS versions must immediately follow the non-POS versions in each case. */ OP_ONCE, /* 123 Atomic group, contains captures */ OP_ONCE_NC, /* 124 Atomic group containing no captures */ OP_BRA, /* 125 Start of non-capturing bracket */ OP_BRAPOS, /* 126 Ditto, with unlimited, possessive repeat */ OP_CBRA, /* 127 Start of capturing bracket */ OP_CBRAPOS, /* 128 Ditto, with unlimited, possessive repeat */ OP_COND, /* 129 Conditional group */ /* These five must follow the previous five, in the same order. There's a check for >= SBRA to distinguish the two sets. */ OP_SBRA, /* 130 Start of non-capturing bracket, check empty */ OP_SBRAPOS, /* 131 Ditto, with unlimited, possessive repeat */ OP_SCBRA, /* 132 Start of capturing bracket, check empty */ OP_SCBRAPOS, /* 133 Ditto, with unlimited, possessive repeat */ OP_SCOND, /* 134 Conditional group, check empty */ /* The next two pairs must (respectively) be kept together. */ OP_CREF, /* 135 Used to hold a capture number as condition */ OP_NCREF, /* 136 Same, but generated by a name reference*/ OP_RREF, /* 137 Used to hold a recursion number as condition */ OP_NRREF, /* 138 Same, but generated by a name reference*/ OP_DEF, /* 139 The DEFINE condition */ OP_BRAZERO, /* 140 These two must remain together and in this */ OP_BRAMINZERO, /* 141 order. */ OP_BRAPOSZERO, /* 142 */ /* These are backtracking control verbs */ OP_MARK, /* 143 always has an argument */ OP_PRUNE, /* 144 */ OP_PRUNE_ARG, /* 145 same, but with argument */ OP_SKIP, /* 146 */ OP_SKIP_ARG, /* 147 same, but with argument */ OP_THEN, /* 148 */ OP_THEN_ARG, /* 149 same, but with argument */ OP_COMMIT, /* 150 */ /* These are forced failure and success verbs */ OP_FAIL, /* 151 */ OP_ACCEPT, /* 152 */ OP_ASSERT_ACCEPT, /* 153 Used inside assertions */ OP_CLOSE, /* 154 Used before OP_ACCEPT to close open captures */ /* This is used to skip a subpattern with a {0} quantifier */ OP_SKIPZERO, /* 155 */ /* This is not an opcode, but is used to check that tables indexed by opcode are the correct length, in order to catch updating errors - there have been some in the past. */ OP_TABLE_LENGTH }; /* *** NOTE NOTE NOTE *** Whenever the list above is updated, the two macro definitions that follow must also be updated to match. There are also tables called "coptable" and "poptable" in pcre_dfa_exec.c that must be updated. */ /* This macro defines textual names for all the opcodes. These are used only for debugging, and some of them are only partial names. The macro is referenced only in pcre_printint.c, which fills out the full names in many cases (and in some cases doesn't actually use these names at all). */ #define OP_NAME_LIST \ "End", "\\A", "\\G", "\\K", "\\B", "\\b", "\\D", "\\d", \ "\\S", "\\s", "\\W", "\\w", "Any", "AllAny", "Anybyte", \ "notprop", "prop", "\\R", "\\H", "\\h", "\\V", "\\v", \ "extuni", "\\Z", "\\z", \ "^", "^", "$", "$", "char", "chari", "not", "noti", \ "*", "*?", "+", "+?", "?", "??", \ "{", "{", "{", \ "*+","++", "?+", "{", \ "*", "*?", "+", "+?", "?", "??", \ "{", "{", "{", \ "*+","++", "?+", "{", \ "*", "*?", "+", "+?", "?", "??", \ "{", "{", "{", \ "*+","++", "?+", "{", \ "*", "*?", "+", "+?", "?", "??", \ "{", "{", "{", \ "*+","++", "?+", "{", \ "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ "*+","++", "?+", "{", \ "*", "*?", "+", "+?", "?", "??", "{", "{", \ "class", "nclass", "xclass", "Ref", "Refi", \ "Recurse", "Callout", \ "Alt", "Ket", "KetRmax", "KetRmin", "KetRpos", \ "Reverse", "Assert", "Assert not", "AssertB", "AssertB not", \ "Once", "Once_NC", \ "Bra", "BraPos", "CBra", "CBraPos", \ "Cond", \ "SBra", "SBraPos", "SCBra", "SCBraPos", \ "SCond", \ "Cond ref", "Cond nref", "Cond rec", "Cond nrec", "Cond def", \ "Brazero", "Braminzero", "Braposzero", \ "*MARK", "*PRUNE", "*PRUNE", "*SKIP", "*SKIP", \ "*THEN", "*THEN", "*COMMIT", "*FAIL", \ "*ACCEPT", "*ASSERT_ACCEPT", \ "Close", "Skip zero" /* This macro defines the length of fixed length operations in the compiled regex. The lengths are used when searching for specific things, and also in the debugging printing of a compiled regex. We use a macro so that it can be defined close to the definitions of the opcodes themselves. As things have been extended, some of these are no longer fixed lenths, but are minima instead. For example, the length of a single-character repeat may vary in UTF-8 mode. The code that uses this table must know about such things. */ #define OP_LENGTHS \ 1, /* End */ \ 1, 1, 1, 1, 1, /* \A, \G, \K, \B, \b */ \ 1, 1, 1, 1, 1, 1, /* \D, \d, \S, \s, \W, \w */ \ 1, 1, 1, /* Any, AllAny, Anybyte */ \ 3, 3, /* \P, \p */ \ 1, 1, 1, 1, 1, /* \R, \H, \h, \V, \v */ \ 1, /* \X */ \ 1, 1, 1, 1, 1, 1, /* \Z, \z, ^, ^M, $, $M */ \ 2, /* Char - the minimum length */ \ 2, /* Chari - the minimum length */ \ 2, /* not */ \ 2, /* noti */ \ /* Positive single-char repeats ** These are */ \ 2, 2, 2, 2, 2, 2, /* *, *?, +, +?, ?, ?? ** minima in */ \ 2+IMM2_SIZE, 2+IMM2_SIZE, /* upto, minupto ** mode */ \ 2+IMM2_SIZE, /* exact */ \ 2, 2, 2, 2+IMM2_SIZE, /* *+, ++, ?+, upto+ */ \ 2, 2, 2, 2, 2, 2, /* *I, *?I, +I, +?I, ?I, ??I ** UTF-8 */ \ 2+IMM2_SIZE, 2+IMM2_SIZE, /* upto I, minupto I */ \ 2+IMM2_SIZE, /* exact I */ \ 2, 2, 2, 2+IMM2_SIZE, /* *+I, ++I, ?+I, upto+I */ \ /* Negative single-char repeats - only for chars < 256 */ \ 2, 2, 2, 2, 2, 2, /* NOT *, *?, +, +?, ?, ?? */ \ 2+IMM2_SIZE, 2+IMM2_SIZE, /* NOT upto, minupto */ \ 2+IMM2_SIZE, /* NOT exact */ \ 2, 2, 2, 2+IMM2_SIZE, /* Possessive NOT *, +, ?, upto */ \ 2, 2, 2, 2, 2, 2, /* NOT *I, *?I, +I, +?I, ?I, ??I */ \ 2+IMM2_SIZE, 2+IMM2_SIZE, /* NOT upto I, minupto I */ \ 2+IMM2_SIZE, /* NOT exact I */ \ 2, 2, 2, 2+IMM2_SIZE, /* Possessive NOT *I, +I, ?I, upto I */ \ /* Positive type repeats */ \ 2, 2, 2, 2, 2, 2, /* Type *, *?, +, +?, ?, ?? */ \ 2+IMM2_SIZE, 2+IMM2_SIZE, /* Type upto, minupto */ \ 2+IMM2_SIZE, /* Type exact */ \ 2, 2, 2, 2+IMM2_SIZE, /* Possessive *+, ++, ?+, upto+ */ \ /* Character class & ref repeats */ \ 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ \ 1+2*IMM2_SIZE, 1+2*IMM2_SIZE, /* CRRANGE, CRMINRANGE */ \ 1+(32/sizeof(pcre_uchar)), /* CLASS */ \ 1+(32/sizeof(pcre_uchar)), /* NCLASS */ \ 0, /* XCLASS - variable length */ \ 1+IMM2_SIZE, /* REF */ \ 1+IMM2_SIZE, /* REFI */ \ 1+LINK_SIZE, /* RECURSE */ \ 4+2*LINK_SIZE, /* CALLOUT */ \ 1+LINK_SIZE, /* Alt */ \ 1+LINK_SIZE, /* Ket */ \ 1+LINK_SIZE, /* KetRmax */ \ 1+LINK_SIZE, /* KetRmin */ \ 1+LINK_SIZE, /* KetRpos */ \ 1+LINK_SIZE, /* Reverse */ \ 1+LINK_SIZE, /* Assert */ \ 1+LINK_SIZE, /* Assert not */ \ 1+LINK_SIZE, /* Assert behind */ \ 1+LINK_SIZE, /* Assert behind not */ \ 1+LINK_SIZE, /* ONCE */ \ 1+LINK_SIZE, /* ONCE_NC */ \ 1+LINK_SIZE, /* BRA */ \ 1+LINK_SIZE, /* BRAPOS */ \ 1+LINK_SIZE+IMM2_SIZE, /* CBRA */ \ 1+LINK_SIZE+IMM2_SIZE, /* CBRAPOS */ \ 1+LINK_SIZE, /* COND */ \ 1+LINK_SIZE, /* SBRA */ \ 1+LINK_SIZE, /* SBRAPOS */ \ 1+LINK_SIZE+IMM2_SIZE, /* SCBRA */ \ 1+LINK_SIZE+IMM2_SIZE, /* SCBRAPOS */ \ 1+LINK_SIZE, /* SCOND */ \ 1+IMM2_SIZE, 1+IMM2_SIZE, /* CREF, NCREF */ \ 1+IMM2_SIZE, 1+IMM2_SIZE, /* RREF, NRREF */ \ 1, /* DEF */ \ 1, 1, 1, /* BRAZERO, BRAMINZERO, BRAPOSZERO */ \ 3, 1, 3, /* MARK, PRUNE, PRUNE_ARG */ \ 1, 3, /* SKIP, SKIP_ARG */ \ 1, 3, /* THEN, THEN_ARG */ \ 1, 1, 1, 1, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */ \ 1+IMM2_SIZE, 1 /* CLOSE, SKIPZERO */ /* A magic value for OP_RREF and OP_NRREF to indicate the "any recursion" condition. */ #define RREF_ANY 0xffff /* Compile time error code numbers. They are given names so that they can more easily be tracked. When a new number is added, the table called eint in pcreposix.c must be updated. */ enum { ERR0, ERR1, ERR2, ERR3, ERR4, ERR5, ERR6, ERR7, ERR8, ERR9, ERR10, ERR11, ERR12, ERR13, ERR14, ERR15, ERR16, ERR17, ERR18, ERR19, ERR20, ERR21, ERR22, ERR23, ERR24, ERR25, ERR26, ERR27, ERR28, ERR29, ERR30, ERR31, ERR32, ERR33, ERR34, ERR35, ERR36, ERR37, ERR38, ERR39, ERR40, ERR41, ERR42, ERR43, ERR44, ERR45, ERR46, ERR47, ERR48, ERR49, ERR50, ERR51, ERR52, ERR53, ERR54, ERR55, ERR56, ERR57, ERR58, ERR59, ERR60, ERR61, ERR62, ERR63, ERR64, ERR65, ERR66, ERR67, ERR68, ERR69, ERR70, ERR71, ERR72, ERR73, ERR74, ERRCOUNT }; /* The real format of the start of the pcre block; the index of names and the code vector run on as long as necessary after the end. We store an explicit offset to the name table so that if a regex is compiled on one host, saved, and then run on another where the size of pointers is different, all might still be well. For the case of compiled-on-4 and run-on-8, we include an extra pointer that is always NULL. For future-proofing, a few dummy fields were originally included - even though you can never get this planning right - but there is only one left now. NOTE NOTE NOTE: Because people can now save and re-use compiled patterns, any additions to this structure should be made at the end, and something earlier (e.g. a new flag in the options or one of the dummy fields) should indicate that the new fields are present. Currently PCRE always sets the dummy fields to zero. NOTE NOTE NOTE */ #ifdef COMPILE_PCRE8 #define REAL_PCRE real_pcre #else #define REAL_PCRE real_pcre16 #endif typedef struct REAL_PCRE { pcre_uint32 magic_number; pcre_uint32 size; /* Total that was malloced */ pcre_uint32 options; /* Public options */ pcre_uint16 flags; /* Private flags */ pcre_uint16 dummy1; /* For future use */ pcre_uint16 top_bracket; pcre_uint16 top_backref; pcre_uint16 first_char; /* Starting character */ pcre_uint16 req_char; /* This character must be seen */ pcre_uint16 name_table_offset; /* Offset to name table that follows */ pcre_uint16 name_entry_size; /* Size of any name items */ pcre_uint16 name_count; /* Number of name items */ pcre_uint16 ref_count; /* Reference count */ const pcre_uint8 *tables; /* Pointer to tables or NULL for std */ const pcre_uint8 *nullpad; /* NULL padding */ } REAL_PCRE; /* The format of the block used to store data from pcre_study(). The same remark (see NOTE above) about extending this structure applies. */ typedef struct pcre_study_data { pcre_uint32 size; /* Total that was malloced */ pcre_uint32 flags; /* Private flags */ pcre_uint8 start_bits[32]; /* Starting char bits */ pcre_uint32 minlength; /* Minimum subject length */ } pcre_study_data; /* Structure for building a chain of open capturing subpatterns during compiling, so that instructions to close them can be compiled when (*ACCEPT) is encountered. This is also used to identify subpatterns that contain recursive back references to themselves, so that they can be made atomic. */ typedef struct open_capitem { struct open_capitem *next; /* Chain link */ pcre_uint16 number; /* Capture number */ pcre_uint16 flag; /* Set TRUE if recursive back ref */ } open_capitem; /* Structure for passing "static" information around between the functions doing the compiling, so that they are thread-safe. */ typedef struct compile_data { const pcre_uint8 *lcc; /* Points to lower casing table */ const pcre_uint8 *fcc; /* Points to case-flipping table */ const pcre_uint8 *cbits; /* Points to character type table */ const pcre_uint8 *ctypes; /* Points to table of type maps */ const pcre_uchar *start_workspace;/* The start of working space */ const pcre_uchar *start_code; /* The start of the compiled code */ const pcre_uchar *start_pattern; /* The start of the pattern */ const pcre_uchar *end_pattern; /* The end of the pattern */ open_capitem *open_caps; /* Chain of open capture items */ pcre_uchar *hwm; /* High watermark of workspace */ pcre_uchar *name_table; /* The name/number table */ int names_found; /* Number of entries so far */ int name_entry_size; /* Size of each entry */ int workspace_size; /* Size of workspace */ int bracount; /* Count of capturing parens as we compile */ int final_bracount; /* Saved value after first pass */ int top_backref; /* Maximum back reference */ unsigned int backref_map; /* Bitmap of low back refs */ int assert_depth; /* Depth of nested assertions */ int external_options; /* External (initial) options */ int external_flags; /* External flag bits to be set */ int req_varyopt; /* "After variable item" flag for reqbyte */ BOOL had_accept; /* (*ACCEPT) encountered */ BOOL check_lookbehind; /* Lookbehinds need later checking */ int nltype; /* Newline type */ int nllen; /* Newline string length */ pcre_uchar nl[4]; /* Newline string when fixed length */ } compile_data; /* Structure for maintaining a chain of pointers to the currently incomplete branches, for testing for left recursion while compiling. */ typedef struct branch_chain { struct branch_chain *outer; pcre_uchar *current_branch; } branch_chain; /* Structure for items in a linked list that represents an explicit recursive call within the pattern; used by pcre_exec(). */ typedef struct recursion_info { struct recursion_info *prevrec; /* Previous recursion record (or NULL) */ int group_num; /* Number of group that was called */ int *offset_save; /* Pointer to start of saved offsets */ int saved_max; /* Number of saved offsets */ PCRE_PUCHAR subject_position; /* Position at start of recursion */ } recursion_info; /* A similar structure for pcre_dfa_exec(). */ typedef struct dfa_recursion_info { struct dfa_recursion_info *prevrec; int group_num; PCRE_PUCHAR subject_position; } dfa_recursion_info; /* Structure for building a chain of data for holding the values of the subject pointer at the start of each subpattern, so as to detect when an empty string has been matched by a subpattern - to break infinite loops; used by pcre_exec(). */ typedef struct eptrblock { struct eptrblock *epb_prev; PCRE_PUCHAR epb_saved_eptr; } eptrblock; /* Structure for passing "static" information around between the functions doing traditional NFA matching, so that they are thread-safe. */ typedef struct match_data { unsigned long int match_call_count; /* As it says */ unsigned long int match_limit; /* As it says */ unsigned long int match_limit_recursion; /* As it says */ int *offset_vector; /* Offset vector */ int offset_end; /* One past the end */ int offset_max; /* The maximum usable for return data */ int nltype; /* Newline type */ int nllen; /* Newline string length */ int name_count; /* Number of names in name table */ int name_entry_size; /* Size of entry in names table */ pcre_uchar *name_table; /* Table of names */ pcre_uchar nl[4]; /* Newline string when fixed */ const pcre_uint8 *lcc; /* Points to lower casing table */ const pcre_uint8 *fcc; /* Points to case-flipping table */ const pcre_uint8 *ctypes; /* Points to table of type maps */ BOOL offset_overflow; /* Set if too many extractions */ BOOL notbol; /* NOTBOL flag */ BOOL noteol; /* NOTEOL flag */ BOOL utf; /* UTF-8 / UTF-16 flag */ BOOL jscript_compat; /* JAVASCRIPT_COMPAT flag */ BOOL use_ucp; /* PCRE_UCP flag */ BOOL endonly; /* Dollar not before final \n */ BOOL notempty; /* Empty string match not wanted */ BOOL notempty_atstart; /* Empty string match at start not wanted */ BOOL hitend; /* Hit the end of the subject at some point */ BOOL bsr_anycrlf; /* \R is just any CRLF, not full Unicode */ BOOL hasthen; /* Pattern contains (*THEN) */ BOOL ignore_skip_arg; /* For re-run when SKIP name not found */ const pcre_uchar *start_code; /* For use when recursing */ PCRE_PUCHAR start_subject; /* Start of the subject string */ PCRE_PUCHAR end_subject; /* End of the subject string */ PCRE_PUCHAR start_match_ptr; /* Start of matched string */ PCRE_PUCHAR end_match_ptr; /* Subject position at end match */ PCRE_PUCHAR start_used_ptr; /* Earliest consulted character */ int partial; /* PARTIAL options */ int end_offset_top; /* Highwater mark at end of match */ int capture_last; /* Most recent capture number */ int start_offset; /* The start offset value */ int match_function_type; /* Set for certain special calls of MATCH() */ eptrblock *eptrchain; /* Chain of eptrblocks for tail recursions */ int eptrn; /* Next free eptrblock */ recursion_info *recursive; /* Linked list of recursion data */ void *callout_data; /* To pass back to callouts */ const pcre_uchar *mark; /* Mark pointer to pass back on success */ const pcre_uchar *nomatch_mark;/* Mark pointer to pass back on failure */ const pcre_uchar *once_target; /* Where to back up to for atomic groups */ } match_data; /* A similar structure is used for the same purpose by the DFA matching functions. */ typedef struct dfa_match_data { const pcre_uchar *start_code; /* Start of the compiled pattern */ const pcre_uchar *start_subject ; /* Start of the subject string */ const pcre_uchar *end_subject; /* End of subject string */ const pcre_uchar *start_used_ptr; /* Earliest consulted character */ const pcre_uint8 *tables; /* Character tables */ int start_offset; /* The start offset value */ int moptions; /* Match options */ int poptions; /* Pattern options */ int nltype; /* Newline type */ int nllen; /* Newline string length */ pcre_uchar nl[4]; /* Newline string when fixed */ void *callout_data; /* To pass back to callouts */ dfa_recursion_info *recursive; /* Linked list of recursion data */ } dfa_match_data; /* Bit definitions for entries in the pcre_ctypes table. */ #define ctype_space 0x01 #define ctype_letter 0x02 #define ctype_digit 0x04 #define ctype_xdigit 0x08 #define ctype_word 0x10 /* alphanumeric or '_' */ #define ctype_meta 0x80 /* regexp meta char or zero (end pattern) */ /* Offsets for the bitmap tables in pcre_cbits. Each table contains a set of bits for a class map. Some classes are built by combining these tables. */ #define cbit_space 0 /* [:space:] or \s */ #define cbit_xdigit 32 /* [:xdigit:] */ #define cbit_digit 64 /* [:digit:] or \d */ #define cbit_upper 96 /* [:upper:] */ #define cbit_lower 128 /* [:lower:] */ #define cbit_word 160 /* [:word:] or \w */ #define cbit_graph 192 /* [:graph:] */ #define cbit_print 224 /* [:print:] */ #define cbit_punct 256 /* [:punct:] */ #define cbit_cntrl 288 /* [:cntrl:] */ #define cbit_length 320 /* Length of the cbits table */ /* Offsets of the various tables from the base tables pointer, and total length. */ #define lcc_offset 0 #define fcc_offset 256 #define cbits_offset 512 #define ctypes_offset (cbits_offset + cbit_length) #define tables_length (ctypes_offset + 256) /* Internal function prefix */ #ifdef COMPILE_PCRE8 #ifndef PUBL #define PUBL(name) pcre_##name #endif #ifndef PRIV #define PRIV(name) _pcre_##name #endif #else /* COMPILE_PCRE8 */ #ifdef COMPILE_PCRE16 #ifndef PUBL #define PUBL(name) pcre16_##name #endif #ifndef PRIV #define PRIV(name) _pcre16_##name #endif #else #error Unsupported compiling mode #endif /* COMPILE_PCRE16 */ #endif /* COMPILE_PCRE8 */ /* Layout of the UCP type table that translates property names into types and codes. Each entry used to point directly to a name, but to reduce the number of relocations in shared libraries, it now has an offset into a single string instead. */ typedef struct { pcre_uint16 name_offset; pcre_uint16 type; pcre_uint16 value; } ucp_type_table; /* Internal shared data tables. These are tables that are used by more than one of the exported public functions. They have to be "external" in the C sense, but are not part of the PCRE public API. The data for these tables is in the pcre_tables.c module. */ #ifdef COMPILE_PCRE8 extern const int PRIV(utf8_table1)[]; extern const int PRIV(utf8_table1_size); extern const int PRIV(utf8_table2)[]; extern const int PRIV(utf8_table3)[]; extern const pcre_uint8 PRIV(utf8_table4)[]; #endif /* COMPILE_PCRE8 */ extern const char PRIV(utt_names)[]; extern const ucp_type_table PRIV(utt)[]; extern const int PRIV(utt_size); extern const pcre_uint8 PRIV(default_tables)[]; extern const pcre_uint8 PRIV(OP_lengths)[]; /* Internal shared functions. These are functions that are used by more than one of the exported public functions. They have to be "external" in the C sense, but are not part of the PCRE public API. */ /* String comparison functions. */ #ifdef COMPILE_PCRE8 #define STRCMP_UC_UC(str1, str2) \ strcmp((char *)(str1), (char *)(str2)) #define STRCMP_UC_C8(str1, str2) \ strcmp((char *)(str1), (str2)) #define STRNCMP_UC_UC(str1, str2, num) \ strncmp((char *)(str1), (char *)(str2), (num)) #define STRNCMP_UC_C8(str1, str2, num) \ strncmp((char *)(str1), (str2), (num)) #define STRLEN_UC(str) strlen((const char *)str) #else extern int PRIV(strcmp_uc_uc)(const pcre_uchar *, const pcre_uchar *); extern int PRIV(strcmp_uc_c8)(const pcre_uchar *, const char *); extern int PRIV(strncmp_uc_uc)(const pcre_uchar *, const pcre_uchar *, unsigned int num); extern int PRIV(strncmp_uc_c8)(const pcre_uchar *, const char *, unsigned int num); extern unsigned int PRIV(strlen_uc)(const pcre_uchar *str); #define STRCMP_UC_UC(str1, str2) \ PRIV(strcmp_uc_uc)((str1), (str2)) #define STRCMP_UC_C8(str1, str2) \ PRIV(strcmp_uc_c8)((str1), (str2)) #define STRNCMP_UC_UC(str1, str2, num) \ PRIV(strncmp_uc_uc)((str1), (str2), (num)) #define STRNCMP_UC_C8(str1, str2, num) \ PRIV(strncmp_uc_c8)((str1), (str2), (num)) #define STRLEN_UC(str) PRIV(strlen_uc)(str) #endif /* COMPILE_PCRE8 */ extern const pcre_uchar *PRIV(find_bracket)(const pcre_uchar *, BOOL, int); extern BOOL PRIV(is_newline)(PCRE_PUCHAR, int, PCRE_PUCHAR, int *, BOOL); extern int PRIV(ord2utf)(pcre_uint32, pcre_uchar *); extern int PRIV(valid_utf)(PCRE_PUCHAR, int, int *); extern BOOL PRIV(was_newline)(PCRE_PUCHAR, int, PCRE_PUCHAR, int *, BOOL); extern BOOL PRIV(xclass)(int, const pcre_uchar *, BOOL); #ifdef SUPPORT_JIT extern void PRIV(jit_compile)(const REAL_PCRE *, PUBL(extra) *); extern int PRIV(jit_exec)(const REAL_PCRE *, void *, const pcre_uchar *, int, int, int, int, int *, int); extern void PRIV(jit_free)(void *); extern int PRIV(jit_get_size)(void *); extern const char* PRIV(jit_get_target)(void); #endif /* Unicode character database (UCD) */ typedef struct { pcre_uint8 script; pcre_uint8 chartype; pcre_int32 other_case; } ucd_record; extern const ucd_record PRIV(ucd_records)[]; extern const pcre_uint8 PRIV(ucd_stage1)[]; extern const pcre_uint16 PRIV(ucd_stage2)[]; extern const int PRIV(ucp_gentype)[]; #ifdef SUPPORT_JIT extern const int PRIV(ucp_typerange)[]; #endif #ifdef SUPPORT_UCP /* UCD access macros */ #define UCD_BLOCK_SIZE 128 #define GET_UCD(ch) (PRIV(ucd_records) + \ PRIV(ucd_stage2)[PRIV(ucd_stage1)[(ch) / UCD_BLOCK_SIZE] * \ UCD_BLOCK_SIZE + (ch) % UCD_BLOCK_SIZE]) #define UCD_CHARTYPE(ch) GET_UCD(ch)->chartype #define UCD_SCRIPT(ch) GET_UCD(ch)->script #define UCD_CATEGORY(ch) PRIV(ucp_gentype)[UCD_CHARTYPE(ch)] #define UCD_OTHERCASE(ch) (ch + GET_UCD(ch)->other_case) #endif /* SUPPORT_UCP */ #endif /* End of pcre_internal.h */
94,859
C++
.h
1,965
46.011196
150
0.569393
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
16,152
pcret.h
AutoHotkey_AutoHotkey/source/lib_pcre/pcre/pcret.h
#ifdef UNICODE #define pcret pcre16 #define pcret_extra pcre16_extra #define pcret_callout_block pcre16_callout_block #define pcret_malloc pcre16_malloc #define pcret_free pcre16_free #define pcret_stack_malloc pcre16_stack_malloc #define pcret_stack_free pcre16_stack_free #define pcret_callout pcre16_callout #define pcret_compile pcre16_compile #define pcret_compile2 pcre16_compile2 #define pcret_config pcre16_config #define pcret_copy_named_substring pcre16_copy_named_substring #define pcret_copy_substring pcre16_copy_substring #define pcret_dfa_exec pcre16_dfa_exec #define pcret_exec pcre16_exec #define pcret_free_substring pcre16_free_substring #define pcret_free_substring_list pcre16_free_substring_list #define pcret_fullinfo pcre16_fullinfo #define pcret_get_named_substring pcre16_get_named_substring #define pcret_get_stringnumber pcre16_get_stringnumber #define pcret_get_first_set pcre16_get_first_set #define pcret_get_stringtable_entries pcre16_get_stringtable_entries #define pcret_get_substring pcre16_get_substring #define pcret_get_substring_list pcre16_get_substring_list #define pcret_maketables pcre16_maketables #define pcret_refcount pcre16_refcount #define pcret_study pcre16_study #define pcret_free_study pcre16_free_study #define pcret_version pcre16_version #define pcret_pattern_to_host_byte_order pcre16_pattern_to_host_byte_order #define pcret_jit_stack_alloc pcre16_jit_stack_alloc #define pcret_jit_stack_free pcre16_jit_stack_free #define pcret_assign_jit_stack pcre16_assign_jit_stack #else #define pcret pcre #define pcret_extra pcre_extra #define pcret_callout_block pcre_callout_block #define pcret_malloc pcre_malloc #define pcret_free pcre_free #define pcret_stack_malloc pcre_stack_malloc #define pcret_stack_free pcre_stack_free #define pcret_callout pcre_callout #define pcret_compile pcre_compile #define pcret_compile2 pcre_compile2 #define pcret_config pcre_config #define pcret_copy_named_substring pcre_copy_named_substring #define pcret_copy_substring pcre_copy_substring #define pcret_dfa_exec pcre_dfa_exec #define pcret_exec pcre_exec #define pcret_free_substring pcre_free_substring #define pcret_free_substring_list pcre_free_substring_list #define pcret_fullinfo pcre_fullinfo #define pcret_get_named_substring pcre_get_named_substring #define pcret_get_stringnumber pcre_get_stringnumber #define pcret_get_first_set pcre_get_first_set #define pcret_get_stringtable_entries pcre_get_stringtable_entries #define pcret_get_substring pcre_get_substring #define pcret_get_substring_list pcre_get_substring_list #define pcret_maketables pcre_maketables #define pcret_refcount pcre_refcount #define pcret_study pcre_study #define pcret_free_study pcre_free_study #define pcret_version pcre_version #define pcret_pattern_to_host_byte_order pcre_pattern_to_host_byte_order #define pcret_jit_stack_alloc pcre_jit_stack_alloc #define pcret_jit_stack_free pcre_jit_stack_free #define pcret_assign_jit_stack pcre_assign_jit_stack #endif
3,259
C++
.h
69
46.101449
74
0.774914
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,153
config.h
AutoHotkey_AutoHotkey/source/lib_pcre/pcre/config.h
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ #include "../../config.h" // Allow AutoHotkey config.h to define charset (_MBCS or UNICODE). /* On Unix-like systems config.h.in is converted by "configure" into config.h. Some other environments also support the use of "configure". PCRE is written in Standard C, but there are a few non-standard things it can cope with, allowing it to run on SunOS4 and other "close to standard" systems. If you are going to build PCRE "by hand" on a system without "configure" you should copy the distributed config.h.generic to config.h, and then set up the macro definitions the way you need them. You must then add -DHAVE_CONFIG_H to all of your compile commands, so that config.h is included at the start of every source. Alternatively, you can avoid editing by using -D on the compiler command line to set the macro values. In this case, you do not have to set -DHAVE_CONFIG_H. PCRE uses memmove() if HAVE_MEMMOVE is set to 1; otherwise it uses bcopy() if HAVE_BCOPY is set to 1. If your system has neither bcopy() nor memmove(), set them both to 0; an emulation function will be used. */ /* By default, the \R escape sequence matches any Unicode line ending character or sequence of characters. If BSR_ANYCRLF is defined, this is changed so that backslash-R matches only CR, LF, or CRLF. The build-time default can be overridden by the user of PCRE at runtime. On systems that support it, "configure" can be used to override the default. */ #define BSR_ANYCRLF /* AutoHotkey: BSR_ANYCRLF above is defined for consistency with the default newline-matching behaviour. */ /* If you are compiling for a system that uses EBCDIC instead of ASCII character codes, define this macro as 1. On systems that can use "configure", this can be done via --enable-ebcdic. PCRE will then assume that all input strings are in EBCDIC. If you do not define this macro, PCRE will assume input strings are ASCII or UTF-8/16 Unicode. It is not possible to build a version of PCRE that supports both EBCDIC and UTF-8/16. */ /* #undef EBCDIC */ /* Define to 1 if you have the `bcopy' function. */ #ifndef HAVE_BCOPY #define HAVE_BCOPY 0 /* AutoHotkey: Changed from 1 to 0. */ #endif /* Define to 1 if you have the <bits/type_traits.h> header file. */ /* #undef HAVE_BITS_TYPE_TRAITS_H */ /* Define to 1 if you have the <bzlib.h> header file. */ /* #undef HAVE_BZLIB_H */ /* Define to 1 if you have the <dirent.h> header file. */ #ifndef HAVE_DIRENT_H #define HAVE_DIRENT_H 0 /* AutoHotkey: Changed from 1 to 0. */ #endif /* Define to 1 if you have the <dlfcn.h> header file. */ #ifndef HAVE_DLFCN_H #define HAVE_DLFCN_H 0 /* AutoHotkey: Changed from 1 to 0. */ #endif /* Define to 1 if you have the <inttypes.h> header file. */ #ifndef HAVE_INTTYPES_H #define HAVE_INTTYPES_H 0 /* AutoHotkey: Changed from 1 to 0. */ #endif /* Define to 1 if you have the <limits.h> header file. */ #ifndef HAVE_LIMITS_H #define HAVE_LIMITS_H 1 #endif /* Define to 1 if the system has the type `long long'. */ #ifndef HAVE_LONG_LONG #define HAVE_LONG_LONG 1 #endif /* Define to 1 if you have the `memmove' function. */ #ifndef HAVE_MEMMOVE #define HAVE_MEMMOVE 1 #endif /* Define to 1 if you have the <memory.h> header file. */ #ifndef HAVE_MEMORY_H #define HAVE_MEMORY_H 1 #endif /* Define to 1 if you have the <readline/history.h> header file. */ /* #undef HAVE_READLINE_HISTORY_H */ /* Define to 1 if you have the <readline/readline.h> header file. */ /* #undef HAVE_READLINE_READLINE_H */ /* Define to 1 if you have the <stdint.h> header file. */ #ifndef HAVE_STDINT_H #define HAVE_STDINT_H 0 /* AutoHotkey: Changed from 1 to 0. */ #endif /* Define to 1 if you have the <stdlib.h> header file. */ #ifndef HAVE_STDLIB_H #define HAVE_STDLIB_H 1 #endif /* Define to 1 if you have the `strerror' function. */ #ifndef HAVE_STRERROR #define HAVE_STRERROR 1 #endif /* Define to 1 if you have the <string> header file. */ #ifndef HAVE_STRING #define HAVE_STRING 1 #endif /* Define to 1 if you have the <strings.h> header file. */ #ifndef HAVE_STRINGS_H #define HAVE_STRINGS_H 0 /* AutoHotkey: Changed from 1 to 0. */ #endif /* Define to 1 if you have the <string.h> header file. */ #ifndef HAVE_STRING_H #define HAVE_STRING_H 1 #endif /* Define to 1 if you have `strtoimax'. */ /* #undef HAVE_STRTOIMAX */ /* Define to 1 if you have `strtoll'. */ #ifndef HAVE_STRTOLL #define HAVE_STRTOLL 0 /* AutoHotkey: Changed from 1 to 0. */ #endif /* Define to 1 if you have `strtoq'. */ #ifndef HAVE_STRTOQ #define HAVE_STRTOQ 1 #endif /* Define to 1 if you have the <sys/stat.h> header file. */ #ifndef HAVE_SYS_STAT_H #define HAVE_SYS_STAT_H 1 #endif /* Define to 1 if you have the <sys/types.h> header file. */ #ifndef HAVE_SYS_TYPES_H #define HAVE_SYS_TYPES_H 1 #endif /* Define to 1 if you have the <type_traits.h> header file. */ /* #undef HAVE_TYPE_TRAITS_H */ /* Define to 1 if you have the <unistd.h> header file. */ #ifndef HAVE_UNISTD_H #define HAVE_UNISTD_H 0 /* AutoHotkey: Changed from 1 to 0. */ #endif /* Define to 1 if the system has the type `unsigned long long'. */ #ifndef HAVE_UNSIGNED_LONG_LONG #define HAVE_UNSIGNED_LONG_LONG 1 #endif /* Define to 1 if you have the <windows.h> header file. */ /* #undef HAVE_WINDOWS_H */ #define HAVE_WINDOWS_H 1 /* AutoHotkey: Added. */ /* Define to 1 if you have the <zlib.h> header file. */ /* #undef HAVE_ZLIB_H */ /* Define to 1 if you have `_strtoi64'. */ #define HAVE__STRTOI64 1 /* AutoHotkey: Added. */ /* The value of LINK_SIZE determines the number of bytes used to store links as offsets within the compiled regex. The default is 2, which allows for compiled patterns up to 64K long. This covers the vast majority of cases. However, PCRE can also be compiled to use 3 or 4 bytes instead. This allows for longer patterns in extreme cases. On systems that support it, "configure" can be used to override this default. */ #ifndef LINK_SIZE #define LINK_SIZE 2 /* AutoHotkey: PHP also seems to use 2, so it's likely the best compromise between memory utilization and being able to handle unusually large compiled patterns. */ #endif /* Define to the sub-directory in which libtool stores uninstalled libraries. */ /* #undef LT_OBJDIR */ /* The value of MATCH_LIMIT determines the default number of times the internal match() function can be called during a single execution of pcre_exec(). There is a runtime interface for setting a different limit. The limit exists in order to catch runaway regular expressions that take for ever to determine that they do not match. The default is set very large so that it does not accidentally catch legitimate cases. On systems that support it, "configure" can be used to override this default default. */ #ifndef MATCH_LIMIT #define MATCH_LIMIT 10000000 #endif /* The above limit applies to all calls of match(), whether or not they increase the recursion depth. In some environments it is desirable to limit the depth of recursive calls of match() more strictly, in order to restrict the maximum amount of stack (or heap, if NO_RECURSE is defined) that is used. The value of MATCH_LIMIT_RECURSION applies only to recursive calls of match(). To have any useful effect, it must be less than the value of MATCH_LIMIT. The default is to use the same value as MATCH_LIMIT. There is a runtime method for setting a different limit. On systems that support it, "configure" can be used to override the default. */ /* AutoHotkey: Original value was MATCH_LIMIT (i.e. 10000000). It was lowered to 6000 so that the program's current stack limit of 4 MB won't be exceeded. The limit was computed from the following info in PCRE docs somewhere: "As a very rough rule of thumb, you should reckon on about 500 bytes per recursion. Thus, if you want to limit your stack usage to 8Mb, you should set the limit at 16000 recursions. A 64Mb stack, on the other hand, can support around 128000 recursions." */ #ifndef MATCH_LIMIT_RECURSION #define MATCH_LIMIT_RECURSION 6000 #endif /* This limit is parameterized just in case anybody ever wants to change it. Care must be taken if it is increased, because it guards against integer overflow caused by enormously large patterns. */ #ifndef MAX_NAME_COUNT #define MAX_NAME_COUNT 10000 #endif /* This limit is parameterized just in case anybody ever wants to change it. Care must be taken if it is increased, because it guards against integer overflow caused by enormously large patterns. */ #ifndef MAX_NAME_SIZE #define MAX_NAME_SIZE 32 #endif /* The value of NEWLINE determines the newline character sequence. On systems that support it, "configure" can be used to override the default, which is 10. The possible values are 10 (LF), 13 (CR), 3338 (CRLF), -1 (ANY), or -2 (ANYCRLF). */ #ifndef NEWLINE #define NEWLINE -2 #endif /* PCRE uses recursive function calls to handle backtracking while matching. This can sometimes be a problem on systems that have stacks of limited size. Define NO_RECURSE to get a version that doesn't use recursion in the match() function; instead it creates its own stack by steam using pcre_recurse_malloc() to obtain memory from the heap. For more detail, see the comments and other stuff just above the match() function. On systems that support it, "configure" can be used to set this in the Makefile (use --disable-stack-for-recursion). */ /* #undef NO_RECURSE */ /* Name of package */ #define PACKAGE "pcre" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "PCRE" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "PCRE 8.30" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "pcre" /* Define to the home page for this package. */ /* #undef PACKAGE_URL */ /* Define to the version of this package. */ #define PACKAGE_VERSION "8.30" /* The value of PCREGREP_BUFSIZE determines the size of buffer used by pcregrep to hold parts of the file it is searching. On systems that support it, "configure" can be used to override the default, which is 8192. This is also the minimum value. The actual amount of memory used by pcregrep is three times this number, because it allows for the buffering of "before" and "after" lines. */ #ifndef PCREGREP_BUFSIZE #define PCREGREP_BUFSIZE 20480 #endif /* If you are compiling for a system other than a Unix-like system or Win32, and it needs some magic to be inserted before the definition of a function that is exported by the library, define this macro to contain the relevant magic. If you do not define this macro, it defaults to "extern" for a C compiler and "extern C" for a C++ compiler on non-Win32 systems. This macro apears at the start of every exported function that is part of the external API. It does not appear on functions that are "external" in the C sense, but which are internal to the library. */ /* #undef PCRE_EXP_DEFN */ /* Define if linking statically (TODO: make nice with Libtool) */ /* #undef PCRE_STATIC */ #define PCRE_STATIC 1 /* AutoHotkey: Added because it reduces code size of AutoHotkey.exe and others by 1-2 KB. It's also more appropriate since the linking of this library is at compile-time (i.e. not a DLL). */ /* When calling PCRE via the POSIX interface, additional working storage is required for holding the pointers to capturing substrings because PCRE requires three integers per substring, whereas the POSIX interface provides only two. If the number of expected substrings is small, the wrapper function uses space on the stack, because this is faster than using malloc() for each call. The threshold above which the stack is no longer used is defined by POSIX_MALLOC_THRESHOLD. On systems that support it, "configure" can be used to override this default. */ #ifndef POSIX_MALLOC_THRESHOLD #define POSIX_MALLOC_THRESHOLD 10 #endif /* Define to 1 if you have the ANSI C header files. */ #ifndef STDC_HEADERS #define STDC_HEADERS 1 #endif /* Define to enable support for Just-In-Time compiling. */ /* #undef SUPPORT_JIT */ /* Define to allow pcregrep to be linked with libbz2, so that it is able to handle .bz2 files. */ /* #undef SUPPORT_LIBBZ2 */ /* Define to allow pcretest to be linked with libreadline. */ /* #undef SUPPORT_LIBREADLINE */ /* Define to allow pcregrep to be linked with libz, so that it is able to handle .gz files. */ /* #undef SUPPORT_LIBZ */ #ifdef UNICODE /* Define to enable the 16 bit PCRE library. */ #define SUPPORT_PCRE16 /* Define to enable support for Unicode properties */ #define SUPPORT_UCP /* Define to enable support for the UTF-8/16 Unicode encoding. This will work even in an EBCDIC environment, but it is incompatible with the EBCDIC macro. That is, PCRE can support *either* EBCDIC code *or* ASCII/UTF-8/16, but not both at once. */ #define SUPPORT_UTF /* AutoHotkey: Define to validate UTF input. Leave undefined for performance. */ /* #undef SUPPORT_UTF_VALIDATION */ #else /* Define to enable the 8 bit PCRE library. */ #define SUPPORT_PCRE8 #endif /* Define to enable JIT support in pcregrep. */ /* #undef SUPPORT_PCREGREP_JIT */ /* Version number of package */ #ifndef VERSION #define VERSION "8.30" #endif /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */ /* Define to the type of a signed integer type of width exactly 64 bits if such a type exists and the standard includes do not define it. */ /* #define int64_t __int64 */ /* Define to `unsigned int' if <sys/types.h> does not define. */ /* #undef size_t */
13,884
C++
.h
289
46.055363
214
0.746615
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
16,154
sljitLir.h
AutoHotkey_AutoHotkey/source/lib_pcre/pcre/sljit/sljitLir.h
/* * Stack-less Just-In-Time compiler * * Copyright 2009-2012 Zoltan Herczeg (hzmester@freemail.hu). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SLJIT_LIR_H_ #define _SLJIT_LIR_H_ /* ------------------------------------------------------------------------ Stack-Less JIT compiler for multiple architectures (x86, ARM, PowerPC) ------------------------------------------------------------------------ Short description Advantages: - The execution can be continued from any LIR instruction In other words, jump into and out of the code is safe - Both target of (conditional) jump and call instructions and constants can be dynamically modified during runtime - although it is not suggested to do it frequently - very effective to cache an important value once - A fixed stack space can be allocated for local variables - The compiler is thread-safe Disadvantages: - Limited number of registers (only 6+4 integer registers, max 3+2 temporary, max 3+2 saved and 4 floating point registers) In practice: - This approach is very effective for interpreters - One of the saved registers typically points to a stack interface - It can jump to any exception handler anytime (even for another function. It is safe for SLJIT.) - Fast paths can be modified during runtime reflecting the changes of the fastest execution path of the dynamic language - SLJIT supports complex memory addressing modes - mainly position independent code - Optimizations (perhaps later) - Only for basic blocks (when no labels inserted between LIR instructions) For valgrind users: - pass --smc-check=all argument to valgrind, since JIT is a "self-modifying code" */ #if !(defined SLJIT_NO_DEFAULT_CONFIG && SLJIT_NO_DEFAULT_CONFIG) #include "sljitConfig.h" #endif /* The following header file defines useful macros for fine tuning sljit based code generators. They are listed in the begining of sljitConfigInternal.h */ #include "sljitConfigInternal.h" /* --------------------------------------------------------------------- */ /* Error codes */ /* --------------------------------------------------------------------- */ /* Indicates no error. */ #define SLJIT_SUCCESS 0 /* After the call of sljit_generate_code(), the error code of the compiler is set to this value to avoid future sljit calls (in debug mode at least). The complier should be freed after sljit_generate_code(). */ #define SLJIT_ERR_COMPILED 1 /* Cannot allocate non executable memory. */ #define SLJIT_ERR_ALLOC_FAILED 2 /* Cannot allocate executable memory. Only for sljit_generate_code() */ #define SLJIT_ERR_EX_ALLOC_FAILED 3 /* return value for SLJIT_CONFIG_UNSUPPORTED empty architecture. */ #define SLJIT_ERR_UNSUPPORTED 4 /* --------------------------------------------------------------------- */ /* Registers */ /* --------------------------------------------------------------------- */ #define SLJIT_UNUSED 0 /* Temporary (scratch) registers may not preserve their values across function calls. */ #define SLJIT_TEMPORARY_REG1 1 #define SLJIT_TEMPORARY_REG2 2 #define SLJIT_TEMPORARY_REG3 3 /* Note: Extra Registers cannot be used for memory addressing. */ /* Note: on x86-32, these registers are emulated (using stack loads & stores). */ #define SLJIT_TEMPORARY_EREG1 4 #define SLJIT_TEMPORARY_EREG2 5 /* Saved registers whose preserve their values across function calls. */ #define SLJIT_SAVED_REG1 6 #define SLJIT_SAVED_REG2 7 #define SLJIT_SAVED_REG3 8 /* Note: Extra Registers cannot be used for memory addressing. */ /* Note: on x86-32, these registers are emulated (using stack loads & stores). */ #define SLJIT_SAVED_EREG1 9 #define SLJIT_SAVED_EREG2 10 /* Read-only register (cannot be the destination of an operation). */ /* Note: SLJIT_MEM2( ... , SLJIT_LOCALS_REG) is not supported (x86 limitation). */ /* Note: SLJIT_LOCALS_REG is not necessary the real stack pointer. See sljit_emit_enter. */ #define SLJIT_LOCALS_REG 11 /* Number of registers. */ #define SLJIT_NO_TMP_REGISTERS 5 #define SLJIT_NO_GEN_REGISTERS 5 #define SLJIT_NO_REGISTERS 11 /* Return with machine word. */ #define SLJIT_RETURN_REG SLJIT_TEMPORARY_REG1 /* x86 prefers specific registers for special purposes. In case of shift by register it supports only SLJIT_TEMPORARY_REG3 for shift argument (which is the src2 argument of sljit_emit_op2). If another register is used, sljit must exchange data between registers which cause a minor slowdown. Other architectures has no such limitation. */ #define SLJIT_PREF_SHIFT_REG SLJIT_TEMPORARY_REG3 /* --------------------------------------------------------------------- */ /* Floating point registers */ /* --------------------------------------------------------------------- */ /* Note: SLJIT_UNUSED as destination is not valid for floating point operations, since they cannot be used for setting flags. */ /* Floating point operations are performed on double precision values. */ #define SLJIT_FLOAT_REG1 1 #define SLJIT_FLOAT_REG2 2 #define SLJIT_FLOAT_REG3 3 #define SLJIT_FLOAT_REG4 4 /* --------------------------------------------------------------------- */ /* Main structures and functions */ /* --------------------------------------------------------------------- */ struct sljit_memory_fragment { struct sljit_memory_fragment *next; sljit_uw used_size; sljit_ub memory[1]; }; struct sljit_label { struct sljit_label *next; sljit_uw addr; /* The maximum size difference. */ sljit_uw size; }; struct sljit_jump { struct sljit_jump *next; sljit_uw addr; sljit_w flags; union { sljit_uw target; struct sljit_label* label; } u; }; struct sljit_const { struct sljit_const *next; sljit_uw addr; }; struct sljit_compiler { int error; struct sljit_label *labels; struct sljit_jump *jumps; struct sljit_const *consts; struct sljit_label *last_label; struct sljit_jump *last_jump; struct sljit_const *last_const; struct sljit_memory_fragment *buf; struct sljit_memory_fragment *abuf; /* Used local registers. */ int temporaries; /* Used saved registers. */ int saveds; /* Local stack size. */ int local_size; /* Code size. */ sljit_uw size; /* For statistical purposes. */ sljit_uw executable_size; #if (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) int args; int temporaries_start; int saveds_start; #endif #if (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) int mode32; #ifdef _WIN64 int has_locals; #endif #endif #if (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) || (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) int flags_saved; #endif #if (defined SLJIT_CONFIG_ARM_V5 && SLJIT_CONFIG_ARM_V5) /* Constant pool handling. */ sljit_uw *cpool; sljit_ub *cpool_unique; sljit_uw cpool_diff; sljit_uw cpool_fill; /* Other members. */ /* Contains pointer, "ldr pc, [...]" pairs. */ sljit_uw patches; #endif #if (defined SLJIT_CONFIG_ARM_V5 && SLJIT_CONFIG_ARM_V5) || (defined SLJIT_CONFIG_ARM_V7 && SLJIT_CONFIG_ARM_V7) /* Temporary fields. */ sljit_uw shift_imm; int cache_arg; sljit_w cache_argw; #endif #if (defined SLJIT_CONFIG_ARM_THUMB2 && SLJIT_CONFIG_ARM_THUMB2) int cache_arg; sljit_w cache_argw; #endif #if (defined SLJIT_CONFIG_PPC_32 && SLJIT_CONFIG_PPC_32) || (defined SLJIT_CONFIG_PPC_64 && SLJIT_CONFIG_PPC_64) int has_locals; sljit_w imm; int cache_arg; sljit_w cache_argw; #endif #if (defined SLJIT_CONFIG_MIPS_32 && SLJIT_CONFIG_MIPS_32) int has_locals; int delay_slot; int cache_arg; sljit_w cache_argw; #endif #if (defined SLJIT_VERBOSE && SLJIT_VERBOSE) FILE* verbose; #endif #if (defined SLJIT_VERBOSE && SLJIT_VERBOSE) || (defined SLJIT_DEBUG && SLJIT_DEBUG) int skip_checks; #endif }; /* --------------------------------------------------------------------- */ /* Main functions */ /* --------------------------------------------------------------------- */ /* Creates an sljit compiler. Returns NULL if failed. */ SLJIT_API_FUNC_ATTRIBUTE struct sljit_compiler* sljit_create_compiler(void); /* Free everything except the codes. */ SLJIT_API_FUNC_ATTRIBUTE void sljit_free_compiler(struct sljit_compiler *compiler); static SLJIT_INLINE int sljit_get_compiler_error(struct sljit_compiler *compiler) { return compiler->error; } /* Allocate a small amount of memory. The size must be <= 64 bytes on 32 bit, and <= 128 bytes on 64 bit architectures. The memory area is owned by the compiler, and freed by sljit_free_compiler. The returned pointer is sizeof(sljit_w) aligned. Excellent for allocating small blocks during the compiling, and no need to worry about freeing them. The size is enough to contain at most 16 pointers. If the size is outside of the range, the function will return with NULL, but this return value does not indicate that there is no more memory (does not set the compiler to out-of-memory status). */ SLJIT_API_FUNC_ATTRIBUTE void* sljit_alloc_memory(struct sljit_compiler *compiler, int size); #if (defined SLJIT_VERBOSE && SLJIT_VERBOSE) /* Passing NULL disables verbose. */ SLJIT_API_FUNC_ATTRIBUTE void sljit_compiler_verbose(struct sljit_compiler *compiler, FILE* verbose); #endif SLJIT_API_FUNC_ATTRIBUTE void* sljit_generate_code(struct sljit_compiler *compiler); SLJIT_API_FUNC_ATTRIBUTE void sljit_free_code(void* code); /* After the code generation we can retrieve the allocated executable memory size, although this area may not be fully filled with instructions depending on some optimizations. This function is useful only for statistical purposes. Before a successful code generation, this function returns with 0. */ static SLJIT_INLINE sljit_uw sljit_get_generated_code_size(struct sljit_compiler *compiler) { return compiler->executable_size; } /* Instruction generation. Returns with error code. */ /* The executable code is basically a function call from the viewpoint of the C language. The function calls must obey to the ABI (Application Binary Interface) of the platform, which specify the purpose of machine registers and stack handling among other things. The sljit_emit_enter function emits the necessary instructions for setting up a new context for the executable code and moves function arguments to the saved registers. The number of arguments are specified in the "args" parameter and the first argument goes to SLJIT_SAVED_REG1, the second goes to SLJIT_SAVED_REG2 and so on. The number of temporary and saved registers are passed in "temporaries" and "saveds" arguments respectively. Since the saved registers contains the arguments, "args" must be less or equal than "saveds". The sljit_emit_enter is also capable of allocating a stack space for local variables. The "local_size" argument contains the size in bytes of this local area and its staring address is stored in SLJIT_LOCALS_REG. However the SLJIT_LOCALS_REG is not necessary the machine stack pointer. The memory bytes between SLJIT_LOCALS_REG (inclusive) and SLJIT_LOCALS_REG + local_size (exclusive) can be modified freely until the function returns. The stack space is uninitialized. Note: every call of sljit_emit_enter and sljit_set_context overwrites the previous context. */ #define SLJIT_MAX_LOCAL_SIZE 65536 SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_enter(struct sljit_compiler *compiler, int args, int temporaries, int saveds, int local_size); /* The machine code has a context (which contains the local stack space size, number of used registers, etc.) which initialized by sljit_emit_enter. Several functions (like sljit_emit_return) requres this context to be able to generate the appropriate code. However, some code fragments (like inline cache) may have no normal entry point so their context is unknown for the compiler. Using the function below we can specify thir context. Note: every call of sljit_emit_enter and sljit_set_context overwrites the previous context. */ /* Note: multiple calls of this function overwrites the previous call. */ SLJIT_API_FUNC_ATTRIBUTE void sljit_set_context(struct sljit_compiler *compiler, int args, int temporaries, int saveds, int local_size); /* Return from machine code. The op argument can be SLJIT_UNUSED which means the function does not return with anything or any opcode between SLJIT_MOV and SLJIT_MOV_SI (see sljit_emit_op1). As for src and srcw they must be 0 if op is SLJIT_UNUSED, otherwise see below the description about source and destination arguments. */ SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_return(struct sljit_compiler *compiler, int op, int src, sljit_w srcw); /* Really fast calling method for utility functions inside sljit (see SLJIT_FAST_CALL). All registers and even the stack frame is passed to the callee. The return address is preserved in dst/dstw by sljit_emit_fast_enter, and sljit_emit_fast_return can use this as a return value later. */ /* Note: only for sljit specific, non ABI compilant calls. Fast, since only a few machine instructions are needed. Excellent for small uility functions, where saving registers and setting up a new stack frame would cost too much performance. However, it is still possible to return to the address of the caller (or anywhere else). */ /* Note: flags are not changed (unlike sljit_emit_enter / sljit_emit_return). */ /* Note: although sljit_emit_fast_return could be replaced by an ijump, it is not suggested, since many architectures do clever branch prediction on call / return instruction pairs. */ SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_fast_enter(struct sljit_compiler *compiler, int dst, sljit_w dstw, int args, int temporaries, int saveds, int local_size); SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_fast_return(struct sljit_compiler *compiler, int src, sljit_w srcw); /* Source and destination values for arithmetical instructions imm - a simple immediate value (cannot be used as a destination) reg - any of the registers (immediate argument must be 0) [imm] - absolute immediate memory address [reg+imm] - indirect memory address [reg+(reg<<imm)] - indirect indexed memory address (shift must be between 0 and 3) useful for (byte, half, int, sljit_w) array access (fully supported by both x86 and ARM architectures, and cheap operation on others) */ /* IMPORATNT NOTE: memory access MUST be naturally aligned except SLJIT_UNALIGNED macro is defined and its value is 1. length | alignment ---------+----------- byte | 1 byte (not aligned) half | 2 byte (real_address & 0x1 == 0) int | 4 byte (real_address & 0x3 == 0) sljit_w | 4 byte if SLJIT_32BIT_ARCHITECTURE is defined and its value is 1 | 8 byte if SLJIT_64BIT_ARCHITECTURE is defined and its value is 1 Note: different architectures have different addressing limitations Thus sljit may generate several instructions for other addressing modes x86: all addressing modes supported, but write-back is not supported (requires an extra instruction). On x86-64 only 32 bit signed integers are supported by the architecture. arm: [reg+imm] supported for small immediates (-4095 <= imm <= 4095 or -255 <= imm <= 255 for loading signed bytes, any halfs or doubles) [reg+(reg<<imm)] are supported or requires only two instructions Write back is limited to small immediates on thumb2 ppc: [reg+imm], -65535 <= imm <= 65535. 64 bit moves requires immediates divisible by 4. [reg+reg] supported, write-back supported [reg+(reg<<imm)] (imm != 0) is cheap (requires two instructions) */ /* Register output: simply the name of the register. For destination, you can use SLJIT_UNUSED as well. */ #define SLJIT_MEM 0x100 #define SLJIT_MEM0() (SLJIT_MEM) #define SLJIT_MEM1(r1) (SLJIT_MEM | (r1)) #define SLJIT_MEM2(r1, r2) (SLJIT_MEM | (r1) | ((r2) << 4)) #define SLJIT_IMM 0x200 /* Set 32 bit operation mode (I) on 64 bit CPUs. The flag is totally ignored on 32 bit CPUs. The arithmetic instruction uses only the lower 32 bit of the input register(s), and set the flags according to the 32 bit result. If the destination is a register, the higher 32 bit of the result is undefined. The addressing modes (SLJIT_MEM1/SLJIT_MEM2 macros) are unaffected by this flag. */ #define SLJIT_INT_OP 0x100 /* Common CPU status flags for all architectures (x86, ARM, PPC) - carry flag - overflow flag - zero flag - negative/positive flag (depends on arc) On mips, these flags are emulated by software. */ /* By default, the instructions may, or may not set the CPU status flags. Forcing to set or keep status flags can be done with the following flags: */ /* Note: sljit tries to emit the minimum number of instructions. Using these flags can increase them, so use them wisely to avoid unnecessary code generation. */ /* Set Equal (Zero) status flag (E). */ #define SLJIT_SET_E 0x0200 /* Set signed status flag (S). */ #define SLJIT_SET_S 0x0400 /* Set unsgined status flag (U). */ #define SLJIT_SET_U 0x0800 /* Set signed overflow flag (O). */ #define SLJIT_SET_O 0x1000 /* Set carry flag (C). Note: Kinda unsigned overflow, but behaves differently on various cpus. */ #define SLJIT_SET_C 0x2000 /* Do not modify the flags (K). Note: This flag cannot be combined with any other SLJIT_SET_* flag. */ #define SLJIT_KEEP_FLAGS 0x4000 /* Notes: - you cannot postpone conditional jump instructions except if noted that the instruction does not set flags (See: SLJIT_KEEP_FLAGS). - flag combinations: '|' means 'logical or'. */ /* Flags: - (never set any flags) Note: breakpoint instruction is not supported by all architectures (namely ppc) It falls back to SLJIT_NOP in those cases. */ #define SLJIT_BREAKPOINT 0 /* Flags: - (never set any flags) Note: may or may not cause an extra cycle wait it can even decrease the runtime in a few cases. */ #define SLJIT_NOP 1 /* Flags: may destroy flags Unsigned multiplication of SLJIT_TEMPORARY_REG1 and SLJIT_TEMPORARY_REG2. Result goes to SLJIT_TEMPORARY_REG2:SLJIT_TEMPORARY_REG1 (high:low) word */ #define SLJIT_UMUL 2 /* Flags: may destroy flags Signed multiplication of SLJIT_TEMPORARY_REG1 and SLJIT_TEMPORARY_REG2. Result goes to SLJIT_TEMPORARY_REG2:SLJIT_TEMPORARY_REG1 (high:low) word */ #define SLJIT_SMUL 3 /* Flags: I | may destroy flags Unsigned divide of the value in SLJIT_TEMPORARY_REG1 by the value in SLJIT_TEMPORARY_REG2. The result is placed in SLJIT_TEMPORARY_REG1 and the remainder goes to SLJIT_TEMPORARY_REG2. Note: if SLJIT_TEMPORARY_REG2 contains 0, the behaviour is undefined. */ #define SLJIT_UDIV 4 /* Flags: I | may destroy flags Signed divide of the value in SLJIT_TEMPORARY_REG1 by the value in SLJIT_TEMPORARY_REG2. The result is placed in SLJIT_TEMPORARY_REG1 and the remainder goes to SLJIT_TEMPORARY_REG2. Note: if SLJIT_TEMPORARY_REG2 contains 0, the behaviour is undefined. */ #define SLJIT_SDIV 5 SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_op0(struct sljit_compiler *compiler, int op); /* Notes for MOV instructions: U = Mov with update (post form). If source or destination defined as SLJIT_MEM1(r1) or SLJIT_MEM2(r1, r2), r1 is increased by the sum of r2 and the constant argument UB = unsigned byte (8 bit) SB = signed byte (8 bit) UH = unsgined half (16 bit) SH = unsgined half (16 bit) */ /* Flags: - (never set any flags) */ #define SLJIT_MOV 6 /* Flags: - (never set any flags) */ #define SLJIT_MOV_UB 7 /* Flags: - (never set any flags) */ #define SLJIT_MOV_SB 8 /* Flags: - (never set any flags) */ #define SLJIT_MOV_UH 9 /* Flags: - (never set any flags) */ #define SLJIT_MOV_SH 10 /* Flags: - (never set any flags) */ #define SLJIT_MOV_UI 11 /* Flags: - (never set any flags) */ #define SLJIT_MOV_SI 12 /* Flags: - (never set any flags) */ #define SLJIT_MOVU 13 /* Flags: - (never set any flags) */ #define SLJIT_MOVU_UB 14 /* Flags: - (never set any flags) */ #define SLJIT_MOVU_SB 15 /* Flags: - (never set any flags) */ #define SLJIT_MOVU_UH 16 /* Flags: - (never set any flags) */ #define SLJIT_MOVU_SH 17 /* Flags: - (never set any flags) */ #define SLJIT_MOVU_UI 18 /* Flags: - (never set any flags) */ #define SLJIT_MOVU_SI 19 /* Flags: I | E | K */ #define SLJIT_NOT 20 /* Flags: I | E | O | K */ #define SLJIT_NEG 21 /* Count leading zeroes Flags: I | E | K */ #define SLJIT_CLZ 22 SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_op1(struct sljit_compiler *compiler, int op, int dst, sljit_w dstw, int src, sljit_w srcw); /* Flags: I | E | O | C | K */ #define SLJIT_ADD 23 /* Flags: I | C | K */ #define SLJIT_ADDC 24 /* Flags: I | E | S | U | O | C | K */ #define SLJIT_SUB 25 /* Flags: I | C | K */ #define SLJIT_SUBC 26 /* Note: integer mul Flags: I | O (see SLJIT_C_MUL_*) | K */ #define SLJIT_MUL 27 /* Flags: I | E | K */ #define SLJIT_AND 28 /* Flags: I | E | K */ #define SLJIT_OR 29 /* Flags: I | E | K */ #define SLJIT_XOR 30 /* Flags: I | E | K Let bit_length be the length of the shift operation: 32 or 64. If src2 is immediate, src2w is masked by (bit_length - 1). Otherwise, if the content of src2 is outside the range from 0 to bit_length - 1, the operation is undefined. */ #define SLJIT_SHL 31 /* Flags: I | E | K Let bit_length be the length of the shift operation: 32 or 64. If src2 is immediate, src2w is masked by (bit_length - 1). Otherwise, if the content of src2 is outside the range from 0 to bit_length - 1, the operation is undefined. */ #define SLJIT_LSHR 32 /* Flags: I | E | K Let bit_length be the length of the shift operation: 32 or 64. If src2 is immediate, src2w is masked by (bit_length - 1). Otherwise, if the content of src2 is outside the range from 0 to bit_length - 1, the operation is undefined. */ #define SLJIT_ASHR 33 SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_op2(struct sljit_compiler *compiler, int op, int dst, sljit_w dstw, int src1, sljit_w src1w, int src2, sljit_w src2w); /* The following function is a helper function for sljit_emit_op_custom. It returns with the real machine register index of any SLJIT_TEMPORARY SLJIT_SAVED or SLJIT_LOCALS register. Note: it returns with -1 for virtual registers (all EREGs on x86-32). Note: register returned by SLJIT_LOCALS_REG is not necessary the real stack pointer register of the target architecture. */ SLJIT_API_FUNC_ATTRIBUTE int sljit_get_register_index(int reg); /* Any instruction can be inserted into the instruction stream by sljit_emit_op_custom. It has a similar purpose as inline assembly. The size parameter must match to the instruction size of the target architecture: x86: 0 < size <= 15. The instruction argument can be byte aligned. Thumb2: if size == 2, the instruction argument must be 2 byte aligned. if size == 4, the instruction argument must be 4 byte aligned. Otherwise: size must be 4 and instruction argument must be 4 byte aligned. */ SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_op_custom(struct sljit_compiler *compiler, void *instruction, int size); /* Returns with non-zero if fpu is available. */ SLJIT_API_FUNC_ATTRIBUTE int sljit_is_fpu_available(void); /* Note: dst is the left and src is the right operand for SLJIT_FCMP. Note: NaN check is always performed. If SLJIT_C_FLOAT_NAN is set, the comparison result is unpredictable. Flags: E | S (see SLJIT_C_FLOAT_*) */ #define SLJIT_FCMP 34 /* Flags: - (never set any flags) */ #define SLJIT_FMOV 35 /* Flags: - (never set any flags) */ #define SLJIT_FNEG 36 /* Flags: - (never set any flags) */ #define SLJIT_FABS 37 SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_fop1(struct sljit_compiler *compiler, int op, int dst, sljit_w dstw, int src, sljit_w srcw); /* Flags: - (never set any flags) */ #define SLJIT_FADD 38 /* Flags: - (never set any flags) */ #define SLJIT_FSUB 39 /* Flags: - (never set any flags) */ #define SLJIT_FMUL 40 /* Flags: - (never set any flags) */ #define SLJIT_FDIV 41 SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_fop2(struct sljit_compiler *compiler, int op, int dst, sljit_w dstw, int src1, sljit_w src1w, int src2, sljit_w src2w); /* Label and jump instructions. */ SLJIT_API_FUNC_ATTRIBUTE struct sljit_label* sljit_emit_label(struct sljit_compiler *compiler); /* Invert conditional instruction: xor (^) with 0x1 */ #define SLJIT_C_EQUAL 0 #define SLJIT_C_ZERO 0 #define SLJIT_C_NOT_EQUAL 1 #define SLJIT_C_NOT_ZERO 1 #define SLJIT_C_LESS 2 #define SLJIT_C_GREATER_EQUAL 3 #define SLJIT_C_GREATER 4 #define SLJIT_C_LESS_EQUAL 5 #define SLJIT_C_SIG_LESS 6 #define SLJIT_C_SIG_GREATER_EQUAL 7 #define SLJIT_C_SIG_GREATER 8 #define SLJIT_C_SIG_LESS_EQUAL 9 #define SLJIT_C_OVERFLOW 10 #define SLJIT_C_NOT_OVERFLOW 11 #define SLJIT_C_MUL_OVERFLOW 12 #define SLJIT_C_MUL_NOT_OVERFLOW 13 #define SLJIT_C_FLOAT_EQUAL 14 #define SLJIT_C_FLOAT_NOT_EQUAL 15 #define SLJIT_C_FLOAT_LESS 16 #define SLJIT_C_FLOAT_GREATER_EQUAL 17 #define SLJIT_C_FLOAT_GREATER 18 #define SLJIT_C_FLOAT_LESS_EQUAL 19 #define SLJIT_C_FLOAT_NAN 20 #define SLJIT_C_FLOAT_NOT_NAN 21 #define SLJIT_JUMP 22 #define SLJIT_FAST_CALL 23 #define SLJIT_CALL0 24 #define SLJIT_CALL1 25 #define SLJIT_CALL2 26 #define SLJIT_CALL3 27 /* Fast calling method. See sljit_emit_fast_enter / sljit_emit_fast_return. */ /* The target can be changed during runtime (see: sljit_set_jump_addr). */ #define SLJIT_REWRITABLE_JUMP 0x1000 /* Emit a jump instruction. The destination is not set, only the type of the jump. type must be between SLJIT_C_EQUAL and SLJIT_CALL3 type can be combined (or'ed) with SLJIT_REWRITABLE_JUMP Flags: - (never set any flags) for both conditional and unconditional jumps. Flags: destroy all flags for calls. */ SLJIT_API_FUNC_ATTRIBUTE struct sljit_jump* sljit_emit_jump(struct sljit_compiler *compiler, int type); /* Basic arithmetic comparison. In most architectures it is implemented as an SLJIT_SUB operation (with SLJIT_UNUSED destination and setting appropriate flags) followed by a sljit_emit_jump. However some architectures (i.e: MIPS) may employ special optimizations here. It is suggested to use this comparison form when appropriate. type must be between SLJIT_C_EQUAL and SLJIT_C_SIG_LESS_EQUAL type can be combined (or'ed) with SLJIT_REWRITABLE_JUMP or SLJIT_INT_OP Flags: destroy flags. */ SLJIT_API_FUNC_ATTRIBUTE struct sljit_jump* sljit_emit_cmp(struct sljit_compiler *compiler, int type, int src1, sljit_w src1w, int src2, sljit_w src2w); /* Basic floating point comparison. In most architectures it is implemented as an SLJIT_FCMP operation (setting appropriate flags) followed by a sljit_emit_jump. However some architectures (i.e: MIPS) may employ special optimizations here. It is suggested to use this comparison form when appropriate. type must be between SLJIT_C_FLOAT_EQUAL and SLJIT_C_FLOAT_NOT_NAN type can be combined (or'ed) with SLJIT_REWRITABLE_JUMP Flags: destroy flags. Note: if either operand is NaN, the behaviour is undefined for type <= SLJIT_C_FLOAT_LESS_EQUAL. */ SLJIT_API_FUNC_ATTRIBUTE struct sljit_jump* sljit_emit_fcmp(struct sljit_compiler *compiler, int type, int src1, sljit_w src1w, int src2, sljit_w src2w); /* Set the destination of the jump to this label. */ SLJIT_API_FUNC_ATTRIBUTE void sljit_set_label(struct sljit_jump *jump, struct sljit_label* label); /* Only for jumps defined with SLJIT_REWRITABLE_JUMP flag. Note: use sljit_emit_ijump for fixed jumps. */ SLJIT_API_FUNC_ATTRIBUTE void sljit_set_target(struct sljit_jump *jump, sljit_uw target); /* Call function or jump anywhere. Both direct and indirect form type must be between SLJIT_JUMP and SLJIT_CALL3 Direct form: set src to SLJIT_IMM() and srcw to the address Indirect form: any other valid addressing mode Flags: - (never set any flags) for unconditional jumps. Flags: destroy all flags for calls. */ SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_ijump(struct sljit_compiler *compiler, int type, int src, sljit_w srcw); /* If op == SLJIT_MOV: Set dst to 1 if condition is fulfilled, 0 otherwise type must be between SLJIT_C_EQUAL and SLJIT_C_FLOAT_NOT_NAN Flags: - (never set any flags) If op == SLJIT_OR Dst is used as src as well, and set its lowest bit to 1 if the condition is fulfilled. Otherwise it does nothing. Flags: E | K Note: sljit_emit_cond_value does nothing, if dst is SLJIT_UNUSED (regardless of op). */ SLJIT_API_FUNC_ATTRIBUTE int sljit_emit_cond_value(struct sljit_compiler *compiler, int op, int dst, sljit_w dstw, int type); /* The constant can be changed runtime (see: sljit_set_const) Flags: - (never set any flags) */ SLJIT_API_FUNC_ATTRIBUTE struct sljit_const* sljit_emit_const(struct sljit_compiler *compiler, int dst, sljit_w dstw, sljit_w init_value); /* After the code generation the address for label, jump and const instructions are computed. Since these structures are freed sljit_free_compiler, the addresses must be preserved by the user program elsewere. */ static SLJIT_INLINE sljit_uw sljit_get_label_addr(struct sljit_label *label) { return label->addr; } static SLJIT_INLINE sljit_uw sljit_get_jump_addr(struct sljit_jump *jump) { return jump->addr; } static SLJIT_INLINE sljit_uw sljit_get_const_addr(struct sljit_const *const_) { return const_->addr; } /* Only the address is required to rewrite the code. */ SLJIT_API_FUNC_ATTRIBUTE void sljit_set_jump_addr(sljit_uw addr, sljit_uw new_addr); SLJIT_API_FUNC_ATTRIBUTE void sljit_set_const(sljit_uw addr, sljit_w new_constant); /* --------------------------------------------------------------------- */ /* Miscellaneous utility functions */ /* --------------------------------------------------------------------- */ #define SLJIT_MAJOR_VERSION 0 #define SLJIT_MINOR_VERSION 87 /* Get the human readable name of the platfrom. Can be useful for debugging on platforms like ARM, where ARM and Thumb2 functions can be mixed. */ SLJIT_API_FUNC_ATTRIBUTE SLJIT_CONST char* sljit_get_platform_name(void); /* Portble helper function to get an offset of a member. */ #define SLJIT_OFFSETOF(base, member) ((sljit_w)(&((base*)0x10)->member) - 0x10) #if (defined SLJIT_UTIL_GLOBAL_LOCK && SLJIT_UTIL_GLOBAL_LOCK) /* This global lock is useful to compile common functions. */ SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_grab_lock(void); SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_release_lock(void); #endif #if (defined SLJIT_UTIL_STACK && SLJIT_UTIL_STACK) /* The sljit_stack is a utiliy feature of sljit, which allocates a writable memory region between base (inclusive) and limit (exclusive). Both base and limit is a pointer, and base is always <= than limit. This feature uses the "address space reserve" feature of modern operating systems. Basically we don't need to allocate a huge memory block in one step for the worst case, we can start with a smaller chunk and extend it later. Since the address space is reserved, the data never copied to other regions, thus it is safe to store pointers here. */ /* Note: The base field is aligned to PAGE_SIZE bytes (usually 4k or more). Note: stack growing should not happen in small steps: 4k, 16k or even bigger growth is better. Note: this structure may not be supported by all operating systems. Some kind of fallback mechanism is suggested when SLJIT_UTIL_STACK is not defined. */ struct sljit_stack { /* User data, anything can be stored here. Starting with the same value as base. */ sljit_uw top; /* These members are read only. */ sljit_uw base; sljit_uw limit; sljit_uw max_limit; }; /* Returns NULL if unsuccessful. Note: limit and max_limit contains the size for stack allocation Note: the top field is initialized to base. */ SLJIT_API_FUNC_ATTRIBUTE struct sljit_stack* SLJIT_CALL sljit_allocate_stack(sljit_uw limit, sljit_uw max_limit); SLJIT_API_FUNC_ATTRIBUTE void SLJIT_CALL sljit_free_stack(struct sljit_stack* stack); /* Can be used to increase (allocate) or decrease (free) the memory area. Returns with a non-zero value if unsuccessful. If new_limit is greater than max_limit, it will fail. It is very easy to implement a stack data structure, since the growth ratio can be added to the current limit, and sljit_stack_resize will do all the necessary checks. The fields of the stack are not changed if sljit_stack_resize fails. */ SLJIT_API_FUNC_ATTRIBUTE sljit_w SLJIT_CALL sljit_stack_resize(struct sljit_stack* stack, sljit_uw new_limit); #endif /* (defined SLJIT_UTIL_STACK && SLJIT_UTIL_STACK) */ #if !(defined SLJIT_INDIRECT_CALL && SLJIT_INDIRECT_CALL) /* Get the entry address of a given function. */ #define SLJIT_FUNC_OFFSET(func_name) ((sljit_w)func_name) #else /* !(defined SLJIT_INDIRECT_CALL && SLJIT_INDIRECT_CALL) */ /* All JIT related code should be placed in the same context (library, binary, etc.). */ #define SLJIT_FUNC_OFFSET(func_name) ((sljit_w)*(void**)func_name) /* For powerpc64, the function pointers point to a context descriptor. */ struct sljit_function_context { sljit_w addr; sljit_w r2; sljit_w r11; }; /* Fill the context arguments using the addr and the function. If func_ptr is NULL, it will not be set to the address of context If addr is NULL, the function address also comes from the func pointer. */ SLJIT_API_FUNC_ATTRIBUTE void sljit_set_function_context(void** func_ptr, struct sljit_function_context* context, sljit_w addr, void* func); #endif /* !(defined SLJIT_INDIRECT_CALL && SLJIT_INDIRECT_CALL) */ #endif /* _SLJIT_LIR_H_ */
35,713
C++
.h
719
46.823366
162
0.711794
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
16,155
sljitConfigInternal.h
AutoHotkey_AutoHotkey/source/lib_pcre/pcre/sljit/sljitConfigInternal.h
/* * Stack-less Just-In-Time compiler * * Copyright 2009-2012 Zoltan Herczeg (hzmester@freemail.hu). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SLJIT_CONFIG_INTERNAL_H_ #define _SLJIT_CONFIG_INTERNAL_H_ /* SLJIT defines the following macros depending on the target architecture: Feature detection (boolean) macros: SLJIT_32BIT_ARCHITECTURE : 32 bit architecture SLJIT_64BIT_ARCHITECTURE : 64 bit architecture SLJIT_WORD_SHIFT : the shift required to apply when accessing a sljit_w/sljit_uw array by index SLJIT_FLOAT_SHIFT : the shift required to apply when accessing a double array by index SLJIT_LITTLE_ENDIAN : little endian architecture SLJIT_BIG_ENDIAN : big endian architecture SLJIT_UNALIGNED : allows unaligned memory accesses for non-fpu operations (only!) SLJIT_INDIRECT_CALL : see SLJIT_FUNC_OFFSET() for more information Types and useful macros: sljit_b, sljit_ub : signed and unsigned 8 bit byte sljit_h, sljit_uh : signed and unsigned 16 bit half-word (short) type sljit_i, sljit_ui : signed and unsigned 32 bit integer type sljit_w, sljit_uw : signed and unsigned machine word, enough to store a pointer (same as intptr_t) SLJIT_CALL : C calling convention define for both calling JIT form C and C callbacks for JIT SLJIT_W(number) : defining 64 bit constants on 64 bit architectures (compiler independent helper) */ #if !((defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) \ || (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) \ || (defined SLJIT_CONFIG_ARM_V5 && SLJIT_CONFIG_ARM_V5) \ || (defined SLJIT_CONFIG_ARM_V7 && SLJIT_CONFIG_ARM_V7) \ || (defined SLJIT_CONFIG_ARM_THUMB2 && SLJIT_CONFIG_ARM_THUMB2) \ || (defined SLJIT_CONFIG_PPC_32 && SLJIT_CONFIG_PPC_32) \ || (defined SLJIT_CONFIG_PPC_64 && SLJIT_CONFIG_PPC_64) \ || (defined SLJIT_CONFIG_MIPS_32 && SLJIT_CONFIG_MIPS_32) \ || (defined SLJIT_CONFIG_AUTO && SLJIT_CONFIG_AUTO) \ || (defined SLJIT_CONFIG_UNSUPPORTED && SLJIT_CONFIG_UNSUPPORTED)) #error "An architecture must be selected" #endif /* Sanity check. */ #if (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) \ + (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) \ + (defined SLJIT_CONFIG_ARM_V5 && SLJIT_CONFIG_ARM_V5) \ + (defined SLJIT_CONFIG_ARM_V7 && SLJIT_CONFIG_ARM_V7) \ + (defined SLJIT_CONFIG_ARM_THUMB2 && SLJIT_CONFIG_ARM_THUMB2) \ + (defined SLJIT_CONFIG_PPC_32 && SLJIT_CONFIG_PPC_32) \ + (defined SLJIT_CONFIG_PPC_64 && SLJIT_CONFIG_PPC_64) \ + (defined SLJIT_CONFIG_MIPS_32 && SLJIT_CONFIG_MIPS_32) \ + (defined SLJIT_CONFIG_AUTO && SLJIT_CONFIG_AUTO) \ + (defined SLJIT_CONFIG_UNSUPPORTED && SLJIT_CONFIG_UNSUPPORTED) >= 2 #error "Multiple architectures are selected" #endif /* Auto select option (requires compiler support) */ #if (defined SLJIT_CONFIG_AUTO && SLJIT_CONFIG_AUTO) #ifndef _WIN32 #if defined(__i386__) || defined(__i386) #define SLJIT_CONFIG_X86_32 1 #elif defined(__x86_64__) #define SLJIT_CONFIG_X86_64 1 #elif defined(__arm__) || defined(__ARM__) #ifdef __thumb2__ #define SLJIT_CONFIG_ARM_THUMB2 1 #elif defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) #define SLJIT_CONFIG_ARM_V7 1 #else #define SLJIT_CONFIG_ARM_V5 1 #endif #elif defined(__ppc64__) || defined(__powerpc64__) #define SLJIT_CONFIG_PPC_64 1 #elif defined(__ppc__) || defined(__powerpc__) #define SLJIT_CONFIG_PPC_32 1 #elif defined(__mips__) #define SLJIT_CONFIG_MIPS_32 1 #else /* Unsupported architecture */ #define SLJIT_CONFIG_UNSUPPORTED 1 #endif #else /* !_WIN32 */ #if defined(_M_X64) || defined(__x86_64__) #define SLJIT_CONFIG_X86_64 1 #elif defined(_ARM_) #define SLJIT_CONFIG_ARM_V5 1 #else #define SLJIT_CONFIG_X86_32 1 #endif #endif /* !WIN32 */ #endif /* SLJIT_CONFIG_AUTO */ #if (defined SLJIT_CONFIG_UNSUPPORTED && SLJIT_CONFIG_UNSUPPORTED) #undef SLJIT_EXECUTABLE_ALLOCATOR #endif #if !(defined SLJIT_STD_MACROS_DEFINED && SLJIT_STD_MACROS_DEFINED) /* These libraries are needed for the macros below. */ #include <stdlib.h> #include <string.h> #endif /* STD_MACROS_DEFINED */ /* General macros: Note: SLJIT is designed to be independent from them as possible. In release mode (SLJIT_DEBUG is not defined) only the following macros are needed: */ #ifndef SLJIT_MALLOC #define SLJIT_MALLOC(size) malloc(size) #endif #ifndef SLJIT_FREE #define SLJIT_FREE(ptr) free(ptr) #endif #ifndef SLJIT_MEMMOVE #define SLJIT_MEMMOVE(dest, src, len) memmove(dest, src, len) #endif #ifndef SLJIT_ZEROMEM #define SLJIT_ZEROMEM(dest, len) memset(dest, 0, len) #endif #if !defined(SLJIT_LIKELY) && !defined(SLJIT_UNLIKELY) #if defined(__GNUC__) && (__GNUC__ >= 3) #define SLJIT_LIKELY(x) __builtin_expect((x), 1) #define SLJIT_UNLIKELY(x) __builtin_expect((x), 0) #else #define SLJIT_LIKELY(x) (x) #define SLJIT_UNLIKELY(x) (x) #endif #endif /* !defined(SLJIT_LIKELY) && !defined(SLJIT_UNLIKELY) */ #ifndef SLJIT_INLINE /* Inline functions. */ #define SLJIT_INLINE __inline #endif #ifndef SLJIT_CONST /* Const variables. */ #define SLJIT_CONST const #endif #ifndef SLJIT_UNUSED_ARG /* Unused arguments. */ #define SLJIT_UNUSED_ARG(arg) (void)arg #endif #if (defined SLJIT_CONFIG_STATIC && SLJIT_CONFIG_STATIC) /* Static ABI functions. For all-in-one programs. */ #if defined(__GNUC__) /* Disable unused warnings in gcc. */ #define SLJIT_API_FUNC_ATTRIBUTE static __attribute__((unused)) #else #define SLJIT_API_FUNC_ATTRIBUTE static #endif #else #define SLJIT_API_FUNC_ATTRIBUTE #endif /* (defined SLJIT_CONFIG_STATIC && SLJIT_CONFIG_STATIC) */ #ifndef SLJIT_CACHE_FLUSH #if (defined SLJIT_CONFIG_PPC_32 && SLJIT_CONFIG_PPC_32) || (defined SLJIT_CONFIG_PPC_64 && SLJIT_CONFIG_PPC_64) /* The __clear_cache() implementation of GCC is a dummy function on PowerPC. */ #define SLJIT_CACHE_FLUSH(from, to) \ ppc_cache_flush((from), (to)) #elif (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) || (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) /* Not required to implement on archs with unified caches. */ #define SLJIT_CACHE_FLUSH(from, to) #else /* Calls __ARM_NR_cacheflush on ARM-Linux. */ #define SLJIT_CACHE_FLUSH(from, to) \ __clear_cache((char*)(from), (char*)(to)) #endif #endif /* !SLJIT_CACHE_FLUSH */ /* 8 bit byte type. */ typedef unsigned char sljit_ub; typedef signed char sljit_b; /* 16 bit half-word type. */ typedef unsigned short int sljit_uh; typedef signed short int sljit_h; /* 32 bit integer type. */ typedef unsigned int sljit_ui; typedef signed int sljit_i; /* Machine word type. Can encapsulate a pointer. 32 bit for 32 bit machines. 64 bit for 64 bit machines. */ #if (defined SLJIT_CONFIG_UNSUPPORTED && SLJIT_CONFIG_UNSUPPORTED) /* Just to have something. */ #define SLJIT_WORD_SHIFT 0 typedef unsigned long int sljit_uw; typedef long int sljit_w; #elif !(defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) && !(defined SLJIT_CONFIG_PPC_64 && SLJIT_CONFIG_PPC_64) #define SLJIT_32BIT_ARCHITECTURE 1 #define SLJIT_WORD_SHIFT 2 typedef unsigned int sljit_uw; typedef int sljit_w; #else #define SLJIT_64BIT_ARCHITECTURE 1 #define SLJIT_WORD_SHIFT 3 #ifdef _WIN32 typedef unsigned __int64 sljit_uw; typedef __int64 sljit_w; #else typedef unsigned long int sljit_uw; typedef long int sljit_w; #endif #endif /* Double precision. */ #define SLJIT_FLOAT_SHIFT 3 #ifndef SLJIT_W /* Defining long constants. */ #if (defined SLJIT_64BIT_ARCHITECTURE && SLJIT_64BIT_ARCHITECTURE) #define SLJIT_W(w) (w##ll) #else #define SLJIT_W(w) (w) #endif #endif /* !SLJIT_W */ #ifndef SLJIT_CALL /* ABI (Application Binary Interface) types. */ #if (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) #if defined(__GNUC__) #define SLJIT_CALL __attribute__ ((fastcall)) #define SLJIT_X86_32_FASTCALL 1 #elif defined(_WIN32) #ifdef __BORLANDC__ #define SLJIT_CALL __msfastcall #else /* __BORLANDC__ */ #define SLJIT_CALL __fastcall #endif /* __BORLANDC__ */ #define SLJIT_X86_32_FASTCALL 1 #else /* defined(_WIN32) */ #define SLJIT_CALL __stdcall #endif #else /* Other architectures. */ #define SLJIT_CALL #endif /* SLJIT_CONFIG_X86_32 */ #endif /* !SLJIT_CALL */ #if !defined(SLJIT_BIG_ENDIAN) && !defined(SLJIT_LITTLE_ENDIAN) /* These macros are useful for the application. */ #if (defined SLJIT_CONFIG_PPC_32 && SLJIT_CONFIG_PPC_32) || (defined SLJIT_CONFIG_PPC_64 && SLJIT_CONFIG_PPC_64) #define SLJIT_BIG_ENDIAN 1 #elif (defined SLJIT_CONFIG_MIPS_32 && SLJIT_CONFIG_MIPS_32) #ifdef __MIPSEL__ #define SLJIT_LITTLE_ENDIAN 1 #else #define SLJIT_BIG_ENDIAN 1 #endif #else #define SLJIT_LITTLE_ENDIAN 1 #endif #endif /* !defined(SLJIT_BIG_ENDIAN) && !defined(SLJIT_LITTLE_ENDIAN) */ /* Sanity check. */ #if (defined SLJIT_BIG_ENDIAN && SLJIT_BIG_ENDIAN) && (defined SLJIT_LITTLE_ENDIAN && SLJIT_LITTLE_ENDIAN) #error "Exactly one endianness must be selected" #endif #if !(defined SLJIT_BIG_ENDIAN && SLJIT_BIG_ENDIAN) && !(defined SLJIT_LITTLE_ENDIAN && SLJIT_LITTLE_ENDIAN) #error "Exactly one endianness must be selected" #endif #if (defined SLJIT_CONFIG_PPC_64 && SLJIT_CONFIG_PPC_64) /* It seems ppc64 compilers use an indirect addressing for functions. It makes things really complicated. */ #define SLJIT_INDIRECT_CALL 1 #endif #ifndef SLJIT_SSE2 #if (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) || (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) /* Turn on SSE2 support on x86 (operating on doubles). (Better performance than legacy fpu instructions). */ #define SLJIT_SSE2 1 #if (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) /* Auto detect SSE2 support using CPUID. On 64 bit x86 cpus, sse2 must be present. */ #define SLJIT_SSE2_AUTO 1 #endif #endif /* (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) || (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) */ #endif /* !SLJIT_SSE2 */ #ifndef SLJIT_UNALIGNED #if (defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) \ || (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) \ || (defined SLJIT_CONFIG_ARM_V7 && SLJIT_CONFIG_ARM_V7) \ || (defined SLJIT_CONFIG_ARM_THUMB2 && SLJIT_CONFIG_ARM_THUMB2) \ || (defined SLJIT_CONFIG_PPC_32 && SLJIT_CONFIG_PPC_32) \ || (defined SLJIT_CONFIG_PPC_64 && SLJIT_CONFIG_PPC_64) #define SLJIT_UNALIGNED 1 #endif #endif /* !SLJIT_UNALIGNED */ #if (defined SLJIT_EXECUTABLE_ALLOCATOR && SLJIT_EXECUTABLE_ALLOCATOR) SLJIT_API_FUNC_ATTRIBUTE void* sljit_malloc_exec(sljit_uw size); SLJIT_API_FUNC_ATTRIBUTE void sljit_free_exec(void* ptr); #define SLJIT_MALLOC_EXEC(size) sljit_malloc_exec(size) #define SLJIT_FREE_EXEC(ptr) sljit_free_exec(ptr) #endif #if (defined SLJIT_DEBUG && SLJIT_DEBUG) || (defined SLJIT_VERBOSE && SLJIT_VERBOSE) #include <stdio.h> #endif #if (defined SLJIT_DEBUG && SLJIT_DEBUG) /* Feel free to redefine these two macros. */ #ifndef SLJIT_ASSERT #define SLJIT_HALT_PROCESS() \ *((int*)0) = 0 #define SLJIT_ASSERT(x) \ do { \ if (SLJIT_UNLIKELY(!(x))) { \ printf("Assertion failed at " __FILE__ ":%d\n", __LINE__); \ SLJIT_HALT_PROCESS(); \ } \ } while (0) #endif /* !SLJIT_ASSERT */ #ifndef SLJIT_ASSERT_STOP #define SLJIT_ASSERT_STOP() \ do { \ printf("Should never been reached " __FILE__ ":%d\n", __LINE__); \ SLJIT_HALT_PROCESS(); \ } while (0) #endif /* !SLJIT_ASSERT_STOP */ #else /* (defined SLJIT_DEBUG && SLJIT_DEBUG) */ #undef SLJIT_ASSERT #undef SLJIT_ASSERT_STOP #define SLJIT_ASSERT(x) \ do { } while (0) #define SLJIT_ASSERT_STOP() \ do { } while (0) #endif /* (defined SLJIT_DEBUG && SLJIT_DEBUG) */ #ifndef SLJIT_COMPILE_ASSERT /* Should be improved eventually. */ #define SLJIT_COMPILE_ASSERT(x, description) \ SLJIT_ASSERT(x) #endif /* !SLJIT_COMPILE_ASSERT */ #endif
12,957
C++
.h
330
37.524242
121
0.734717
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
16,156
sljitConfig.h
AutoHotkey_AutoHotkey/source/lib_pcre/pcre/sljit/sljitConfig.h
/* * Stack-less Just-In-Time compiler * * Copyright 2009-2012 Zoltan Herczeg (hzmester@freemail.hu). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SLJIT_CONFIG_H_ #define _SLJIT_CONFIG_H_ /* --------------------------------------------------------------------- */ /* Architecture */ /* --------------------------------------------------------------------- */ /* Architecture selection */ /* #define SLJIT_CONFIG_X86_32 1 */ /* #define SLJIT_CONFIG_X86_64 1 */ /* #define SLJIT_CONFIG_ARM_V5 1 */ /* #define SLJIT_CONFIG_ARM_V7 1 */ /* #define SLJIT_CONFIG_ARM_THUMB2 1 */ /* #define SLJIT_CONFIG_PPC_32 1 */ /* #define SLJIT_CONFIG_PPC_64 1 */ /* #define SLJIT_CONFIG_MIPS_32 1 */ /* #define SLJIT_CONFIG_AUTO 1 */ /* #define SLJIT_CONFIG_UNSUPPORTED 1 */ /* --------------------------------------------------------------------- */ /* Utilities */ /* --------------------------------------------------------------------- */ /* Useful for thread-safe compiling of global functions. */ #ifndef SLJIT_UTIL_GLOBAL_LOCK /* Enabled by default */ #define SLJIT_UTIL_GLOBAL_LOCK 1 #endif /* Implements a stack like data structure (by using mmap / VirtualAlloc). */ #ifndef SLJIT_UTIL_STACK /* Enabled by default */ #define SLJIT_UTIL_STACK 1 #endif /* --------------------------------------------------------------------- */ /* Configuration */ /* --------------------------------------------------------------------- */ /* If SLJIT_STD_MACROS_DEFINED is not defined, the application should define SLJIT_MALLOC, SLJIT_FREE, SLJIT_MEMMOVE, and NULL. */ #ifndef SLJIT_STD_MACROS_DEFINED /* Disabled by default. */ #define SLJIT_STD_MACROS_DEFINED 0 #endif /* Executable code allocation: If SLJIT_EXECUTABLE_ALLOCATOR is not defined, the application should define both SLJIT_MALLOC_EXEC and SLJIT_FREE_EXEC. */ #ifndef SLJIT_EXECUTABLE_ALLOCATOR /* Enabled by default. */ #define SLJIT_EXECUTABLE_ALLOCATOR 1 #endif /* Debug checks (assertions, etc.). */ #ifndef SLJIT_DEBUG /* Enabled by default */ #define SLJIT_DEBUG 1 #endif /* Verbose operations */ #ifndef SLJIT_VERBOSE /* Enabled by default */ #define SLJIT_VERBOSE 1 #endif /* See the beginning of sljitConfigInternal.h */ #endif
3,692
C++
.h
82
43.414634
94
0.625661
AutoHotkey/AutoHotkey
9,046
932
17
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
16,157
main.cpp
BlackINT3_OpenArk/src/OpenArk/main.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "../openark/openark.h" #include "common/common.h" //for qt static link #include <QtWidgets/QApplication> #include <QtPlugin> Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) Q_IMPORT_PLUGIN(QICOPlugin) int OpenArkInit(int argc, char *argv[]) { UNONE::SeEnableDebugPrivilege(); bool is_ark64 = UNONE::PeX64((CHAR*)GetModuleHandleW(NULL)); if (!is_ark64 && UNONE::OsIs64()) { auto &&path = UNONE::PsGetProcessDirW() + L"\\OpenArk64.exe"; if (UNONE::FsIsExistedW(path)) { UNONE::PsCreateProcessW(path); exit(0); } } app = new QApplication(argc, argv); app->setWindowIcon(QIcon(":/OpenArk/OpenArk.ico")); app_tr = new QTranslator(); QFont font = qApp->font(); font.setPixelSize(12); font.setFamily("Microsoft YaHei"); qApp->setFont(font); OpenArkConfig::Instance()->Init(); OpenArkLanguage::Instance()->ChangeLanguage(OpenArkConfig::Instance()->GetLang(CONF_GET)); return 0; } int OpenArkUninit(int argc, char *argv[]) { delete app_tr; delete app; app_tr = nullptr; app = nullptr; return 0; } int main(int argc, char *argv[]) { OpenArkInit(argc, argv); auto w = new OpenArk; w->show(); auto err = app->exec(); delete w; OpenArkUninit(argc, argv); return err; }
2,003
C++
.cpp
62
30.532258
91
0.683066
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,158
coderkit.cpp
BlackINT3_OpenArk/src/OpenArk/coderkit/coderkit.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "coderkit.h" #include "../common/common.h" #include "../openark/openark.h" #include <locale> #include <codecvt> #if (!_DLL) && (_MSC_VER >= 1900 /* VS 2015*/) && (_MSC_VER <= 1911 /* VS 2017 */) std::locale::id std::codecvt<char16_t, char, _Mbstatet>::id; #endif typedef std::wstring_convert<std::codecvt_utf8<int16_t>, int16_t> U16Convert; typedef U16Convert::wide_string U16; typedef std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> U32Convert; typedef U32Convert::wide_string U32; // Algorithm index struct { int s = 0; int base64 = s++; int crc32 = s++; int md5 = s++; int sha1 = s++; int rc4 = s++; int urlencode = s++; int urldecode = s++; int urlencodeURL = s++; int urldecodeURL = s++; } IDX; struct { int s = 0; int x64 = s++; int x86 = s++; int x86_16 = s++; int arm64 = s++; int arm32 = s++; int arm16 = s++; int mips64 = s++; int mips32 = s++; int mips16 = s++; } CPUPLATFORM_IDX; enum InstrPlatform { X64, X86, X86_16, ARM64, ARM32, ARM16, MIPS64, MIPS32, MIPS16, }; enum ByteOrder { LITTLE_ENDIAN, BIG_ENDIAN, }; CoderKit::CoderKit(QWidget* parent, int tabid) : CommonMainTabObject::CommonMainTabObject((OpenArk*)parent) { ui.setupUi(this); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); radio_group_type_.addButton(ui.nullRadio_2, 0); radio_group_type_.addButton(ui.spaceRadio_2, 1); radio_group_type_.addButton(ui.slashxRadio_2, 2); radio_group_type_.addButton(ui.assembleRadio, 3); radio_group_interval_.addButton(ui.byteRadio, 0); radio_group_interval_.addButton(ui.twoBytesRadio, 1); radio_group_interval_.addButton(ui.fourBytesRadio, 2); ui.nullRadio_2->setChecked(true); ui.byteRadio->setChecked(true); connect(ui.nullRadio_2, SIGNAL(clicked()), this, SLOT(onFormatChanged())); connect(ui.spaceRadio_2, SIGNAL(clicked()), this, SLOT(onFormatChanged())); connect(ui.slashxRadio_2, SIGNAL(clicked()), this, SLOT(onFormatChanged())); connect(ui.assembleRadio, SIGNAL(clicked()), this, SLOT(onFormatChanged())); connect(ui.byteRadio, SIGNAL(clicked()), this, SLOT(onFormatChanged())); connect(ui.twoBytesRadio, SIGNAL(clicked()), this, SLOT(onFormatChanged())); connect(ui.fourBytesRadio, SIGNAL(clicked()), this, SLOT(onFormatChanged())); connect(ui.textEdit, SIGNAL(textChanged()), this, SLOT(onCodeTextChanged())); connect(ui.defaultEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.asciiEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.unicodeEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.utf7Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.utf8Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.utf16Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.butf16Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.utf32Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.butf32Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.gbkEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.big5Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.cp866Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &))); connect(ui.doserrEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onWindowsErrorTextChanged(const QString &))); connect(ui.ntstatusEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onWindowsErrorTextChanged(const QString &))); connect(ui.hresultEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onWindowsErrorTextChanged(const QString &))); connect(ui.msgidBtn, SIGNAL(clicked()), this, SLOT(onMessageId())); alg_idx_ = 0; is_user_ = false; is_format_changed_ = false; onAlgIndexChanged(alg_idx_); // ui.typeBox->insertItem(IDX.base64, "Base64"); // ui.typeBox->insertItem(IDX.crc32, "CRC32"); // ui.typeBox->insertItem(IDX.md5, "MD5"); // ui.typeBox->insertItem(IDX.sha1, "SHA1"); // ui.typeBox->insertItem(IDX.rc4, "RC4"); ui.base64Radio->setChecked(true); connect(ui.base64Radio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged())); connect(ui.crc32Radio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged())); connect(ui.md5Radio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged())); connect(ui.sha1Radio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged())); connect(ui.urlencodeRadio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged())); connect(ui.urldecodeRadio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged())); // connect(ui.urlencodeURLRadio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged())); // connect(ui.urldecodeURLRadio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged())); //connect(ui.typeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onAlgIndexChanged(int))); connect(ui.plainEdit, SIGNAL(textChanged()), this, SLOT(onAlgPlainChanged())); connect(ui.cipherEdit, SIGNAL(textChanged()), this, SLOT(onAlgPlainChanged())); //connect(ui.keyEdit, SIGNAL(textChanged()), this, SLOT(onAlgPlainChanged())); InitAsmToolsView(); CommonMainTabObject::Init(ui.tabWidget, tabid); } CoderKit::~CoderKit() { } void CoderKit::onTabChanged(int index) { CommonMainTabObject::onTabChanged(index); } void CoderKit::onCodeTextChanged() { std::wstring data; std::string str; QObject* sender = QObject::sender(); if (sender == ui.textEdit || is_format_changed_) { data = ui.textEdit->toPlainText().toStdWString(); is_format_changed_ = false; } UpdateEditCodeText(data, sender); } void CoderKit::onCodeTextChanged(const QString & text) { QLineEdit* sender = qobject_cast<QLineEdit*>(QObject::sender()); sender->setStyleSheet("background-color:white"); try { std::string str = sender->text().toStdString(); std::wstring data; auto InputFilter = [&](std::string& input) { UNONE::StrReplaceA(input, "-"); UNONE::StrReplaceA(input, " "); UNONE::StrReplaceA(input, "0x"); UNONE::StrReplaceA(input, "h"); UNONE::StrReplaceA(input, "\\x"); sender->setText(StrToQ(input)); }; is_user_ = ui.defaultEdit->isModified() || ui.asciiEdit->isModified() || ui.unicodeEdit->isModified() || ui.utf7Edit->isModified() || ui.utf8Edit->isModified() || ui.utf16Edit->isModified() || ui.butf16Edit->isModified() || ui.utf32Edit->isModified() || ui.butf32Edit->isModified() || ui.gbkEdit->isModified() || ui.big5Edit->isModified() || ui.cp866Edit->isModified(); if (is_user_) { InputFilter(str); } else { return; } str = UNONE::StrHexStrToStreamA(str); if (sender == ui.defaultEdit) { data = UNONE::StrACPToWide(str); } else if (sender == ui.asciiEdit) { data = UNONE::StrCodeToWide(437, str); } else if (sender == ui.unicodeEdit) { data = std::wstring((wchar_t*)str.c_str(), str.size() / 2); } else if (sender == ui.utf7Edit) { data = UNONE::StrCodeToWide(CP_UTF7, str); } else if (sender == ui.utf8Edit) { data = UNONE::StrCodeToWide(CP_UTF8, str); } else if (sender == ui.utf16Edit) { data = std::wstring((wchar_t*)str.c_str(), str.size() / 2); } else if (sender == ui.butf16Edit) { str = UNONE::StrReverseA(str, 2); data = std::wstring((wchar_t*)str.c_str(), str.size() / 2); } else if (sender == ui.utf32Edit) { U32 utf32((int32_t*)str.c_str(), str.size() / 4); data = UNONE::StrUTF8ToWide(U32Convert().to_bytes(utf32)); } else if (sender == ui.butf32Edit) { str = UNONE::StrReverseA(str, 4); U32 utf32((int32_t*)str.c_str(), str.size() / 4); data = UNONE::StrUTF8ToWide(U32Convert().to_bytes(utf32)); } else if (sender == ui.gbkEdit) { data = UNONE::StrCodeToWide(936, str); } else if (sender == ui.big5Edit) { data = UNONE::StrCodeToWide(950, str); } else if (sender == ui.cp866Edit) { data = UNONE::StrCodeToWide(866, str); } UpdateEditCodeText(data, sender); } catch(...) { sender->setStyleSheet("background-color:red"); } } void CoderKit::onWindowsErrorTextChanged(const QString & text) { std::string number = text.toStdString(); QLineEdit* sender = qobject_cast<QLineEdit*>(QObject::sender()); if (sender == ui.doserrEdit) { auto err = VariantInt(number, 10); auto msg = UNONE::StrFormatW(L"%d: %s", err, UNONE::OsDosErrorMsgW(err).c_str()); ui.msgEdit->setText(WStrToQ(msg)); } else if (sender == ui.ntstatusEdit) { auto err = VariantInt(number, 16); auto doserr = UNONE::OsNtToDosError((VariantInt(number, 16))); auto msg = UNONE::StrFormatW(L"%X: %s", err, UNONE::OsDosErrorMsgW(doserr).c_str()); ui.doserrEdit->setText(QString("%1").arg(doserr)); ui.msgEdit->setText(WStrToQ(msg)); } else if (sender == ui.hresultEdit) { auto hr = VariantInt(number, 16); auto doserr = hr & 0xFFFF; ui.doserrEdit->setText(QString("%1").arg(doserr)); auto msg = UNONE::StrFormatW(L"%X: %s", hr, UNONE::OsDosErrorMsgW(doserr).c_str()); ui.msgEdit->setText(WStrToQ(msg)); } } void CoderKit::onMessageId() { parent_->onExecCmd(L".msg"); MsgBoxInfo(tr("Open console to view result")); } void CoderKit::onAlgIndexChanged(int index) { alg_idx_ = index; auto e_key = ui.keyEdit; auto e_plain = ui.plainEdit; auto l_plain = ui.keyLabel; auto e_cipher = ui.cipherEdit; e_key->hide(); l_plain->hide(); if (index == IDX.rc4) { e_key->show(); l_plain->show(); UpdateAlgorithmText(false); return; } UpdateAlgorithmText(true); return; } void CoderKit::onAlgPlainChanged() { auto sender = qobject_cast<QTextEdit*>(QObject::sender()); if (sender == ui.plainEdit) { UpdateAlgorithmText(true); } else if (sender == ui.cipherEdit) { UpdateAlgorithmText(false); } else if (sender == ui.keyEdit) { UpdateAlgorithmText(true); } auto sender_radio = qobject_cast<QRadioButton*>(QObject::sender()); if (sender_radio == ui.base64Radio) { alg_idx_ = 0; } else if (sender_radio == ui.crc32Radio) { alg_idx_ = 1; } else if (sender_radio == ui.md5Radio) { alg_idx_ = 2; } else if (sender_radio == ui.sha1Radio) { alg_idx_ = 3; } else if (sender_radio == ui.urlencodeRadio) { alg_idx_ = 5; } else if (sender_radio == ui.urldecodeRadio) { alg_idx_ = 6; // } else if (sender_radio == ui.urlencodeURLRadio) { // alg_idx_ = 7; // } else if (sender_radio == ui.urldecodeURLRadio) { // alg_idx_ = 8; } else { return; } UpdateAlgorithmText(true); } void CoderKit::onFormatChanged() { is_format_changed_ = true; onCodeTextChanged(); } void CoderKit::InitAsmToolsView() { ui.splitter->setStretchFactor(0, 1); ui.splitter->setStretchFactor(1, 2); ui.nullRadio->setChecked(true); connect(ui.asmBtn, &QPushButton::clicked, this, [&]() { if (!UNONE::OsIs64()) { MsgBoxError("The feature not support 32bits os."); return; } ByteOrder byteorder = LITTLE_ENDIAN; auto byteorder_idx = ui.byteorderBox->currentIndex(); if (byteorder_idx == 0) byteorder = LITTLE_ENDIAN; else if (byteorder_idx == 1) byteorder = BIG_ENDIAN; InstrPlatform cpu = X64; auto idx = ui.platformBox->currentIndex(); if (idx == CPUPLATFORM_IDX.x64) cpu = X64; else if (idx == CPUPLATFORM_IDX.x86) cpu = X86; else if (idx == CPUPLATFORM_IDX.x86_16) cpu = X86_16; else if (idx == CPUPLATFORM_IDX.arm64) cpu = ARM64; else if (idx == CPUPLATFORM_IDX.arm32) cpu = ARM32; else if (idx == CPUPLATFORM_IDX.arm16) cpu = ARM16; else if (idx == CPUPLATFORM_IDX.mips64) cpu = MIPS64; else if (idx == CPUPLATFORM_IDX.mips32) cpu = MIPS32; else if (idx == CPUPLATFORM_IDX.mips16) cpu = MIPS16; auto &&in = ui.asmEdit->toPlainText().toStdString(); std::string formats; if (ui.nullRadio->isChecked()) formats = ""; else if (ui.spaceRadio->isChecked()) formats = " "; else if (ui.slashxRadio->isChecked()) formats = "\\x"; auto &&out = Rasm2Asm(in, cpu, byteorder, formats); ui.disasmEdit->setText(out); }); connect(ui.disasmBtn, &QPushButton::clicked, this, [&]() { if (!UNONE::OsIs64()) { MsgBoxError("The feature not support 32bits os."); return; } ByteOrder byteorder = LITTLE_ENDIAN; auto byteorder_idx = ui.byteorderBox->currentIndex(); if (byteorder_idx == 0) byteorder = LITTLE_ENDIAN; else if (byteorder_idx == 1) byteorder = BIG_ENDIAN; InstrPlatform cpu = X64; auto idx = ui.platformBox->currentIndex(); if (idx == CPUPLATFORM_IDX.x64) cpu = X64; else if (idx == CPUPLATFORM_IDX.x86) cpu = X86; else if (idx == CPUPLATFORM_IDX.x86_16) cpu = X86_16; else if (idx == CPUPLATFORM_IDX.arm64) cpu = ARM64; else if (idx == CPUPLATFORM_IDX.arm32) cpu = ARM32; else if (idx == CPUPLATFORM_IDX.arm16) cpu = ARM16; else if (idx == CPUPLATFORM_IDX.mips64) cpu = MIPS64; else if (idx == CPUPLATFORM_IDX.mips32) cpu = MIPS32; else if (idx == CPUPLATFORM_IDX.mips16) cpu = MIPS16; auto &&in = ui.asmEdit->toPlainText().toStdString(); const char *pfx = "file:///"; auto pos = in.find(pfx); if (pos == 0) { auto file = UNONE::StrToW(in.substr(pos + strlen(pfx))); UNONE::FsReadFileDataW(file, in); in = UNONE::StrStreamToHexStrA(in); } else { UNONE::StrReplaceA(in, " "); UNONE::StrReplaceA(in, "\\x"); } if (in.size() >= 10 * KB) { auto msbox = QMessageBox::warning(this, tr("Warning"), tr("Your input data so much(suggest less 10 KB), it'll be very slowly, continue?"), QMessageBox::Yes | QMessageBox::No); if (msbox == QMessageBox::No) return; } auto &&out = Rasm2Disasm(in, cpu, byteorder); ui.disasmEdit->setText(out); }); } void CoderKit::UpdateAlgorithmText(bool crypt) { auto e_key = ui.keyEdit; std::string key = e_key->toPlainText().toStdString(); auto e_plain = ui.plainEdit; std::string plain = e_plain->toPlainText().toStdString(); auto e_cipher = ui.cipherEdit; std::string cipher; if (alg_idx_ == IDX.base64) { if (crypt) { cipher = Cryptor::Base64Encode(plain); } else { cipher = e_cipher->toPlainText().toStdString(); plain = Cryptor::Base64Decode(cipher); e_plain->blockSignals(true); e_plain->setText(StrToQ(plain)); e_plain->blockSignals(false); return; } } else if (alg_idx_ == IDX.crc32) { auto val = Cryptor::GetCRC32ByData(plain); cipher = UNONE::StrFormatA("%x", val); } else if (alg_idx_ == IDX.md5) { cipher = Cryptor::GetMD5ByData(plain); cipher = UNONE::StrStreamToHexStrA(cipher); } else if (alg_idx_ == IDX.sha1) { cipher = Cryptor::GetSHA1ByData(plain); cipher = UNONE::StrStreamToHexStrA(cipher); } else if (alg_idx_ == IDX.rc4) { cipher = Cryptor::GetSHA1ByData(plain); } else if (alg_idx_ == IDX.urlencode) { std::vector<char> pass; std::vector<std::string> headers = { "http", "https", "ftp" }; for (auto h : headers) { if (UNONE::StrIndexIA(plain, h) == 0) { pass = { ':', '&', '/', '?', '=' }; break; } } cipher = UrlEncode(plain, pass); } else if (alg_idx_ == IDX.urldecode) { cipher = UrlDecode(plain); } else if (alg_idx_ == IDX.urlencodeURL) { cipher = UrlEncodeURL(plain); } else if (alg_idx_ == IDX.urldecodeURL) { cipher = UrlDecode(plain); } if (!crypt) return; e_cipher->blockSignals(true); e_cipher->setText(StrToQ(cipher)); e_cipher->blockSignals(false); } void CoderKit::UpdateEditCodeText(const std::wstring& data, QObject* ignored_obj) { //prevent multi call simultaneously std::unique_lock<std::mutex> guard(upt_mutex_, std::try_to_lock); if (!guard.owns_lock()) return; auto SetText = [&](QObject* obj, std::string data) { if (obj == ignored_obj) return; const char* class_name = obj->metaObject()->className(); if (class_name == QStringLiteral("QTextEdit")) { qobject_cast<QTextEdit*>(obj)->setText(StrToQ(data)); } else if (class_name == QStringLiteral("QLineEdit")) { data = UNONE::StrTrimA(data); qobject_cast<QLineEdit*>(obj)->setText(StrToQ(data)); } }; is_user_ = false; int interval = 2; int id_interval = radio_group_interval_.checkedId(); if (id_interval == 0) interval = 2; else if (id_interval == 1) interval = 4; else if (id_interval == 2) interval = 8; std::string format = ""; int id_format = radio_group_type_.checkedId(); if (id_format == 0) format = ""; else if (id_format == 1) format = " "; else if (id_format == 2) format = "\\x"; else if (id_format == 3) format = "h, ", interval = 2; std::string text; text = UNONE::StrWideToUTF8(data); SetText(ui.textEdit, text); text = UNONE::StrStreamToHexStrA(UNONE::StrWideToACP(data)); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.defaultEdit, text); text = UNONE::StrStreamToHexStrA(UNONE::StrACPToCode(437, UNONE::StrToA(data))); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.asciiEdit, text); text = UNONE::StrStreamToHexStrA(std::string((char*)data.c_str(), data.size() * 2)); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.unicodeEdit, text); text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(CP_UTF7, data)); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.utf7Edit, text); text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(CP_UTF8, data)); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.utf8Edit, text); text = UNONE::StrStreamToHexStrA(std::string((char*)data.c_str(), data.size() * 2)); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.utf16Edit, text); auto stream = std::string((char*)data.c_str(), data.size() * 2); stream = UNONE::StrReverseA(stream, 2); text = UNONE::StrStreamToHexStrA(stream); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.butf16Edit, text); U32Convert cvt32; auto utf32 = cvt32.from_bytes(UNONE::StrWideToCode(CP_UTF8, data)); stream = std::string((char*)utf32.c_str(), utf32.size() * 4); text = UNONE::StrStreamToHexStrA(stream); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.utf32Edit, text); stream = UNONE::StrReverseA(stream, 4); text = UNONE::StrStreamToHexStrA(stream); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.butf32Edit, text); text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(936, data)); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.gbkEdit, text); text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(950, data)); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.big5Edit, text); text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(866, data)); SolveCodeTextFormat(text, format, interval, id_format); SetText(ui.cp866Edit, text); } QString CoderKit::Rasm2Asm(std::string data, int cpu, int byteorder, const std::string &format) { auto &&rasm2 = AppConfigDir() + L"\\nasm\\rasm2.exe"; if (!UNONE::FsIsExistedW(rasm2)) { ExtractResource(":/OpenArk/nasm/rasm2.exe", WStrToQ(rasm2)); } auto &&tmp_out = UNONE::OsEnvironmentW(L"%Temp%\\temp-nasm-code.bin"); auto &&tmp_in = UNONE::OsEnvironmentW(L"%Temp%\\temp-nasm-code.asm"); UNONE::FsWriteFileDataW(tmp_in, data); int bits; std::wstring plat; switch (cpu) { case X64: plat = L"x86"; bits = 64; break; case X86: plat = L"x86"; bits = 32; break; case X86_16: plat = L"x86"; bits = 16; break; case ARM64: plat = L"arm"; bits = 64; break; case ARM32: plat = L"arm"; bits = 32; break; case ARM16: plat = L"arm"; bits = 16; break; case MIPS64: plat = L"mips"; bits = 64; break; case MIPS32: plat = L"mips"; bits = 32; break; case MIPS16: plat = L"mips"; bits = 16; break; } auto &&cmdline = rasm2; if (byteorder == BIG_ENDIAN) cmdline += L" -e"; cmdline = UNONE::StrFormatW(L"%s -a %s -b%d -O \"%s\" -f \"%s\"", rasm2.c_str(), plat.c_str(), bits, tmp_out.c_str(), tmp_in.c_str()); std::wstring out; DWORD exitcode; QString err_prefix = tr("Compile Error:\n--------------------------------------------------------------\n"); auto ret = ReadStdout(cmdline, out, exitcode); if (!ret) return err_prefix + tr("run compiler error"); if (exitcode != 0) return err_prefix + WStrToQ(out); std::string bin; UNONE::FsReadFileDataW(tmp_out, bin); bin = UNONE::StrTrimA(bin); bin = format + UNONE::StrInsertA(bin, 2, format); return StrToQ(bin); } QString CoderKit::Rasm2Disasm(std::string data, int cpu, int byteorder) { auto &&rasm2 = AppConfigDir() + L"\\nasm\\rasm2.exe"; if (!UNONE::FsIsExistedW(rasm2)) { ExtractResource(":/OpenArk/nasm/rasm2.exe", WStrToQ(rasm2)); } auto &&tmp_in = UNONE::OsEnvironmentW(L"%Temp%\\temp-ndisasm-code.bin"); UNONE::FsWriteFileDataW(tmp_in, data); int bits; std::wstring plat; switch (cpu) { case X64: plat = L"x86"; bits = 64; break; case X86: plat = L"x86"; bits = 32; break; case X86_16: plat = L"x86"; bits = 16; break; case ARM64: plat = L"arm"; bits = 64; break; case ARM32: plat = L"arm"; bits = 32; break; case ARM16: plat = L"arm"; bits = 16; break; case MIPS64: plat = L"mips"; bits = 64; break; case MIPS32: plat = L"mips"; bits = 32; break; case MIPS16: plat = L"mips"; bits = 16; break; } auto &&cmdline = rasm2; if (byteorder == BIG_ENDIAN) cmdline += L" -e"; cmdline = UNONE::StrFormatW(L"%s -a %s -b%d -D -f \"%s\"", cmdline.c_str(), plat.c_str(), bits, tmp_in.c_str()); std::wstring out; DWORD exitcode; auto ret = ReadStdout(cmdline, out, exitcode); if (!ret) return tr("run disassember error"); UNONE::StrLowerW(out); //UNONE::StrReplaceW(out, L" ", L" "); return WStrToQ(out); } QString CoderKit::NasmAsm(std::string data, int bits, const std::string &format) { if (bits == 64) data.insert(0, "[bits 64]\n"); else if (bits == 32) data.insert(0, "[bits 32]\n"); else if (bits == 16) data.insert(0, "[bits 16]\n"); auto &&nasm = AppConfigDir() + L"\\nasm\\nasm.exe"; if (!UNONE::FsIsExistedW(nasm)) { ExtractResource(":/OpenArk/nasm/nasm.exe", WStrToQ(nasm)); } auto &&tmp_out = UNONE::OsEnvironmentW(L"%Temp%\\temp-nasm-code.bin"); auto &&tmp_in = UNONE::OsEnvironmentW(L"%Temp%\\temp-nasm-code.asm"); UNONE::FsWriteFileDataW(tmp_in, data); auto &&cmdline = UNONE::StrFormatW(L"%s -f bin -o \"%s\" \"%s\"", nasm.c_str(), tmp_out.c_str(), tmp_in.c_str()); std::wstring out; DWORD exitcode; QString err_prefix = tr("Compile Error:\n--------------------------------------------------------------\n"); auto ret = ReadStdout(cmdline, out, exitcode); if (!ret) return err_prefix + tr("start nasm error"); if (exitcode != 0) return err_prefix + WStrToQ(out); std::string bin; UNONE::FsReadFileDataW(tmp_out, bin); bin = UNONE::StrStreamToHexStrA(bin); bin = format + UNONE::StrInsertA(bin, 2, format); return StrToQ(bin); } QString CoderKit::NasmDisasm(const std::string &data, int bits) { auto &&ndisasm = AppConfigDir() + L"\\nasm\\ndisasm.exe"; if (!UNONE::FsIsExistedW(ndisasm)) { ExtractResource(":/OpenArk/nasm/ndisasm.exe", WStrToQ(ndisasm)); } auto &&tmp_in = UNONE::OsEnvironmentW(L"%Temp%\\temp-ndisasm-code.bin"); UNONE::FsWriteFileDataW(tmp_in, data); auto &&cmdline = UNONE::StrFormatW(L"%s -b %d \"%s\"", ndisasm.c_str(), bits, tmp_in.c_str()); std::wstring out; DWORD exitcode; auto ret = ReadStdout(cmdline, out, exitcode); if (!ret) return tr("start ndisasm error"); UNONE::StrLowerW(out); return WStrToQ(out); } void CoderKit::SolveCodeTextFormat(std::string &text, std::string &format, int interval, int id) { if (id == 3) { // assemble text = UNONE::StrInsertA(text, interval, format); text = text + "h"; } else { text = format + UNONE::StrInsertA(text, interval, format); } } #ifndef HEX_TO_UPPER_CHAR #define HEX_TO_UPPER_CHAR(x) ((unsigned char)(x) > 9 ? (unsigned char)(x) -10 + 'A': (unsigned char)(x) + '0') #endif //'1' => 1 / 'A' => A #ifndef UPPER_CHAR_TO_HEX #define UPPER_CHAR_TO_HEX(x) (isdigit((unsigned char)(x)) ? (unsigned char)(x)-'0' : (unsigned char)(toupper(x))-'A'+10) #endif static const char* kUrlReservedCharset = "!*'();:@&=+$,/?#[]"; static const char* kUrlNonReservedCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"; std::string CoderKit::UrlEncode(const std::string &buf, std::vector<char> pass) { std::string str; try { std::string CharSet = kUrlNonReservedCharset; for (size_t i = 0; i < buf.size(); i++) { unsigned char temp[4] = {0}; unsigned char ch = static_cast<unsigned char>(buf[i]); bool found = false; for (auto p : pass) { if (p == ch) { found = true; break; } } if (found || CharSet.find(ch) != std::string::npos) { temp[0] = ch; } else { temp[0] = '%'; temp[1] = HEX_TO_UPPER_CHAR(ch >> 4); temp[2] = HEX_TO_UPPER_CHAR(ch & 0x0F); } str += (char*)temp; } } catch (std::exception& e) { str.clear(); } catch (...) { str.clear(); } return std::move(str); } std::string CoderKit::UrlDecode(const std::string &buf) { std::string str; try { std::string bits; bits.assign(buf.size(), 0); for (size_t i = 0; i < buf.size(); i++) { if (buf[i]=='%') { bits[i] = 1; bits[i+1] = 1; bits[i+2] = 1; i += 2; } } auto& decode = [](std::string& s)->std::string { std::string out; for (size_t i = 0; i < s.size(); i+=3) { unsigned char ch = 0; if (s[i] != '%') continue; ch = UPPER_CHAR_TO_HEX(s[i+1]) << 4; ch |= (UPPER_CHAR_TO_HEX(s[i+2]) & 0x0F); out.push_back(ch); } //out = StrUTF8ToGBK(out); return out; }; size_t last = 0; size_t i = 0; for (i=0; i<bits.size(); i++) { if (bits[i] == 0) { if (last < i) { str += decode(buf.substr(last, i-last)); } str += buf[i]; last = i + 1; } } //处理边界情况 if (bits.size() && bits.back() == 1) { if (last < i) { str += decode(buf.substr(last, i-last)); } } } catch (std::exception& e) { str.clear(); } catch (...) { str.clear(); } return std::move(str); } bool IsValidUrlChar(char ch, bool unsafe_only) { if (static_cast<unsigned>(ch) < 0 || static_cast<unsigned>(ch) > 127) { return false; } if (unsafe_only) { return !(ch <= ' ' || strchr("\\\"^&`<>[]{}", ch)); } else { return isalnum(ch) || strchr("-_.!~*'()", ch); } } static const char* kSpecialCharset = "/:?"; static const char* kNewUrlNonReservedCharset = "!*()ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"; std::string CoderKit::UrlEncodeURL(const std::string &buf) { std::string source = buf; std::string str; try { // for (size_t i = 0; i < buf.size(); i++) { // unsigned char temp[4] = {0}; // unsigned char ch = static_cast<unsigned char>(buf[i]); // if (char_set.find(ch) != std::string::npos) { // temp[0] = ch; // } // else { // if (!has_question_mark && (special_charset.find(ch) != std::string::npos)) { // temp[0] = ch; // has_question_mark = (ch == '?'); // } else if (!has_equal_mark && ch == '=') { // temp[0] = ch; // has_equal_mark = true; // } else { // temp[0] = '%'; // temp[1] = HEX_TO_UPPER_CHAR(ch >> 4); // temp[2] = HEX_TO_UPPER_CHAR(ch & 0x0F); // } // } // str += (char*)temp; // } } catch (std::exception& e) { str.clear(); } catch (...) { str.clear(); } return std::move(str); // size_t size = buf.size() + 5; // std::unique_ptr<char[]> source_ptr(new char[size]); // std::unique_ptr<char[]> dest_ptr(new char[size<<2]); // strcpy(source_ptr.get(), buf.c_str()); // char *source = source_ptr.get(); // char *dest = dest_ptr.get(); // bool encode_space_as_plus = true; // bool unsafe_only = false; // static const char *digits = "0123456789ABCDEF"; // //if (max == 0) { // // return 0; // //} // char *start = dest; // while (*source) { // unsigned char ch = static_cast<unsigned char>(*source); // if (*source == ' ' && encode_space_as_plus && !unsafe_only) { // *dest++ = '+'; // } else if (IsValidUrlChar(ch, unsafe_only)) { // *dest++ = *source; // } else { // /*if (static_cast<unsigned>(dest - start) + 4 > max) { // break; // }*/ // *dest++ = '%'; // *dest++ = digits[(ch >> 4) & 0x0F]; // *dest++ = digits[ ch & 0x0F]; // } // source++; // } // // ASSERT(static_cast<unsigned int>(dest - start) < max); // *dest = 0; // return std::move(dest_ptr.get()); }
29,241
C++
.cpp
782
34.831202
120
0.665891
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,159
scanner.cpp
BlackINT3_OpenArk/src/OpenArk/scanner/scanner.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "scanner.h" #include "../common/common.h" #include "../openark/openark.h" #define PE_UNKNOWN_FILE L"Unknown file" #define PE_FILE32 L"PE 32-bit" #define PE_FILE64 L"PE 64-bit" Scanner::Scanner(QWidget *parent, int tabid) : CommonMainTabObject::CommonMainTabObject((OpenArk*)parent), pe_image_(NULL) { ui.setupUi(this); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); setAcceptDrops(true); sumup_model_ = new QStandardItemModel; SetDefaultTableViewStyle(ui.summaryUpView, sumup_model_); sumup_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Value")); ui.summaryUpView->setColumnWidth(0, 120); sumdown_model_ = new QStandardItemModel; SetDefaultTableViewStyle(ui.summaryDownView, sumdown_model_); ui.summaryDownView->horizontalHeader()->hide(); ui.summaryDownView->setColumnWidth(0, 120); ui.splitterSummary->setStretchFactor(0, 2); ui.splitterSummary->setStretchFactor(1, 1); headers_model_ = new QStandardItemModel; headers_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Value")); SetDefaultTreeViewStyle(ui.headersView, headers_model_); ui.headersView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); ui.headersView->viewport()->installEventFilter(this); ui.headersView->installEventFilter(this); headers_menu_ = new QMenu(); headers_menu_->addAction(tr("ExpandAll"), this, SLOT(onExpandAll())); sections_model_ = new QStandardItemModel; SetDefaultTableViewStyle(ui.sectionsView, sections_model_); sections_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("VirtualSize") << tr("VirtualAddress") << tr("SizeOfRawData") << tr("PointerToRawData") << tr("PointerToRelocations") << tr("PointerToLinenumbers") << tr("NumberOfRelocations") << tr("NumberOfLinenumbers") << tr("Characteristics")); imp_model_ = new QStandardItemModel; imp_func_model_ = new QStandardItemModel; SetDefaultTableViewStyle(ui.impView, imp_model_); SetDefaultTableViewStyle(ui.impFuncView, imp_func_model_); imp_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("OriginalFirstThunk") << tr("TimeDateStamp") << tr("ForwarderChain") << tr("FirstThunk")); imp_func_model_->setHorizontalHeaderLabels(QStringList() << tr("ForwarderString") << tr("Function") << tr("Ordinal") << tr("AddressOfData") << tr("Hint") << tr("Name")); connect(ui.impView->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &Scanner::onImportChanged); exp_model_ = new QStandardItemModel; exp_func_model_ = new QStandardItemModel; SetDefaultTableViewStyle(ui.expView, exp_model_); SetDefaultTableViewStyle(ui.expFuncView, exp_func_model_); exp_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Value")); exp_func_model_->setHorizontalHeaderLabels(QStringList() << tr("FunctionAddr") << tr("Ordinal") << tr("Name")); reloc_model_ = new QStandardItemModel; reloc_item_model_ = new QStandardItemModel; SetDefaultTableViewStyle(ui.relocView, reloc_model_); SetDefaultTableViewStyle(ui.relocItemView, reloc_item_model_); reloc_model_->setHorizontalHeaderLabels(QStringList() << tr("VirtualAddress") << tr("SizeOfBlock") << tr("ItemCount")); reloc_item_model_->setHorizontalHeaderLabels(QStringList() << tr("Item") << tr("Address") << tr("Type")); connect(ui.relocView->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &Scanner::onRelocChanged); dbg_model_ = new QStandardItemModel; SetDefaultTableViewStyle(ui.debugView, dbg_model_); dbg_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Value")); connect(ui.baseEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.rebaseEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.vaEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.revaEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.rvaEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.rawEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); CommonMainTabObject::Init(ui.tabWidget, tabid); } Scanner::~Scanner() { } bool Scanner::eventFilter(QObject *obj, QEvent *e) { if (obj == ui.headersView->viewport()) { if (e->type() == QEvent::ContextMenu) { QContextMenuEvent* ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt != nullptr) { headers_menu_->move(ctxevt->globalPos()); headers_menu_->show(); } } } return QWidget::eventFilter(obj, e); } void Scanner::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } void Scanner::dragMoveEvent(QDragMoveEvent *event) { } void Scanner::dropEvent(QDropEvent *event) { if (!event->mimeData()->hasUrls()) return; QString& path = event->mimeData()->urls()[0].toLocalFile(); onOpenFile(path); } void Scanner::onImportChanged(const QModelIndex &current, const QModelIndex &previous) { ClearItemModelData(imp_func_model_); std::string dll = GetCurItemViewData(ui.impView, 0).toStdString(); PIMAGE_IMPORT_DESCRIPTOR imp = (PIMAGE_IMPORT_DESCRIPTOR)UNONE::PeGetDataEntity(IMAGE_DIRECTORY_ENTRY_IMPORT, pe_image_); if (!imp) return; while (imp->Name != 0) { if ((pe_image_ + imp->Name) != dll) { imp++; continue; } if (UNONE::PeX64(pe_image_)) { PIMAGE_THUNK_DATA64 othunk = NULL; PIMAGE_THUNK_DATA64 fthunk = (PIMAGE_THUNK_DATA64)(pe_image_ + imp->FirstThunk); if (imp->OriginalFirstThunk != 0) othunk = (PIMAGE_THUNK_DATA64)(pe_image_ + imp->OriginalFirstThunk); else othunk = fthunk; while (othunk != NULL && othunk->u1.Ordinal != 0) { WORD hint = 0; std::string func_name; if (IMAGE_SNAP_BY_ORDINAL64(othunk->u1.Ordinal)) { func_name = UNONE::StrFormatA("Ordinal: %08X", othunk->u1.Ordinal & (~IMAGE_ORDINAL_FLAG64)); } else { PIMAGE_IMPORT_BY_NAME imp_name = (PIMAGE_IMPORT_BY_NAME)(pe_image_ + othunk->u1.AddressOfData); func_name = (LPCSTR)(imp_name->Name); hint = imp_name->Hint; } InitTableItem(imp_func_model_); AppendTableItem(imp_func_model_, QWordToHexQ(othunk->u1.Ordinal)); AppendTableItem(imp_func_model_, QWordToHexQ(othunk->u1.Ordinal)); AppendTableItem(imp_func_model_, QWordToHexQ(othunk->u1.Ordinal)); AppendTableItem(imp_func_model_, QWordToHexQ(othunk->u1.Ordinal)); AppendTableItem(imp_func_model_, DWordToHexQ(hint)); AppendTableItem(imp_func_model_, StrToQ(func_name)); fthunk++; othunk++; } } else { PIMAGE_THUNK_DATA32 othunk = NULL; PIMAGE_THUNK_DATA32 fthunk = (PIMAGE_THUNK_DATA32)(pe_image_ + imp->FirstThunk); if (imp->OriginalFirstThunk != 0) othunk = (PIMAGE_THUNK_DATA32)(pe_image_ + imp->OriginalFirstThunk); else othunk = fthunk; while (othunk != NULL && othunk->u1.Ordinal != 0) { WORD hint = 0; std::string func_name; if (IMAGE_SNAP_BY_ORDINAL32(othunk->u1.Ordinal)) { func_name = UNONE::StrFormatA("Ordinal: %08X", othunk->u1.Ordinal & (~IMAGE_ORDINAL_FLAG32)); } else { PIMAGE_IMPORT_BY_NAME imp_name = (PIMAGE_IMPORT_BY_NAME)(pe_image_ + othunk->u1.AddressOfData); func_name = (LPCSTR)(imp_name->Name); hint = imp_name->Hint; } InitTableItem(imp_func_model_); AppendTableItem(imp_func_model_, DWordToHexQ(othunk->u1.Ordinal)); AppendTableItem(imp_func_model_, DWordToHexQ(othunk->u1.Ordinal)); AppendTableItem(imp_func_model_, DWordToHexQ(othunk->u1.Ordinal)); AppendTableItem(imp_func_model_, DWordToHexQ(othunk->u1.Ordinal)); AppendTableItem(imp_func_model_, WordToHexQ(hint)); AppendTableItem(imp_func_model_, StrToQ(func_name)); fthunk++; othunk++; } } imp++; } } void Scanner::onRelocChanged(const QModelIndex &current, const QModelIndex &previous) { ClearItemModelData(reloc_item_model_); int row = GetCurViewRow(ui.relocView); PIMAGE_BASE_RELOCATION reloc = (PIMAGE_BASE_RELOCATION)UNONE::PeGetDataEntity(IMAGE_DIRECTORY_ENTRY_BASERELOC, pe_image_); if (!reloc) return; PIMAGE_DATA_DIRECTORY dir = UNONE::PeGetDataDirectory(IMAGE_DIRECTORY_ENTRY_BASERELOC, pe_image_); DWORD reloc_size = dir->Size; DWORD reloc_rva = dir->VirtualAddress; DWORD item_size = 0; int idx = 0; while (item_size < reloc_size) { DWORD itemcnt = (reloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT); PUSHORT items = (PUSHORT)(reloc + 1); if (idx++ == row) { for (int i = 0; i < itemcnt; i++) { USHORT offset = items[i] & 0xFFF; DWORD rva = reloc->VirtualAddress + offset; CHAR *type = NULL; switch (items[i] >> 12) { case IMAGE_REL_BASED_ABSOLUTE: type = "IMAGE_REL_BASED_ABSOLUTE"; break; case IMAGE_REL_BASED_HIGHLOW: type = "IMAGE_REL_BASED_HIGHLOW"; break; case IMAGE_REL_BASED_HIGH: type = "IMAGE_REL_BASED_HIGH"; break; case IMAGE_REL_BASED_LOW: type = "IMAGE_REL_BASED_LOW"; break; case IMAGE_REL_BASED_HIGHADJ: type = "IMAGE_REL_BASED_HIGHADJ"; break; case IMAGE_REL_BASED_DIR64: type = "IMAGE_REL_BASED_DIR64"; break; default: type = "IMAGE_REL_BASED_UNKNOWN"; break; } InitTableItem(reloc_item_model_); AppendTableItem(reloc_item_model_, DWordToHexQ(items[i])); AppendTableItem(reloc_item_model_, DWordToHexQ(rva)); AppendTableItem(reloc_item_model_, CharsToQ(type)); } break; } item_size += reloc->SizeOfBlock; reloc = (PIMAGE_BASE_RELOCATION)(pe_image_ + reloc_rva + item_size); } } void Scanner::onExpandAll() { ExpandTreeView(ui.headersView->currentIndex(), ui.headersView); } void Scanner::onTextChanged(const QString& text) { QLineEdit* sender = qobject_cast<QLineEdit*>(QObject::sender()); auto SetEditValue = [&](QLineEdit* edit, int64_t val){ if (sender != edit) edit->setText(StrToQ(UNONE::StrFormatA("%llX", val))); }; auto GetEditValue = [](QLineEdit* edit) { return UNONE::StrToHex64A(edit->text().toStdString()); }; try { std::string str = sender->text().toStdString(); auto InputFilter = [&](std::string& input) { UNONE::StrReplaceA(input, "-"); UNONE::StrReplaceA(input, " "); UNONE::StrReplaceA(input, "0x"); UNONE::StrReplaceA(input, "h"); UNONE::StrReplaceA(input, "\\x"); UNONE::StrReplaceA(input, "`"); input = UNONE::StrTrimLeftA(input, "0"); UNONE::StrUpperA(input); sender->setText(StrToQ(input)); }; InputFilter(str); std::unique_lock<std::mutex> guard(upt_mutex_, std::try_to_lock); if (!guard.owns_lock()) return; int64_t hex = UNONE::StrToHex64A(str); int64_t base, va, reva, rva, raw; if (sender == ui.baseEdit) { va = hex + GetEditValue(ui.revaEdit) - GetEditValue(ui.rebaseEdit); SetEditValue(ui.vaEdit, va); } else if (sender == ui.vaEdit) { __va: reva = hex - GetEditValue(ui.baseEdit) + GetEditValue(ui.rebaseEdit); SetEditValue(ui.revaEdit, reva); rva = hex - GetEditValue(ui.baseEdit); SetEditValue(ui.rvaEdit, rva); hex = rva; goto __rva; } else if (sender == ui.rebaseEdit) { reva = GetEditValue(ui.vaEdit) - GetEditValue(ui.baseEdit) + hex; SetEditValue(ui.revaEdit, reva); hex = reva; goto __reva; } else if (sender == ui.revaEdit) { __reva: va = hex - GetEditValue(ui.rebaseEdit) + GetEditValue(ui.baseEdit); SetEditValue(ui.vaEdit, va); hex = va; goto __va; } else if (sender == ui.rvaEdit) { __rva: va = hex + GetEditValue(ui.baseEdit); SetEditValue(ui.vaEdit, va); reva = va - GetEditValue(ui.baseEdit) + GetEditValue(ui.rebaseEdit); SetEditValue(ui.revaEdit, reva); if (pe_image_) { raw = UNONE::PeRvaToRaw(pe_image_, hex); SetEditValue(ui.rawEdit, raw); } hex = raw; goto __raw; } else if (sender == ui.rawEdit) { __raw: if (pe_image_) { rva = UNONE::PeRawToRva(pe_image_, hex); if (rva != 0) { SetEditValue(ui.rvaEdit, rva); hex = rva + GetEditValue(ui.baseEdit); /* if (va != hex) goto __va;*/ } } } } catch (...) { } } void Scanner::onTabChanged(int index) { CommonMainTabObject::onTabChanged(index); } void Scanner::onOpenFile(const QString& file) { if (file.isEmpty()) { ERR(tr("file path is empty").toStdWString().c_str()); return; } bool pe_valid = false; std::wstring path = file.toStdWString(); pe_file_ = file; if (pe_image_) UnmapPe(); if (MapPe(path)) pe_valid = true; RefreshSummary(path); if (!pe_valid) return; RefreshHeaders(); RefreshSections(); RefreshImport(); RefreshExport(); RefreshResource(); RefreshRelocation(); RefreshDebug(); RefreshRva(); } void Scanner::onRefresh() { onOpenFile(pe_file_); } std::wstring Scanner::GuessFileType() { if (!pe_image_) return PE_UNKNOWN_FILE; std::wstring filetype; if (UNONE::PeX64(pe_image_)) { filetype.append(PE_FILE64); } else { filetype.append(PE_FILE32); } return filetype.empty() ? PE_UNKNOWN_FILE : filetype; } bool Scanner::CheckIsPe() { return pe_valid_; } bool Scanner::MapPe(const std::wstring& path) { pe_valid_ = false; pe_image_ = UNONE::PeMapImageByPathW(path); if (!pe_image_) return false; pe_valid_ = UNONE::PeValid(pe_image_) == TRUE; pe_x64_ = UNONE::PeX64(pe_image_) == TRUE; return true; } bool Scanner::UnmapPe() { bool ret = UNONE::PeUnmapImage(pe_image_); pe_image_ = NULL; ClearItemModelData(sumup_model_); ClearItemModelData(sumdown_model_); ClearItemModelData(headers_model_); ClearItemModelData(sections_model_); ClearItemModelData(imp_model_); ClearItemModelData(imp_func_model_); ClearItemModelData(exp_model_); ClearItemModelData(exp_func_model_); ClearItemModelData(reloc_model_); ClearItemModelData(reloc_item_model_); ClearItemModelData(dbg_model_); return ret; } void Scanner::RefreshSummary(const std::wstring& path) { int up_seq = 0, down_seq = 0; double kbytes, mbytes; DWORD64 size; UNONE::FsGetFileSizeW(path, (DWORD64&)size); kbytes = size / 1024; mbytes = kbytes / 1024; std::wstring formed = UNONE::StrFormatW(L"%.2f MB | %.2f KB | %d B", mbytes, kbytes, size); auto AddSummaryUpItem = [&](QString name, QString value) { sumup_model_->setItem(up_seq, 0, new QStandardItem(name)); sumup_model_->setItem(up_seq, 1, new QStandardItem(value)); up_seq++; }; auto AddSummaryDownItem = [&](QString name, QString value) { sumdown_model_->setItem(down_seq, 0, new QStandardItem(name)); sumdown_model_->setItem(down_seq, 1, new QStandardItem(value)); down_seq++; }; auto std_path = WStrToQ(UNONE::FsPathStandardW(path)); sumup_model_->setItem(up_seq, 0, new QStandardItem(tr("File Path"))); sumup_model_->setItem(up_seq, 1, new QStandardItem(LoadIcon(std_path), std_path)); up_seq++; AddSummaryUpItem(tr("File Type"), WStrToQ(GuessFileType())); AddSummaryUpItem(tr("File Size"), WStrToQ(formed)); LONGLONG create_tm, access_tm, modify_tm; UNONE::FsGetFileTimeW(path, &create_tm, &access_tm, &modify_tm); AddSummaryUpItem(tr("Created Time"), MsToTime(create_tm)); AddSummaryUpItem(tr("Modified Time"), MsToTime(access_tm)); AddSummaryUpItem(tr("Accessed Time"), MsToTime(modify_tm)); auto &&temp = UNONE::StrToA(path); auto crc32 = Cryptor::GetCRC32ByFile(temp); auto md5 = UNONE::StrStreamToHexStrA(Cryptor::GetMD5ByFile(temp)); auto sha1 = UNONE::StrStreamToHexStrA(Cryptor::GetSHA1ByFile(temp)); AddSummaryUpItem(tr("CRC32"), StrToQ(UNONE::StrFormatA("%08x", crc32))); AddSummaryUpItem(tr("MD5"), StrToQ(md5)); AddSummaryUpItem(tr("SHA1"), StrToQ(sha1)); if (!CheckIsPe()) return; std::wstring file_ver, prod_ver, prod_name, cright, origin, inner, corp, desc; UNONE::FsGetFileInfoW(path, L"FileVersion", file_ver); UNONE::FsGetFileInfoW(path, L"ProductVersion", prod_ver); UNONE::FsGetFileInfoW(path, L"ProductName", prod_name); UNONE::FsGetFileInfoW(path, L"LegalCopyright", cright); UNONE::FsGetFileInfoW(path, L"OriginalFileName", origin); UNONE::FsGetFileInfoW(path, L"InternalName", inner); UNONE::FsGetFileInfoW(path, L"CompanyName", corp); UNONE::FsGetFileInfoW(path, L"FileDescription", desc); AddSummaryUpItem(tr("File Version"), WStrToQ(file_ver)); AddSummaryUpItem(tr("ProductVersion"), WStrToQ(prod_ver)); AddSummaryUpItem(tr("ProductName"), WStrToQ(prod_name)); AddSummaryUpItem(tr("LegalCopyright"), WStrToQ(cright)); AddSummaryUpItem(tr("OriginalFileName"), WStrToQ(origin)); AddSummaryUpItem(tr("InternalName"), WStrToQ(inner)); AddSummaryUpItem(tr("CompanyName"), WStrToQ(corp)); AddSummaryUpItem(tr("FileDescription"), WStrToQ(desc)); std::wstring pdb, cptime, cpver; pdb = UNONE::StrToW(UNONE::PeGetPdb(pe_image_)); cptime = UNONE::TmFormatUnixTimeW((time_t)PE_NT_HEADER(pe_image_)->FileHeader.TimeDateStamp, L"Y-M-D H:W:S"); DWORD link_major, link_minor; if (UNONE::PeX64(pe_image_)) { AddSummaryDownItem(tr("ImageBase"), QWordToHexQ(PE_OPT_HEADER64(pe_image_)->ImageBase)); AddSummaryDownItem(tr("ImageSize"), DWordToHexQ(PE_OPT_HEADER64(pe_image_)->SizeOfImage)); AddSummaryDownItem(tr("OEP"), DWordToHexQ(PE_OPT_HEADER64(pe_image_)->AddressOfEntryPoint)); link_major = PE_OPT_HEADER64(pe_image_)->MajorLinkerVersion; link_minor = PE_OPT_HEADER64(pe_image_)->MinorLinkerVersion; } else { AddSummaryDownItem(tr("ImageBase"), DWordToHexQ(PE_OPT_HEADER32(pe_image_)->ImageBase)); AddSummaryDownItem(tr("ImageSize"), DWordToHexQ(PE_OPT_HEADER32(pe_image_)->SizeOfImage)); AddSummaryDownItem(tr("OEP"), DWordToHexQ(PE_OPT_HEADER32(pe_image_)->AddressOfEntryPoint)); link_major = PE_OPT_HEADER32(pe_image_)->MajorLinkerVersion; link_minor = PE_OPT_HEADER32(pe_image_)->MinorLinkerVersion; } struct { int major; int minor; wchar_t* info; } linkers[] = { { 5, -1, L"vc50 (5.0)" }, { 6, -1, L"vc60 (6.0)" }, { 7, -1, L"vc70 (2003)" }, { 8, -1, L"vc80 (2005)" }, { 9, -1, L"vc90 (2008)" }, { 10, -1, L"vc100 (2010)" }, { 11, -1, L"vc110 (2012)" }, { 12, -1, L"vc120 (2013)" }, { 14, 0, L"vc140 (2015)" }, { 14, 0x10, L"vc141 (2017)" }, { 14, 0x10, L"vc142 (2019)" }, }; cpver = UNONE::StrFormatW(L"vc%d%d (unknown)", link_major, link_minor); for (int i = 0; i < _countof(linkers); i++) { if (linkers[i].major == link_major && (linkers[i].minor == link_minor || linkers[i].minor == -1)) { cpver = linkers[i].info; break; } } AddSummaryDownItem(tr("Linker"), WStrToQ(cpver)); AddSummaryDownItem(tr("CompileTime"), WStrToQ(cptime)); AddSummaryDownItem(tr("PDB File"), WStrToQ(pdb)); std::vector<UNONE::CertInfoW> infos; std::wstring sign, sn; bool ret = UNONE::SeGetCertInfoW(path, infos); if (!ret) { DWORD err = GetLastError(); UNONE::StrFormatW(sign, L"%X %s", err, UNONE::OsDosErrorMsgW(err).c_str()); } else { sign = infos[0].owner; sn = infos[0].sn; } AddSummaryDownItem(tr("Cert Owner"), WStrToQ(sign)); AddSummaryDownItem(tr("Cert SN"), WStrToQ(sn)); } void Scanner::RefreshHeaders() { int row = 0; QStandardItem *item, *value; auto dos_item = new QStandardItem("IMAGE_DOS_HEADER"); headers_model_->appendRow(dos_item); PIMAGE_DOS_HEADER dos_hdr = PE_DOS_HEADER(pe_image_); AppendTreeItem(dos_item, "e_magic", WordToHexQ(dos_hdr->e_magic)); AppendTreeItem(dos_item, "e_cblp", WordToHexQ(dos_hdr->e_cblp)); AppendTreeItem(dos_item, "e_cp", WordToHexQ(dos_hdr->e_cp)); AppendTreeItem(dos_item, "e_crlc", WordToHexQ(dos_hdr->e_crlc)); AppendTreeItem(dos_item, "e_cparhdr", WordToHexQ(dos_hdr->e_cparhdr)); AppendTreeItem(dos_item, "e_minalloc", WordToHexQ(dos_hdr->e_minalloc)); AppendTreeItem(dos_item, "e_maxalloc", WordToHexQ(dos_hdr->e_maxalloc)); AppendTreeItem(dos_item, "e_ss", WordToHexQ(dos_hdr->e_ss)); AppendTreeItem(dos_item, "e_sp", WordToHexQ(dos_hdr->e_sp)); AppendTreeItem(dos_item, "e_csum", WordToHexQ(dos_hdr->e_csum)); AppendTreeItem(dos_item, "e_ip", WordToHexQ(dos_hdr->e_ip)); AppendTreeItem(dos_item, "e_cs", WordToHexQ(dos_hdr->e_cs)); AppendTreeItem(dos_item, "e_lfarlc", WordToHexQ(dos_hdr->e_lfarlc)); AppendTreeItem(dos_item, "e_ovno", WordToHexQ(dos_hdr->e_ovno)); AppendTreeItem(dos_item, "e_res", WordArrayToHexQ(dos_hdr->e_res, 4)); AppendTreeItem(dos_item, "e_oemid", WordToHexQ(dos_hdr->e_oemid)); AppendTreeItem(dos_item, "e_oeminfo", WordToHexQ(dos_hdr->e_oeminfo)); AppendTreeItem(dos_item, "e_res2", WordArrayToHexQ(dos_hdr->e_res2, 10)); AppendTreeItem(dos_item, "e_lfanew", DWordToHexQ(dos_hdr->e_lfanew)); row = 0; auto nt_item = new QStandardItem(pe_x64_ ? "IMAGE_NT_HEADERS64":"IMAGE_FILE_HEADER32"); headers_model_->appendRow(nt_item); PIMAGE_NT_HEADERS nt_hdr = PE_NT_HEADER(pe_image_); AppendTreeItem(nt_item, "Signature", DWordToHexQ(nt_hdr->Signature)); PIMAGE_FILE_HEADER file_hdr = &nt_hdr->FileHeader; auto file_item = new QStandardItem("FileHeader"); nt_item->appendRow(file_item); nt_item->setChild(row++, 1, new QStandardItem("IMAGE_FILE_HEADER")); row = 0; AppendTreeItem(file_item, "Machine", WordToHexQ(file_hdr->Machine)); AppendTreeItem(file_item, "NumberOfSections", WordToHexQ(file_hdr->NumberOfSections)); AppendTreeItem(file_item, "TimeDateStamp", DWordToHexQ(file_hdr->TimeDateStamp)); AppendTreeItem(file_item, "PointerToSymbolTable", DWordToHexQ(file_hdr->PointerToSymbolTable)); AppendTreeItem(file_item, "NumberOfSymbols", DWordToHexQ(file_hdr->NumberOfSymbols)); AppendTreeItem(file_item, "SizeOfOptionalHeader", WordToHexQ(file_hdr->SizeOfOptionalHeader)); AppendTreeItem(file_item, "Characteristics", WordToHexQ(file_hdr->Characteristics)); PIMAGE_OPTIONAL_HEADER32 opt_hdr32; PIMAGE_OPTIONAL_HEADER64 opt_hdr64; char* opt_title; if (pe_x64_) { opt_title = "IMAGE_FILE_HEADER64"; opt_hdr64 = PE_OPT_HEADER64(pe_image_); } else { opt_title = "IMAGE_FILE_HEADER32"; opt_hdr32 = PE_OPT_HEADER32(pe_image_); } row = 0; auto opt_item = new QStandardItem("OptionalHeader"); nt_item->appendRow(opt_item); nt_item->setChild(2, 1, new QStandardItem(opt_title)); if (pe_x64_) { AppendTreeItem(opt_item, "Magic", WordToHexQ(opt_hdr64->Magic)); AppendTreeItem(opt_item, "MajorLinkerVersion", ByteToHexQ(opt_hdr64->MajorLinkerVersion)); AppendTreeItem(opt_item, "MinorLinkerVersion", ByteToHexQ(opt_hdr64->MinorLinkerVersion)); AppendTreeItem(opt_item, "SizeOfCode", DWordToHexQ(opt_hdr64->SizeOfCode)); AppendTreeItem(opt_item, "SizeOfInitializedData", DWordToHexQ(opt_hdr64->SizeOfInitializedData)); AppendTreeItem(opt_item, "SizeOfUninitializedData", DWordToHexQ(opt_hdr64->SizeOfUninitializedData)); AppendTreeItem(opt_item, "AddressOfEntryPoint", DWordToHexQ(opt_hdr64->AddressOfEntryPoint)); AppendTreeItem(opt_item, "BaseOfCode", DWordToHexQ(opt_hdr64->BaseOfCode)); AppendTreeItem(opt_item, "ImageBase", QWordToHexQ(opt_hdr64->ImageBase)); AppendTreeItem(opt_item, "SectionAlignment", DWordToHexQ(opt_hdr64->SectionAlignment)); AppendTreeItem(opt_item, "FileAlignment", DWordToHexQ(opt_hdr64->FileAlignment)); AppendTreeItem(opt_item, "MajorOperatingSystemVersion", WordToHexQ(opt_hdr64->MajorOperatingSystemVersion)); AppendTreeItem(opt_item, "MinorOperatingSystemVersion", WordToHexQ(opt_hdr64->MinorOperatingSystemVersion)); AppendTreeItem(opt_item, "MajorImageVersion", WordToHexQ(opt_hdr64->MajorImageVersion)); AppendTreeItem(opt_item, "MinorImageVersion", WordToHexQ(opt_hdr64->MinorImageVersion)); AppendTreeItem(opt_item, "MajorSubsystemVersion", WordToHexQ(opt_hdr64->MajorSubsystemVersion)); AppendTreeItem(opt_item, "MinorSubsystemVersion", WordToHexQ(opt_hdr64->MinorSubsystemVersion)); AppendTreeItem(opt_item, "Win32VersionValue", DWordToHexQ(opt_hdr64->Win32VersionValue)); AppendTreeItem(opt_item, "SizeOfImage", DWordToHexQ(opt_hdr64->SizeOfImage)); AppendTreeItem(opt_item, "SizeOfHeaders", DWordToHexQ(opt_hdr64->SizeOfHeaders)); AppendTreeItem(opt_item, "CheckSum", DWordToHexQ(opt_hdr64->CheckSum)); AppendTreeItem(opt_item, "Subsystem", WordToHexQ(opt_hdr64->Subsystem)); AppendTreeItem(opt_item, "DllCharacteristics", WordToHexQ(opt_hdr64->DllCharacteristics)); AppendTreeItem(opt_item, "SizeOfStackReserve", QWordToHexQ(opt_hdr64->SizeOfStackReserve)); AppendTreeItem(opt_item, "SizeOfStackCommit", QWordToHexQ(opt_hdr64->SizeOfStackCommit)); AppendTreeItem(opt_item, "SizeOfHeapReserve", QWordToHexQ(opt_hdr64->SizeOfHeapReserve)); AppendTreeItem(opt_item, "SizeOfHeapCommit", QWordToHexQ(opt_hdr64->SizeOfHeapCommit)); AppendTreeItem(opt_item, "LoaderFlags", DWordToHexQ(opt_hdr64->LoaderFlags)); AppendTreeItem(opt_item, "NumberOfRvaAndSizes", DWordToHexQ(opt_hdr64->NumberOfRvaAndSizes)); } else { AppendTreeItem(opt_item, "Magic", WordToHexQ(opt_hdr32->Magic)); AppendTreeItem(opt_item, "MajorLinkerVersion", ByteToHexQ(opt_hdr32->MajorLinkerVersion)); AppendTreeItem(opt_item, "MinorLinkerVersion", ByteToHexQ(opt_hdr32->MinorLinkerVersion)); AppendTreeItem(opt_item, "SizeOfCode", DWordToHexQ(opt_hdr32->SizeOfCode)); AppendTreeItem(opt_item, "SizeOfInitializedData", DWordToHexQ(opt_hdr32->SizeOfInitializedData)); AppendTreeItem(opt_item, "SizeOfUninitializedData", DWordToHexQ(opt_hdr32->SizeOfUninitializedData)); AppendTreeItem(opt_item, "AddressOfEntryPoint", DWordToHexQ(opt_hdr32->AddressOfEntryPoint)); AppendTreeItem(opt_item, "BaseOfCode", DWordToHexQ(opt_hdr32->BaseOfCode)); AppendTreeItem(opt_item, "BaseOfData", DWordToHexQ(opt_hdr32->BaseOfData)); AppendTreeItem(opt_item, "ImageBase", DWordToHexQ(opt_hdr32->ImageBase)); AppendTreeItem(opt_item, "SectionAlignment", DWordToHexQ(opt_hdr32->SectionAlignment)); AppendTreeItem(opt_item, "FileAlignment", DWordToHexQ(opt_hdr32->FileAlignment)); AppendTreeItem(opt_item, "MajorOperatingSystemVersion", WordToHexQ(opt_hdr32->MajorOperatingSystemVersion)); AppendTreeItem(opt_item, "MinorOperatingSystemVersion", WordToHexQ(opt_hdr32->MinorOperatingSystemVersion)); AppendTreeItem(opt_item, "MajorImageVersion", WordToHexQ(opt_hdr32->MajorImageVersion)); AppendTreeItem(opt_item, "MinorImageVersion", WordToHexQ(opt_hdr32->MinorImageVersion)); AppendTreeItem(opt_item, "MajorSubsystemVersion", WordToHexQ(opt_hdr32->MajorSubsystemVersion)); AppendTreeItem(opt_item, "MinorSubsystemVersion", WordToHexQ(opt_hdr32->MinorSubsystemVersion)); AppendTreeItem(opt_item, "Win32VersionValue", DWordToHexQ(opt_hdr32->Win32VersionValue)); AppendTreeItem(opt_item, "SizeOfImage", DWordToHexQ(opt_hdr32->SizeOfImage)); AppendTreeItem(opt_item, "SizeOfHeaders", DWordToHexQ(opt_hdr32->SizeOfHeaders)); AppendTreeItem(opt_item, "CheckSum", DWordToHexQ(opt_hdr32->CheckSum)); AppendTreeItem(opt_item, "Subsystem", WordToHexQ(opt_hdr32->Subsystem)); AppendTreeItem(opt_item, "DllCharacteristics", WordToHexQ(opt_hdr32->DllCharacteristics)); AppendTreeItem(opt_item, "SizeOfStackReserve", DWordToHexQ(opt_hdr32->SizeOfStackReserve)); AppendTreeItem(opt_item, "SizeOfStackCommit", DWordToHexQ(opt_hdr32->SizeOfStackCommit)); AppendTreeItem(opt_item, "SizeOfHeapReserve", DWordToHexQ(opt_hdr32->SizeOfHeapReserve)); AppendTreeItem(opt_item, "SizeOfHeapCommit", DWordToHexQ(opt_hdr32->SizeOfHeapCommit)); AppendTreeItem(opt_item, "LoaderFlags", DWordToHexQ(opt_hdr32->LoaderFlags)); AppendTreeItem(opt_item, "NumberOfRvaAndSizes", DWordToHexQ(opt_hdr32->NumberOfRvaAndSizes)); } auto dir_item = new QStandardItem("DataDirectory[]"); opt_item->appendRow(dir_item); opt_item->setChild(row++, 1, new QStandardItem("IMAGE_DATA_DIRECTORY")); QStandardItem* subdir_item; PIMAGE_DATA_DIRECTORY dir; struct {char* name; int value;} dir_arr[] = { "IMAGE_DIRECTORY_ENTRY_EXPORT", IMAGE_DIRECTORY_ENTRY_EXPORT, "IMAGE_DIRECTORY_ENTRY_IMPORT", IMAGE_DIRECTORY_ENTRY_IMPORT, "IMAGE_DIRECTORY_ENTRY_RESOURCE", IMAGE_DIRECTORY_ENTRY_RESOURCE, "IMAGE_DIRECTORY_ENTRY_EXCEPTION", IMAGE_DIRECTORY_ENTRY_EXCEPTION, "IMAGE_DIRECTORY_ENTRY_SECURITY", IMAGE_DIRECTORY_ENTRY_SECURITY, "IMAGE_DIRECTORY_ENTRY_BASERELOC", IMAGE_DIRECTORY_ENTRY_BASERELOC, "IMAGE_DIRECTORY_ENTRY_DEBUG", IMAGE_DIRECTORY_ENTRY_DEBUG, "IMAGE_DIRECTORY_ENTRY_ARCHITECTURE", IMAGE_DIRECTORY_ENTRY_ARCHITECTURE, "IMAGE_DIRECTORY_ENTRY_GLOBALPTR", IMAGE_DIRECTORY_ENTRY_GLOBALPTR, "IMAGE_DIRECTORY_ENTRY_TLS", IMAGE_DIRECTORY_ENTRY_TLS, "IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG", IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, "IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT", IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT, "IMAGE_DIRECTORY_ENTRY_IAT", IMAGE_DIRECTORY_ENTRY_IAT, "IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT", IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, "IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR", IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR }; for (int i = 0; i < _countof(dir_arr); i++) { row = 0; subdir_item = new QStandardItem(dir_arr[i].name); dir_item->appendRow(subdir_item); dir_item->setChild(dir_arr[i].value, 1, new QStandardItem(StrToQ(UNONE::StrFormatA("%d", dir_arr[i].value)))); dir = UNONE::PeGetDataDirectory(dir_arr[i].value, pe_image_); AppendTreeItem(subdir_item, "VirtualAddress",DWordToHexQ(dir->VirtualAddress)); AppendTreeItem(subdir_item, "Size", DWordToHexQ(dir->Size)); } } void Scanner::RefreshSections() { PIMAGE_NT_HEADERS nt_header = PE_NT_HEADER(pe_image_); PIMAGE_SECTION_HEADER header = IMAGE_FIRST_SECTION(nt_header); for (DWORD i = 0; i < nt_header->FileHeader.NumberOfSections; i++) { char name[IMAGE_SIZEOF_SHORT_NAME+1] = { 0 }; memcpy(name, header->Name, IMAGE_SIZEOF_SHORT_NAME); InitTableItem(sections_model_); AppendTableItem(sections_model_, CharsToQ(name)); AppendTableItem(sections_model_, DWordToHexQ(header->Misc.VirtualSize)); AppendTableItem(sections_model_, DWordToHexQ(header->VirtualAddress)); AppendTableItem(sections_model_, DWordToHexQ(header->SizeOfRawData)); AppendTableItem(sections_model_, DWordToHexQ(header->PointerToRawData)); AppendTableItem(sections_model_, DWordToHexQ(header->PointerToRelocations)); AppendTableItem(sections_model_, DWordToHexQ(header->PointerToLinenumbers)); AppendTableItem(sections_model_, DWordToHexQ(header->NumberOfRelocations)); AppendTableItem(sections_model_, DWordToHexQ(header->NumberOfLinenumbers)); AppendTableItem(sections_model_, DWordToHexQ(header->Characteristics)); header++; } } void Scanner::RefreshImport() { auto imp = (PIMAGE_IMPORT_DESCRIPTOR)UNONE::PeGetDataEntity(IMAGE_DIRECTORY_ENTRY_IMPORT, pe_image_); if (!imp) return; while (imp->Name != 0) { InitTableItem(imp_model_); AppendTableItem(imp_model_, CharsToQ(pe_image_ + imp->Name)); AppendTableItem(imp_model_, DWordToHexQ(imp->OriginalFirstThunk)); AppendTableItem(imp_model_, DWordToHexQ(imp->TimeDateStamp)); AppendTableItem(imp_model_, DWordToHexQ(imp->ForwarderChain)); AppendTableItem(imp_model_, DWordToHexQ(imp->FirstThunk)); imp++; } } void Scanner::RefreshExport() { #define AppendExpKvItem(key, value) \ item = new QStandardItem(key); \ count = exp_model_->rowCount();\ exp_model_->setItem(count, 0, item); \ item = new QStandardItem(value); \ exp_model_->setItem(count, 1, item); int row = 0, count = 0; QStandardItem *item; auto exp = (PIMAGE_EXPORT_DIRECTORY)UNONE::PeGetDataEntity(IMAGE_DIRECTORY_ENTRY_EXPORT, pe_image_); if (!exp) return; AppendExpKvItem("Characteristics", DWordToHexQ(exp->Characteristics)); AppendExpKvItem("TimeDateStamp", DWordToHexQ(exp->TimeDateStamp)); AppendExpKvItem("MajorVersion", WordToHexQ(exp->MajorVersion)); AppendExpKvItem("MinorVersion", WordToHexQ(exp->MinorVersion)); AppendExpKvItem("Name", DWordToHexQ(exp->Name)); AppendExpKvItem("Base", DWordToHexQ(exp->Base)); AppendExpKvItem("NumberOfFunctions", DWordToHexQ(exp->NumberOfFunctions)); AppendExpKvItem("NumberOfNames", DWordToHexQ(exp->NumberOfNames)); AppendExpKvItem("AddressOfFunctions", DWordToHexQ(exp->AddressOfFunctions)); AppendExpKvItem("AddressOfNames", DWordToHexQ(exp->AddressOfNames)); AppendExpKvItem("AddressOfNameOrdinals", DWordToHexQ(exp->AddressOfNameOrdinals)); PIMAGE_DATA_DIRECTORY dir = UNONE::PeGetDataDirectory(IMAGE_DIRECTORY_ENTRY_EXPORT, pe_image_); PDWORD addr_names = (PDWORD)(exp->AddressOfNames + pe_image_); if (!UNONE::PeRegionValid(pe_image_, addr_names)) return; PDWORD addr_funcs = (PDWORD)(exp->AddressOfFunctions + pe_image_); if (!UNONE::PeRegionValid(pe_image_, addr_funcs)) return; PWORD addr_ordinals = (PWORD)(exp->AddressOfNameOrdinals + pe_image_); if (!UNONE::PeRegionValid(pe_image_, addr_ordinals)) return; DWORD cnt_names = exp->NumberOfNames; DWORD cnt_ordinals = exp->NumberOfFunctions; DWORD base_ordinal = exp->Base; for (DWORD i = 0; i < cnt_names; i++) { DWORD idx = addr_ordinals[i]; DWORD func_addr = addr_funcs[idx]; CHAR* func_name = pe_image_ + addr_names[i]; InitTableItem2(exp_func_model_, exp_func_model_->rowCount()); AppendTableItem(exp_func_model_, DWordToHexQ(func_addr)); AppendTableItem(exp_func_model_, DWordToHexQ(idx)); AppendTableItem(exp_func_model_, CharsToQ(func_name)); } } void Scanner::RefreshResource() { } void Scanner::RefreshRelocation() { auto reloc = (PIMAGE_BASE_RELOCATION)UNONE::PeGetDataEntity(IMAGE_DIRECTORY_ENTRY_BASERELOC, pe_image_); if (!reloc) return; PIMAGE_DATA_DIRECTORY dir = UNONE::PeGetDataDirectory(IMAGE_DIRECTORY_ENTRY_BASERELOC, pe_image_); DWORD reloc_size = dir->Size; DWORD reloc_rva = dir->VirtualAddress; DWORD item_size = 0; while (item_size < reloc_size) { DWORD itemcnt = (reloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT); InitTableItem(reloc_model_); AppendTableItem(reloc_model_, DWordToHexQ(reloc->VirtualAddress)); AppendTableItem(reloc_model_, DWordToHexQ(reloc->SizeOfBlock)); AppendTableItem(reloc_model_, DWordToDecQ(itemcnt)); item_size += reloc->SizeOfBlock; reloc = (PIMAGE_BASE_RELOCATION)(pe_image_ + reloc_rva + item_size); } } void Scanner::RefreshDebug() { ClearItemModelData(dbg_model_); PIMAGE_DEBUG_DIRECTORY dbg = (PIMAGE_DEBUG_DIRECTORY)UNONE::PeGetDataEntity(IMAGE_DIRECTORY_ENTRY_DEBUG, pe_image_); if (dbg == NULL || dbg->Type != IMAGE_DEBUG_TYPE_CODEVIEW || !dbg->AddressOfRawData || !dbg->SizeOfData) { return; } UNONE::CV_HEADER* cv_hdr = (UNONE::CV_HEADER*)(pe_image_ + dbg->AddressOfRawData); DWORD cv_size = dbg->SizeOfData; if (!UNONE::PeRegionValid(pe_image_, cv_hdr, cv_size)) return; int count = 0; AppendNameValue(dbg_model_, tr("Characteristics"), DWordToHexQ(dbg->Characteristics)); AppendNameValue(dbg_model_, tr("TimeDateStamp"), DWordToHexQ(dbg->TimeDateStamp)); AppendNameValue(dbg_model_, tr("MajorVersion"), WordToHexQ(dbg->MajorVersion)); AppendNameValue(dbg_model_, tr("MinorVersion"), WordToHexQ(dbg->MinorVersion)); AppendNameValue(dbg_model_, tr("Type"), DWordToHexQ(dbg->Type)); AppendNameValue(dbg_model_, tr("SizeOfData"), DWordToHexQ(dbg->SizeOfData)); AppendNameValue(dbg_model_, tr("AddressOfRawData"), DWordToHexQ(dbg->AddressOfRawData)); AppendNameValue(dbg_model_, tr("PointerToRawData"), DWordToHexQ(dbg->PointerToRawData)); PIMAGE_NT_HEADERS nt_hdr = PE_NT_HEADER(pe_image_); PIMAGE_FILE_HEADER file_hdr = &nt_hdr->FileHeader; auto ts = file_hdr->TimeDateStamp; PIMAGE_OPTIONAL_HEADER32 opt_hdr32; PIMAGE_OPTIONAL_HEADER64 opt_hdr64; ULONG imgsize; char* opt_title; if (pe_x64_) imgsize = PE_OPT_HEADER64(pe_image_)->SizeOfImage; else imgsize = PE_OPT_HEADER32(pe_image_)->SizeOfImage; auto imgid = UNONE::StrFormatA("%X%x", ts, imgsize); DWORD age = 0; CHAR *sig = ""; std::string pdb, guidsig, symid; if (cv_hdr->Signature == NB10_SIG) { sig = "NB10"; age = ((UNONE::CV_INFO_PDB20*)cv_hdr)->Age; auto name = (CHAR*)((UNONE::CV_INFO_PDB20*)cv_hdr)->PdbFileName; auto name_size = (DWORD)strlen(name); if (name_size && name_size < MAX_PATH) pdb = name; } else if (cv_hdr->Signature == RSDS_SIG) { sig = "RSDS"; auto name = (CHAR*)((UNONE::CV_INFO_PDB70*)cv_hdr)->PdbFileName; auto name_size = (DWORD)strlen(name); if (name_size && name_size < MAX_PATH) pdb = name; GUID guid = ((UNONE::CV_INFO_PDB70*)cv_hdr)->Signature; age = ((UNONE::CV_INFO_PDB70*)cv_hdr)->Age; guidsig = UNONE::StrFormatA("{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); symid = UNONE::StrFormatA("%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X%X", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7], age); pdb = UNONE::StrUTF8ToACP(name); } AppendNameValue(dbg_model_, tr("Signature"), CharsToQ(sig)); AppendNameValue(dbg_model_, tr("Age"), DWordToHexQ(age)); AppendNameValue(dbg_model_, tr("GUID"), StrToQ(guidsig)); AppendNameValue(dbg_model_, tr("ImageID"), StrToQ(imgid)); AppendNameValue(dbg_model_, tr("SymbolID"), StrToQ(symid)); AppendNameValue(dbg_model_, tr("PDB"), WStrToQ(UNONE::StrToW(pdb))); } void Scanner::RefreshRva() { connect(ui.baseEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.rebaseEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.vaEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.revaEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.rvaEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); connect(ui.rawEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&))); if (pe_x64_) { ULONGLONG base = PE_OPT_HEADER64(pe_image_)->ImageBase; base_prev_ = base; QString basestr = StrToQ(UNONE::StrFormatA("%llX", base)); ui.baseEdit->setText(basestr); ui.vaEdit->setText(basestr); ui.rebaseEdit->setText(basestr); ui.revaEdit->setText(basestr); } else { ULONG base = PE_OPT_HEADER32(pe_image_)->ImageBase; base_prev_ = base; QString basestr = StrToQ(UNONE::StrFormatA("%X", base)); ui.baseEdit->setText(basestr); ui.vaEdit->setText(basestr); ui.rebaseEdit->setText(basestr); ui.revaEdit->setText(basestr); } ui.rvaEdit->setText("0"); ui.rawEdit->setText("0"); }
38,992
C++
.cpp
851
43.104583
310
0.73374
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,160
process-mgr.cpp
BlackINT3_OpenArk/src/OpenArk/process-mgr/process-mgr.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "process-mgr.h" #include "../common/common.h" #include "../cmds/constants/constants.h" #include "../openark/openark.h" #include "process-properties.h" #include "process-selection.h" #include <arkdrv-api/arkdrv-api.h> // ProcessView's header index struct { int s = 0; int name = s++; int pid = s++; int ppid = s++; int path = s++; int desc = s++; int corp = s++; int ctime = s++; } PS; // ModuleView's header index struct { int s = 0; int name = s++; int base = s++; int size = s++; int path = s++; int desc = s++; int ver = s++; int corp = s++; int sign = s++; } MOD; // HandleView's header index struct { int s = 0; int type = s++; int name = s++; int value = s++; int access = s++; int obj = s++; } HD; // MemoryView's header index struct { int s = 0; int addr = s++; int size = s++; int property = s++; int state = s++; int type = s++; int base = s++; int mod = s++; } MEM; #define BOTTOM_HIDE -1 #define BOTTOM_MOD 0 #define BOTTOM_HD 1 #define BOTTOM_MEM 2 bool ProcSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); auto column = left.column(); if ((column == PS.pid || column == PS.ppid)) return s1.toUInt() < s2.toUInt(); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } bool ModSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); auto column = left.column(); bool ok; if (bottom_idx_ == BOTTOM_MOD) { if ((column == MOD.base || column == MOD.size)) return s1.toString().toULongLong(&ok, 16) < s2.toString().toULongLong(&ok, 16); } else if (bottom_idx_ == BOTTOM_HD) { if ((column == HD.value || column == HD.access || column == HD.obj)) return s1.toString().toULongLong(&ok, 16) < s2.toString().toULongLong(&ok, 16); } else if (bottom_idx_ == BOTTOM_MEM) { if ((column == MEM.addr || column == MEM.size || column == MEM.base)) return s1.toString().toULongLong(&ok, 16) < s2.toString().toULongLong(&ok, 16); } return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } ProcessMgr::ProcessMgr(QWidget* parent) : parent_((OpenArk*)parent), cntproc_label_(nullptr), proxy_proc_(nullptr), proc_header_idx_(0), bottom_header_idx_(0), bottom_idx_(BOTTOM_HIDE), mod_menu_(nullptr), hd_menu_(nullptr), mem_menu_(nullptr) { unnamed_checked_ = false; uncommed_checked_ = false; nonexec_checked_ = false; imaged_checked_ = false; ui.setupUi(this); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); ui.splitter->setStretchFactor(0, 2); ui.splitter->setStretchFactor(1, 1); InitProcessView(); InitBottomCommon(); InitModuleView(); InitHandleView(); InitMemoryView(); connect(parent_, SIGNAL(signalShowPtool(int)), this, SLOT(onShowBottom(int))); connect(this, SIGNAL(signalOpen(QString)), parent_, SLOT(onOpen(QString))); connect(&timer_, SIGNAL(timeout()), this, SLOT(onTimer())); timer_.setInterval(1000); timer_.start(); } ProcessMgr::~ProcessMgr() { timer_.stop(); } bool ProcessMgr::eventFilter(QObject *obj, QEvent *e) { bool filtered = false; if (obj == ui.processView->viewport()) { if (e->type() == QEvent::ContextMenu) { QContextMenuEvent* ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt != nullptr) { proc_menu_->move(ctxevt->globalPos()); proc_menu_->show(); } } else if (e->type() == QEvent::MouseMove) { QMouseEvent *mouse = static_cast<QMouseEvent *>(e); QPoint pt = mouse->pos(); if (pt.rx() <= ui.processView->columnWidth(0)) { DISABLE_RECOVER(); QModelIndex idx = ui.processView->indexAt(pt); const QModelIndex &curidx = idx.sibling(idx.row(), 1); if (!curidx.isValid()) return true; auto pid = curidx.data(Qt::DisplayRole).toInt(); if (pid == 0 || pid == 4) return true; auto info = CacheGetProcessBaseInfo(pid); info.CommandLine = UNONE::StrInsertW(info.CommandLine, 120, L"\n "); info.ImagePathName = UNONE::StrInsertW(info.ImagePathName, 120, L"\n "); QString tips = QString("Command Line:\n %1\nPath:\n %2").arg(WStrToQ(info.CommandLine)).arg(WStrToQ(info.ImagePathName)); QToolTip::showText(mouse->globalPos(), tips); return true; } } } else if (obj == ui.moduleView->viewport()) { if (e->type() == QEvent::ContextMenu) { QContextMenuEvent* ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt != nullptr) { QMenu *menu = nullptr; switch (bottom_idx_) { case BOTTOM_MOD: menu = mod_menu_; break; case BOTTOM_HD: menu = hd_menu_; break; case BOTTOM_MEM: menu = mem_menu_; break; } if (menu) { menu->move(ctxevt->globalPos()); menu->show(); } } } } else if (obj == ui.processView) { if (e->type() == QEvent::KeyPress) { filtered = true; QKeyEvent *keyevt = dynamic_cast<QKeyEvent*>(e); if (keyevt->matches(QKeySequence::Refresh)) { onRefresh(); } else if (keyevt->matches(QKeySequence::Delete)) { onKillProcess(); } else if (keyevt->key() == Qt::Key_Delete && keyevt->modifiers() == Qt::ShiftModifier) { onKillProcessTree(); } else if (keyevt->key() == Qt::Key_L && keyevt->modifiers() == Qt::ControlModifier) { onExploreFile(); } else if (keyevt->key() == Qt::Key_J && keyevt->modifiers() == Qt::ControlModifier) { onInjectDll(); } else if (keyevt->key() == Qt::Key_G && keyevt->modifiers() == Qt::ControlModifier) { onSelectPid(); } else if (keyevt->key() == Qt::Key_P && keyevt->modifiers() == Qt::ControlModifier) { onShowProperties(); } else { filtered = false; } } } if (filtered) { dynamic_cast<QKeyEvent*>(e)->ignore(); return true; } return QWidget::eventFilter(obj, e); } void ProcessMgr::onOpenFile(const QString& file) { } void ProcessMgr::onRefresh() { auto sender = QObject::sender(); if (IsContainAction(proc_menu_, sender)) { onShowProcess(); return; } if (IsContainAction(mod_menu_, sender)) { onShowModule(); return; } if (sender == nullptr) { onShowProcess(); return; } } void ProcessMgr::onReset() { //proxy_model_->setSortRole(Qt::InitialSortOrderRole); //proxy_model_->invalidate(); ui.processView->header()->setSortIndicator(-1, Qt::AscendingOrder); ui.moduleView->header()->setSortIndicator(-1, Qt::AscendingOrder); onRefresh(); } void ProcessMgr::onTimer() { //ShowProcessList(); PERFORMANCE_INFORMATION perf = { 0 }; GetPerformanceInfo(&perf, sizeof(perf)); if (cntproc_label_ == nullptr) { cpu_percent_label_ = new QLabel(); parent_->StatusBarAdd(cpu_percent_label_); mm_percent_label_ = new QLabel(); parent_->StatusBarAdd(mm_percent_label_); cntproc_label_ = new QLabel(); parent_->StatusBarAdd(cntproc_label_); cntthread_label_ = new QLabel(); parent_->StatusBarAdd(cntthread_label_); cnthandle_label_ = new QLabel(); parent_->StatusBarAdd(cnthandle_label_); } cpu_percent_label_->setText(tr("CPU:") + WStrToQ(UNONE::StrFormatW(L"%0.2f%%", GetSystemUsageOfCPU()))); mm_percent_label_->setText(tr("Memory:") + WStrToQ(UNONE::StrFormatW(L"%0.2f%%", GetSystemUsageOfMemory()))); cntproc_label_->setText(tr("Processes:") + QString("%1").arg(perf.ProcessCount)); cntthread_label_->setText(tr("Threads:") + QString("%1").arg(perf.ThreadCount)); cnthandle_label_->setText(tr("Handles:") + QString("%1").arg(perf.HandleCount)); } void ProcessMgr::onCopyActionTriggerd(QAction* action) { auto idx = action->data().toInt(); QString data = ProcCurViewItemData(idx); if (idx == 0) data.replace(" *32", ""); ClipboardCopyData(data.toStdString()); } void ProcessMgr::onKillProcess() { PsKillProcess(ProcCurPid()); onRefresh(); } void ProcessMgr::onKillProcessTree() { QString tips; auto pid = ProcCurPid(); auto pids = UNONE::PsGetDescendantPids(pid); pids.push_back(pid); tips.append(tr("Do you kill all processes?\n-------------------\n")); for (auto d : pids) { std::wstring wstr = UNONE::StrFormatW(L"[%d] %s", d, UNONE::PsGetProcessNameW(d).c_str()); tips.append(WStrToQ(wstr)); tips.append("\n"); } auto msbox = QMessageBox::warning(this, tr("Warning"), tips, QMessageBox::Yes | QMessageBox::No); if (msbox == QMessageBox::Yes) { for (auto d : pids) { PsKillProcess(d); }; onRefresh(); } } void ProcessMgr::onRestartProcess() { UNONE::PsRestartProcess(ProcCurPid()); onRefresh(); } void ProcessMgr::onSuspendProcess() { } void ProcessMgr::onInjectDll() { QString file = QFileDialog::getOpenFileName(this, tr("Select Dll"), "", tr("Dll Files (*.dll);;All Files (*.*)")); if (file.isEmpty()) return; std::wstring dll = file.toStdWString(); std::string buf; UNONE::FsReadFileDataW(dll, buf); if (buf.empty() || !UNONE::PeValid((CHAR*)buf.c_str())) { MsgBoxError(tr("Dll file invalid.")); return; } auto pid = ProcCurPid(); bool is_dll64 = UNONE::PeX64((CHAR*)buf.c_str()); bool is_exe64 = UNONE::PsIsX64(pid); if ((!is_dll64 && is_exe64)) { MsgBoxError(tr("Can't inject 32-bit dll to 64-bit process.")); return; } if ((is_dll64 && !is_exe64)) { MsgBoxWarn(tr("Inject 64-bit dll to 32-bit process, maybe fail.")); } auto thd = UNONE::PsInjectByRemoteThreadW(pid, dll); if (thd) { MsgBoxInfo(tr("Inject ok.")); } else { MsgBoxError(tr("Inject failed.")); } CloseHandle(thd); } void ProcessMgr::onSelectPid() { auto dlg = new ProcessSelection(this); dlg->setObjectName("ProcessSelection"); dlg->raise(); dlg->show(); } void ProcessMgr::onExploreFile() { auto sender = QObject::sender(); if (IsContainAction(proc_menu_, sender)) { ExploreFile(ProcCurViewItemData(PS.path)); return; } if (IsContainAction(mod_menu_, sender)) { ExploreFile(BottomCurViewItemData(MOD.path)); return; } if (sender == nullptr) { ExploreFile(ProcCurViewItemData(PS.path)); return; } } void ProcessMgr::onEnumThread() { ShowProperties(ProcCurPid(), 1); } void ProcessMgr::onEnumWindow() { ShowProperties(ProcCurPid(), 2); } void ProcessMgr::onCreateMiniDump() { DWORD pid = ProcCurPid(); QString name = WStrToQ(UNONE::PsGetProcessNameW(pid)).replace(".exe", ".dmp", Qt::CaseInsensitive); QString dmp = QFileDialog::getSaveFileName(this, tr("Save dump file"), name, tr("DumpFile(*.dmp)")); if (dmp.isEmpty()) return; CreateDump(pid, dmp.toStdWString(), true); } void ProcessMgr::onCreateFullDump() { DWORD pid = ProcCurPid(); QString name = WStrToQ(UNONE::PsGetProcessNameW(pid)).replace(".exe", ".dmp", Qt::CaseInsensitive); QString dmp = QFileDialog::getSaveFileName(this, tr("Save dump file"), name, tr("DumpFile(*.dmp)")); if (dmp.isEmpty()) return; CreateDump(pid, dmp.toStdWString(), false); } void ProcessMgr::onSendtoScanner() { QString path; auto action = qobject_cast<QAction*>(QObject::sender()); if (IsContainAction(proc_menu_, action)) { path = ProcCurViewItemData(PS.path); } else if (IsContainAction(mod_menu_, action)) { path = BottomCurViewItemData(MOD.path); } parent_->SetActiveTab(TAB_SCANNER); emit signalOpen(path); } void ProcessMgr::onVerifySignature() { QString path; path = BottomCurViewItemData(MOD.path); auto row = ui.moduleView->currentIndex().row(); QString owner; bool ret = GetCertOwner(path, owner); if (!ret) { auto err = GetLastError(); owner = WStrToQ(UNONE::StrFormatW(L"[-] %X %s", err, UNONE::OsDosErrorMsgW(err).c_str())); SetLineBgColor(bottom_model_, row, Qt::red); } SetCurItemViewData(ui.moduleView, MOD.sign, owner); } void ProcessMgr::onVerifyAllSignature() { for (int i = 0; i < bottom_model_->rowCount(); i++) { auto row = i; QString path = bottom_model_->item(row, MOD.path)->data(Qt::DisplayRole).toString(); QString owner; bool ret = GetCertOwner(path, owner); if (!ret) { auto err = GetLastError(); owner = WStrToQ(UNONE::StrFormatW(L"[-] %X %s", err, UNONE::OsDosErrorMsgW(err).c_str())); SetLineBgColor(bottom_model_, row, Qt::red); } bottom_model_->item(row, MOD.sign)->setData(owner, Qt::DisplayRole); } ui.moduleView->header()->setSortIndicator(MOD.sign, Qt::AscendingOrder); } void ProcessMgr::onShowProperties() { ShowProperties(ProcCurPid(), 0); } void ProcessMgr::onCloseHandle() { auto src_hd = (HANDLE)(UNONE::StrToHex64A(BottomCurViewItemData(HD.value).toStdString())); DWORD pid = ProcCurPid(); HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); if (!phd) { ERR(L"OpenProcess pid:%d err:%d", pid, GetLastError()); return; } HANDLE dup = NULL; if (!DuplicateHandle(phd, (HANDLE)src_hd, GetCurrentProcess(), &dup, 0, FALSE, DUPLICATE_CLOSE_SOURCE)) { ERR(L"DuplicateHandle pid:%d hd:%x err:%d", pid, src_hd, GetLastError()); CloseHandle(phd); return; } INFO(L"DuplicateHandle pid:%d hd:%x ok", pid, src_hd); CloseHandle(dup); CloseHandle(phd); onShowHandle(); } void ProcessMgr::onHideUnnamedHandles(bool checked) { unnamed_checked_ = checked; for (int i = 0; i < bottom_model_->rowCount(); i++) { if (!checked) { SetLineHidden(ui.moduleView, i, false); continue; } if (bottom_model_->item(i, HD.name)->data(Qt::DisplayRole).toString().isEmpty()) { QModelIndex idx = bottom_model_->index(i, HD.name); SetLineHidden(ui.moduleView, proxy_bottom_->mapFromSource(idx).row(), true); } } } void ProcessMgr::onHideMemoryItem(bool checked) { auto sender = QObject::sender(); if (sender == ui.actionHideUncommited) uncommed_checked_ = checked; else if (sender == ui.actionHideNonExecute) nonexec_checked_ = checked; else if (sender == ui.actionHideImage) imaged_checked_ = checked; for (int i = 0; i < bottom_model_->rowCount(); i++) { bool hidden = false; if (uncommed_checked_) { if (bottom_model_->item(i, MEM.state)->data(Qt::DisplayRole).toString() != "MEM_COMMIT") hidden = true; } if (nonexec_checked_) { if (!bottom_model_->item(i, MEM.property)->data(Qt::DisplayRole).toString().contains("EXECUTE")) hidden = true; } if (imaged_checked_) { if (bottom_model_->item(i, MEM.type)->data(Qt::DisplayRole).toString() == "MEM_IMAGE") hidden = true; } QModelIndex idx = bottom_model_->index(i, HD.name); if (hidden) { SetLineHidden(ui.moduleView, proxy_bottom_->mapFromSource(idx).row(), true); } else { SetLineHidden(ui.moduleView, proxy_bottom_->mapFromSource(idx).row(), false); } } } void ProcessMgr::onDumpMemory() { DWORD pid = ProcCurPid(); HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); if (!phd) { ERR(L"OpenProcess pid:%d err:%d", pid, GetLastError()); return; } DWORD size = UNONE::StrToHexA(BottomCurViewItemData(MEM.size).toStdString()); DWORD64 addr = UNONE::StrToHex64A(BottomCurViewItemData(MEM.base).toStdString()); std::string data; data.resize(size); SIZE_T readlen; bool ret = ReadProcessMemory(phd, (LPCVOID)addr, (LPVOID)data.data(), size, &readlen); if (!ret && size != readlen) { ERR(L"ReadProcessMemory pid:%d err:%d, expect:%d readlen:%d", pid, GetLastError(), size, readlen); CloseHandle(phd); return; } QString filename = StrToQ(UNONE::StrFormatA("%X_%X", addr, size)); QString dumpmem = QFileDialog::getSaveFileName(this, tr("Save to"), filename, tr("DumpMemory(*)")); if (!dumpmem.isEmpty()) { ret = UNONE::FsWriteFileDataW(dumpmem.toStdWString(), data); if (ret) { MsgBoxInfo(tr("Dump memory ok")); } } CloseHandle(phd); } void ProcessMgr::onShowBottom(int idx) { ui.moduleView->show(); switch (idx) { case BOTTOM_MOD: onShowModule(); break; case BOTTOM_HD: onShowHandle(); break; case BOTTOM_MEM: onShowMemory(); break; default: ui.moduleView->hide(); break; } bottom_idx_ = idx; proxy_bottom_->bottom_idx_ = idx; } void ProcessMgr::onShowProcess() { DISABLE_RECOVER(); auto view = ui.processView; auto selected = view->selectionModel()->selectedIndexes(); if (!selected.empty()) { QRect rect = view->visualRect(selected[0]); proc_sel_ = rect.center(); } ClearItemModelData(proc_model_); CacheRefreshProcInfo(); if (proc_header_idx_ == 0) ShowProcessTree(); else ShowProcessList(); AjustProcessStyle(); } void ProcessMgr::onShowModule() { DISABLE_RECOVER(); ClearItemModelData(bottom_model_, 0); InitModuleView(); DWORD pid = ProcCurPid(); bool activate = false; auto &&path = UNONE::PsGetProcessPathW(pid); if (path.empty()) { UNONE::InterCreateTlsValue(ArkDrvApi::Process::OpenProcessR0, UNONE::PROCESS_VID); path = UNONE::PsGetProcessPathW(pid); activate = true; } UNONE::PsEnumModule(pid, [&](MODULEENTRY32W& entry)->bool{ QString modname = WCharsToQ(entry.szModule); QString modpath = WCharsToQ(entry.szExePath); ULONG64 modbase = (ULONG64)entry.modBaseAddr; ULONG64 modsize = entry.modBaseSize; auto count = bottom_model_->rowCount(); for (int i = 0; i < count; i++) { auto base = bottom_model_->data(bottom_model_->index(i, MOD.base)).toString().toStdWString(); if (UNONE::StrToHex64W(base) == modbase) { return true; } } auto info = CacheGetFileBaseInfo(modpath); QStandardItem *name_item = new QStandardItem(LoadIcon(modpath), modname); QStandardItem *base_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%llX", modbase))); QStandardItem *size_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%llX", modsize))); QStandardItem *path_item = new QStandardItem(modpath); QStandardItem *desc_item = new QStandardItem(info.desc); QStandardItem *ver_item = new QStandardItem(info.ver); QStandardItem *corp_item = new QStandardItem(info.corp); QStandardItem *sign_item = new QStandardItem(""); bottom_model_->setItem(count, MOD.name, name_item); bottom_model_->setItem(count, MOD.base, base_item); bottom_model_->setItem(count, MOD.size, size_item); bottom_model_->setItem(count, MOD.path, path_item); bottom_model_->setItem(count, MOD.desc, desc_item); bottom_model_->setItem(count, MOD.ver, ver_item); bottom_model_->setItem(count, MOD.corp, corp_item); bottom_model_->setItem(count, MOD.sign, sign_item); return true; }); auto view = ui.moduleView; view->setColumnWidth(MOD.name, 150); view->resizeColumnToContents(MOD.base); view->resizeColumnToContents(MOD.size); view->setColumnWidth(MOD.path, 290); view->setColumnWidth(MOD.desc, 200); view->setColumnWidth(MOD.corp, 150); } void ProcessMgr::onShowHandle() { DISABLE_RECOVER(); ClearItemModelData(bottom_model_, 0); InitHandleView(); InitObjectTypeTable(); DWORD pid = ProcCurPid(); HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); UNONE::PsEnumHandle(pid, [&](SYSTEM_HANDLE_TABLE_ENTRY_INFO &info)->bool { auto count = bottom_model_->rowCount(); auto idx = info.ObjectTypeIndex; QStandardItem *type_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%s",ObjectTypeTable[idx].c_str()))); std::string name; if (phd != NULL) { HANDLE dup = NULL; if (DuplicateHandle(phd, (HANDLE)info.HandleValue, GetCurrentProcess(), &dup, 0, FALSE, DUPLICATE_SAME_ACCESS)) { switch (idx) { case 7: { DWORD pid = GetProcessId(dup); name = UNONE::StrFormatA("%s(%d)", UNONE::PsGetProcessNameA(pid).c_str(), pid); break; } case 8: { typedef DWORD (WINAPI *__GetThreadId)(HANDLE Thread); auto pGetThreadId = (__GetThreadId)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadId"); DWORD tid = 0; if (pGetThreadId) tid = pGetThreadId(dup); DWORD pid = UNONE::PsGetPidByThread(tid); name = UNONE::StrFormatA("%s(%d) %d", UNONE::PsGetProcessNameA(pid).c_str(), pid, tid); } default: ObGetObjectName((HANDLE)dup, name); static int file_idx = GetObjectTypeIndex(L"File"); if (idx == file_idx) UNONE::ObParseToDosPathA(name, name); break; } CloseHandle(dup); } } QStandardItem *name_item = new QStandardItem(StrToQ(name)); QStandardItem *value_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%llX", info.HandleValue))); QStandardItem *access_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%llX", info.GrantedAccess))); QStandardItem *obj_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%llX", info.Object))); bottom_model_->setItem(count, HD.type, type_item); bottom_model_->setItem(count, HD.name, name_item); bottom_model_->setItem(count, HD.value, value_item); bottom_model_->setItem(count, HD.access, access_item); bottom_model_->setItem(count, HD.obj, obj_item); return true; }); CloseHandle(phd); } void ProcessMgr::onShowMemory() { DISABLE_RECOVER(); ClearItemModelData(bottom_model_, 0); InitMemoryView(); DWORD pid = ProcCurPid(); HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); UNONE::PsEnumMemory(pid, [&](MEMORY_BASIC_INFORMATION &mbi)->bool { std::wstring mod_name; WCHAR name[MAX_PATH + 1] = { 0 }; if (mbi.Type & MEM_IMAGE) { GetMappedFileNameW(phd, mbi.BaseAddress, name, MAX_PATH); UNONE::ObParseToDosPathW(name, mod_name); } auto count = bottom_model_->rowCount(); QStandardItem *addr_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%llX", mbi.BaseAddress))); QStandardItem *size_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%X", mbi.RegionSize))); QStandardItem *property_item = new QStandardItem(StrToQ(MbiPageProtectToString(mbi.Protect))); QStandardItem *state_item = new QStandardItem(StrToQ(MbiStateToString(mbi.State))); QStandardItem *type_item = new QStandardItem(StrToQ(MbiTypeToString(mbi.Type))); QStandardItem *base_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%llX", mbi.AllocationBase))); QStandardItem *mod_item = new QStandardItem(WStrToQ(mod_name)); bottom_model_->setItem(count, MEM.addr, addr_item); bottom_model_->setItem(count, MEM.size, size_item); bottom_model_->setItem(count, MEM.property, property_item); bottom_model_->setItem(count, MEM.state, state_item); bottom_model_->setItem(count, MEM.type, type_item); bottom_model_->setItem(count, MEM.base, base_item); bottom_model_->setItem(count, MEM.mod, mod_item); if ((mbi.Protect & PAGE_NOACCESS) || (mbi.State & MEM_RESERVE)) { SetLineBgColor(bottom_model_, count, Qt::gray); } return true; }); } void ProcessMgr::onSectionClicked(int idx) { auto sender = QObject::sender(); if (sender == ui.processView->header()) { if (idx == PS.name) { proc_header_idx_++; switch (proc_header_idx_) { case 3: ui.processView->header()->setSortIndicator(-1, Qt::AscendingOrder); proc_header_idx_ = 0; onShowProcess(); break; case 1: onShowProcess(); } } else { if (proc_header_idx_ == 0) { proc_header_idx_ = 1; onShowProcess(); } } } else if (sender == ui.moduleView->header()) { if (idx == bottom_header_last_) { bottom_header_idx_ = 1; } else { bottom_header_idx_++; } if (bottom_header_idx_ == 3) { bottom_header_idx_ = 0; ui.moduleView->header()->setSortIndicator(-1, Qt::AscendingOrder); } } onProcSelection(DWordToDecQ(cur_pid_)); } void ProcessMgr::onProcDoubleClicked( const QModelIndex &idx ) { onShowProperties(); } void ProcessMgr::onProcChanged(const QModelIndex &current, const QModelIndex &previous) { if (current.isValid()) { //auto row = current.row(); cur_pid_ = current.sibling(current.row(), PS.pid).data().toUInt(); } onShowBottom(bottom_idx_); } void ProcessMgr::onProcSelection(QString pid) { auto view = ui.processView; std::function<bool(QModelIndex idx)> LocateProcess = [&](QModelIndex idx)->bool { int rows = proc_model_->rowCount(idx); for (int i = 0; i < rows; i++) { QString qstr; QModelIndex child_name; QStandardItem *item; if (idx == view->rootIndex()) { child_name = proc_model_->index(i, PS.name); item = proc_model_->itemFromIndex(child_name); qstr = proc_model_->index(i, PS.pid).data(Qt::DisplayRole).toString(); } else { item = proc_model_->itemFromIndex(idx); child_name = item->child(i, PS.name)->index(); qstr = item->child(i, PS.pid)->data(Qt::DisplayRole).toString(); } if (qstr == pid) { auto idx = proxy_proc_->mapFromSource(child_name); view->selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); view->scrollTo(idx); return true; } if (proc_model_->itemFromIndex(child_name)->hasChildren()) { if (LocateProcess(child_name)) { return true; } } } return false; }; LocateProcess(view->rootIndex()); } DWORD ProcessMgr::ProcCurPid() { //auto idx = ui.processView->currentIndex(); //DWORD pid = idx.sibling(idx.row(), PS.pid).data().toUInt(); return cur_pid_; } int ProcessMgr::ProcCurRow() { auto idx = ui.processView->currentIndex(); return idx.row(); } int ProcessMgr::ProcCurCol() { auto idx = ui.processView->currentIndex(); return idx.column(); } QString ProcessMgr::ProcCurViewItemData(int column) { return GetCurItemViewData(ui.processView, column); } QString ProcessMgr::ProcViewItemData(int row, int column) { return GetItemViewData(ui.processView, row, column); } QString ProcessMgr::BottomCurViewItemData(int column) { return GetCurItemViewData(ui.moduleView, column); } QString ProcessMgr::ModViewItemData(int row, int column) { return GetItemViewData(ui.moduleView, row, column); } void ProcessMgr::InitProcessView() { //process list auto copy_menu_ = new QMenu(); copy_menu_->addAction(tr("Process Name"))->setData(PS.name); copy_menu_->addAction(tr("Process ID"))->setData(PS.pid); copy_menu_->addAction(tr("Parent ID"))->setData(PS.ppid); copy_menu_->addAction(tr("Process Path"))->setData(PS.path); copy_menu_->addAction(tr("Created Time"))->setData(PS.ctime); copy_menu_->setTitle(tr("Copy")); connect(copy_menu_, SIGNAL(triggered(QAction*)), SLOT(onCopyActionTriggerd(QAction*))); auto dump_menu_ = new QMenu(); dump_menu_->addAction(tr("Create Minidump..."), this, SLOT(onCreateMiniDump())); dump_menu_->addAction(tr("Create Fulldump..."), this, SLOT(onCreateFullDump())); dump_menu_->setTitle(tr("Create Dump")); proc_menu_ = new QMenu(); proc_menu_->addAction(tr("Refresh"), this, SLOT(onRefresh()), QKeySequence::Refresh); proc_menu_->addAction(copy_menu_->menuAction()); proc_menu_->addAction(tr("Kill Process"), this, SLOT(onKillProcess()), QKeySequence::Delete); proc_menu_->addAction(tr("Kill Process Tree"), this, SLOT(onKillProcessTree()), QKeySequence("SHIFT+Delete")); proc_menu_->addAction(tr("Restart Process"), this, SLOT(onRestartProcess())); //proc_menu_->addAction(tr("Suspend"), this, SLOT(onSuspendProcess())); proc_menu_->addAction(tr("Select PID"), this, SLOT(onSelectPid()), QKeySequence("CTRL+G")); proc_menu_->addAction(tr("Explore File"), this, SLOT(onExploreFile()), QKeySequence("CTRL+L")); proc_menu_->addAction(tr("Enum Thread"), this, SLOT(onEnumThread())); proc_menu_->addAction(tr("Enum Window"), this, SLOT(onEnumWindow())); proc_menu_->addAction(tr("Inject Dll"), this, SLOT(onInjectDll()), QKeySequence("CTRL+J")); proc_menu_->addAction(tr("Sendto Scanner"), this, SLOT(onSendtoScanner())); proc_menu_->addAction(dump_menu_->menuAction()); proc_menu_->addAction(tr("Properties..."), this, SLOT(onShowProperties()), QKeySequence("CTRL+P")); proc_model_ = new QStandardItemModel; proc_model_->setHorizontalHeaderLabels(QStringList() << tr("Process") << tr("PID") << tr("PPID") << tr("Path") << tr("Description") << tr("Company Name") << tr("CreatedTime")); QTreeView *pview = ui.processView; proxy_proc_ = new ProcSortFilterProxyModel(pview); proxy_proc_->setSourceModel(proc_model_); proxy_proc_->setDynamicSortFilter(true); proxy_proc_->setFilterKeyColumn(1); pview->setModel(proxy_proc_); pview->selectionModel()->setModel(proxy_proc_); pview->header()->setSortIndicator(-1, Qt::AscendingOrder); pview->setSortingEnabled(true); pview->viewport()->installEventFilter(this); pview->installEventFilter(this); pview->setMouseTracking(true); pview->setEditTriggers(QAbstractItemView::NoEditTriggers); pview->setExpandsOnDoubleClick(false); pview->setColumnWidth(PS.name, 250); pview->setColumnWidth(PS.path, 400); pview->setColumnWidth(PS.desc, 190); pview->setColumnWidth(PS.corp, 155); connect(pview->header(), SIGNAL(sectionClicked(int)), this, SLOT(onSectionClicked(int))); connect(pview, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(onProcDoubleClicked(const QModelIndex&))); connect(pview->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &ProcessMgr::onProcChanged); } void ProcessMgr::InitBottomCommon() { bottom_model_ = new QStandardItemModel; QTreeView *view = ui.moduleView; proxy_bottom_ = new ModSortFilterProxyModel(view); proxy_bottom_->setSourceModel(bottom_model_); proxy_bottom_->setDynamicSortFilter(true); proxy_bottom_->setFilterKeyColumn(1); view->setModel(proxy_bottom_); view->selectionModel()->setModel(proxy_bottom_); view->header()->setSortIndicator(-1, Qt::AscendingOrder); view->setSortingEnabled(true); view->viewport()->installEventFilter(this); view->installEventFilter(this); view->hide(); connect(view->header(), SIGNAL(sectionClicked(int)), this, SLOT(onSectionClicked(int))); } void ProcessMgr::InitModuleView() { if (!mod_menu_) { mod_menu_ = new QMenu(); mod_menu_->addAction(tr("Refresh"), this, SLOT(onRefresh())); mod_menu_->addAction(tr("Explore File"), this, SLOT(onExploreFile())); mod_menu_->addAction(tr("Sendto Scanner"), this, SLOT(onSendtoScanner())); mod_menu_->addAction(tr("Verify Signature"), this, SLOT(onVerifySignature())); mod_menu_->addAction(tr("Verify All Signature"), this, SLOT(onVerifyAllSignature())); mod_menu_->addAction(tr("Properties..."), this, [&]() {WinShowProperties(BottomCurViewItemData(MOD.path).toStdWString()); }); } else { bottom_model_->clear(); bottom_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Base") << tr("Size") << tr("Path") << tr("Description") << tr("Version") << tr("Company Name")<<tr("Signature")); auto bview = ui.moduleView; bview->header()->setSortIndicator(-1, Qt::AscendingOrder); } } void ProcessMgr::InitHandleView() { if (!hd_menu_) { hd_menu_ = new QMenu(); hd_menu_->addAction(tr("Close Handle"), this, SLOT(onCloseHandle())); hd_menu_->addAction(ui.actionHideUnnamed); connect(ui.actionHideUnnamed, SIGNAL(triggered(bool)), this, SLOT(onHideUnnamedHandles(bool))); } else { bottom_model_->clear(); bottom_model_->setHorizontalHeaderLabels(QStringList() << tr("Type") << tr("Name") << tr("Value") << tr("Access") << tr("Object Address")); auto bview = ui.moduleView; bview->setColumnWidth(HD.type, 170); bview->setColumnWidth(HD.name, 700); bview->header()->setSortIndicator(-1, Qt::AscendingOrder); } } void ProcessMgr::InitMemoryView() { if (!mem_menu_) { mem_menu_ = new QMenu(); mem_menu_->addAction(ui.actionHideUncommited); mem_menu_->addAction(ui.actionHideNonExecute); mem_menu_->addAction(ui.actionHideImage); mem_menu_->addSeparator(); mem_menu_->addAction(tr("Dump Memory"), this, SLOT(onDumpMemory())); connect(ui.actionHideUncommited, SIGNAL(triggered(bool)), this, SLOT(onHideMemoryItem(bool))); connect(ui.actionHideNonExecute, SIGNAL(triggered(bool)), this, SLOT(onHideMemoryItem(bool))); connect(ui.actionHideImage, SIGNAL(triggered(bool)), this, SLOT(onHideMemoryItem(bool))); } else { bottom_model_->clear(); bottom_model_->setHorizontalHeaderLabels(QStringList() << tr("Address") << tr("Size") << tr("Property") << tr("State") << tr("Type") << tr("Base") << tr("Module")); auto bview = ui.moduleView; bview->setColumnWidth(MEM.addr, 150); bview->setColumnWidth(MEM.property, 180); bview->setColumnWidth(MEM.state, 180); bview->setColumnWidth(MEM.type, 180); bview->setColumnWidth(MEM.base, 150); bview->header()->setSortIndicator(-1, Qt::AscendingOrder); } } void ProcessMgr::ShowProperties(DWORD pid, int tab) { auto properties = new ProcessProperties(this->parent_, pid, tab); properties->setObjectName("ProcessProperties"); properties->raise(); properties->show(); } void ProcessMgr::ShowProcessList() { DISABLE_RECOVER(); std::vector<ProcInfo> pis; UNONE::PsEnumProcess([&pis](PROCESSENTRY32W& entry)->bool { ProcInfo info; auto pid = info.pid = entry.th32ProcessID; auto ppid = info.ppid = entry.th32ParentProcessID; info.name = WCharsToQ(entry.szExeFile); CacheGetProcInfo(pid, info); pis.push_back(info); return true; }); for (const auto& pi : pis) { QStandardItem *name_item = new QStandardItem(pi.name); name_item->setBackground(QColor(240, 240, 240)); AppendProcessItem(nullptr, name_item, pi, proc_model_->rowCount()); } } void ProcessMgr::ShowProcessTree() { DISABLE_RECOVER(); std::function<void(QStandardItem *parent, ProcInfo pi, int seq)> AppendProcessTree = [&](QStandardItem *parent, ProcInfo pi, int seq) { QStandardItem *name_item = new QStandardItem(pi.name); name_item->setBackground(QColor(240, 240, 240)); AppendProcessItem(parent, name_item, pi, seq); QVector<ProcInfo> childs; CacheGetProcChilds(pi.pid, childs); for (size_t i = 0; i < childs.size(); i++) { AppendProcessTree(name_item, childs[i], i); } }; std::vector<ProcInfo> pis; UNONE::PsEnumProcess([&](PROCESSENTRY32W& entry)->bool { ProcInfo info; auto pid = info.pid = entry.th32ProcessID; auto ppid = info.ppid = entry.th32ParentProcessID; info.name = WCharsToQ(entry.szExeFile); CacheGetProcInfo(pid, info); if (ppid == 0 || !info.parent_existed) { pis.push_back(info); } return true; }); for (const auto& pi : pis) { AppendProcessTree(nullptr, pi, proc_model_->rowCount()); } ui.processView->expandAll(); } void ProcessMgr::AppendProcessItem(QStandardItem *parent, QStandardItem *name_item, ProcInfo info, int seq) { name_item->setIcon(LoadIcon(info.path)); QStandardItem *pid_item = new QStandardItem(PidFormat(info.pid)); QStandardItem *ppid_item = new QStandardItem(PidFormat(info.ppid)); QStandardItem *desc_item = new QStandardItem(info.desc); QStandardItem *corp_item = new QStandardItem(info.corp); QStandardItem *ctime_item = new QStandardItem(info.ctime); QStandardItem *path_item = new QStandardItem(info.path); if (parent == nullptr) { proc_model_->setItem(seq, PS.name, name_item); proc_model_->setItem(seq, PS.pid, pid_item); proc_model_->setItem(seq, PS.ppid, ppid_item); proc_model_->setItem(seq, PS.path, path_item); proc_model_->setItem(seq, PS.desc, desc_item); proc_model_->setItem(seq, PS.corp, corp_item); proc_model_->setItem(seq, PS.ctime, ctime_item); return; } parent->appendRow(name_item); parent->setChild(seq, PS.pid, pid_item); parent->setChild(seq, PS.ppid, ppid_item); parent->setChild(seq, PS.path, path_item); parent->setChild(seq, PS.desc, desc_item); parent->setChild(seq, PS.corp, corp_item); parent->setChild(seq, PS.ctime, ctime_item); } void ProcessMgr::AjustProcessStyle() { auto view = ui.processView; view->resizeColumnToContents(1); view->resizeColumnToContents(2); QModelIndex idx = view->indexAt(proc_sel_); view->selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); view->scrollTo(idx); }
36,138
C++
.cpp
1,012
33.179842
191
0.704306
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,161
process-selection.cpp
BlackINT3_OpenArk/src/OpenArk/process-mgr/process-selection.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "../common/common.h" #include "process-selection.h" ProcessSelection::ProcessSelection(QWidget *parent) : parent_((ProcessMgr*)parent) { ui.setupUi(this); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); setAttribute(Qt::WA_ShowModal, true); setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint); setWindowTitle(tr("Select...")); ui.decRadio->setChecked(true); ui.pidEdit->setFocus(); connect(ui.okBtn, SIGNAL(accepted()), this, SLOT(onLocateProcess())); connect(this, SIGNAL(procSelection(QString)), parent_, SLOT(onProcSelection(QString))); connect(ui.pidEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onPidChanged(const QString&))); connect(ui.decRadio, SIGNAL(toggled(bool)), this, SLOT(onToggled(bool))); connect(ui.hexRadio, SIGNAL(toggled(bool)), this, SLOT(onToggled(bool))); } ProcessSelection::~ProcessSelection() { } void ProcessSelection::onLocateProcess() { QString dec = WStrToQ(UNONE::StrFormatW(L"%d", GetInputPid())); emit procSelection(dec); } void ProcessSelection::onPidChanged(const QString &text) { DWORD pid = GetInputPid(); ui.nameEdit->setText(WStrToQ(UNONE::PsGetProcessNameW(pid))); ui.pathEdit->setText(WStrToQ(UNONE::PsGetProcessPathW(pid))); } void ProcessSelection::onToggled(bool checked) { auto sender = qobject_cast<QRadioButton*>(QObject::sender()); if (!sender->isChecked()) return; DWORD pid = 0; if (sender == ui.decRadio) { pid = UNONE::StrToHexA(ui.pidEdit->text().toStdString()); ui.pidEdit->setText(WStrToQ(UNONE::StrFormatW(L"%d", pid))); return; } if (sender == ui.hexRadio) { pid = UNONE::StrToIntegerA(ui.pidEdit->text().toStdString()); ui.pidEdit->setText(WStrToQ(UNONE::StrFormatW(L"%X", pid))); return; } } DWORD ProcessSelection::GetInputPid() { DWORD pid; bool hexed = true; if (ui.decRadio->isChecked()) hexed = false; if (hexed) { pid = UNONE::StrToHexA(ui.pidEdit->text().toStdString()); } else { pid = UNONE::StrToIntegerA(ui.pidEdit->text().toStdString()); } return pid; }
2,905
C++
.cpp
76
36.486842
115
0.708717
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,162
process-properties.cpp
BlackINT3_OpenArk/src/OpenArk/process-mgr/process-properties.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "process-properties.h" #include "../common/common.h" #include "../common/cache/cache.h" ProcessProperties::ProcessProperties(QWidget* parent, DWORD pid, int tab) : pid_(pid) { setAttribute(Qt::WA_ShowModal, true); setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint); ui.setupUi(this); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); CacheGetProcInfo(pid_, pinfo_); QString title = QString(tr("%1:%2 Properties")).arg(pinfo_.name).arg(pid_); setWindowTitle(title); setWindowIcon(LoadIcon(pinfo_.path)); threads_model_ = new QStandardItemModel; wnds_model_ = new QStandardItemModel; threads_model_->setHorizontalHeaderLabels(QStringList() << tr("TID") << tr("KernelTime") << tr("UserTime") << tr("CreateTime")); wnds_model_->setHorizontalHeaderLabels(QStringList() << tr("HWND") << tr("Title") << tr("ClassName") << tr("Visible") << tr("TID") << tr("PID")); SetDefaultTreeViewStyle(ui.threadView, threads_model_); SetDefaultTreeViewStyle(ui.wndsView, wnds_model_); menu_ = new QMenu(); menu_->addAction(tr("Refresh"), this, SLOT(onRefresh())); ui.threadView->installEventFilter(this); ui.wndsView->installEventFilter(this); connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged())); connect(ui.exploreButton, SIGNAL(clicked()), this, SLOT(onExploreFile())); ui.tabWidget->setCurrentIndex(tab); if (tab == 0) ShowImageDetail(); else if (tab == 1) ShowThreads(); else if (tab == 2) ShowWindowList(); this->installEventFilter(this); // timer_.setInterval(2000); // timer_.start(); // connect(&timer_, SIGNAL(timeout()), this, SLOT(onTimer())); } ProcessProperties::~ProcessProperties() { // timer_.stop(); } bool ProcessProperties::eventFilter(QObject *obj, QEvent *e) { if (obj == this) { if (e->type() == QEvent::KeyPress) { QKeyEvent* keyevt = dynamic_cast<QKeyEvent*>(e); if (keyevt->key() == Qt::Key_Escape) { this->close(); return true; } } } else if (obj == ui.threadView || obj == ui.wndsView) { if (e->type() == QEvent::ContextMenu) { QContextMenuEvent* ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt != nullptr) { menu_->move(ctxevt->globalPos()); menu_->show(); } } } return QWidget::eventFilter(obj, e); } void ProcessProperties::onRefresh() { onTabChanged(); } void ProcessProperties::onTimer() { onTabChanged(); } void ProcessProperties::onTabChanged() { auto curidx = ui.tabWidget->currentIndex(); switch (curidx) { case 0: ShowImageDetail(); break; case 1: ShowThreads(); break; case 2: ShowWindowList(); break; } } void ProcessProperties::onExploreFile() { ExploreFile(pinfo_.path); } void ProcessProperties::ShowImageDetail() { ui.pathEdit->setText(pinfo_.path); ui.iconLabel->setPixmap(LoadIcon(pinfo_.path).pixmap(QSize(48, 48))); std::wstring prod_ver, file_ver, descript, copyright; std::wstring path = pinfo_.path.toStdWString(); UNONE::FsGetFileInfoW(path, L"ProductVersion", prod_ver); UNONE::FsGetFileVersionW(path, file_ver); UNONE::FsGetFileInfoW(path, L"FileDescription", descript); UNONE::FsGetFileInfoW(path, L"LegalCopyright", copyright); ui.prodVerLabel->setText(WStrToQ(prod_ver)); ui.fileVerLabel->setText(WStrToQ(file_ver)); ui.descLabel->setText(WStrToQ(descript)); ui.copyrightLabel->setText(WStrToQ(copyright)); ui.bitsLabel->setText(UNONE::PsIsX64(pid_) ? WCharsToQ(L"64-bits") : WCharsToQ(L"32-bits")); auto image = UNONE::PeMapImageByPathW(path); if (image) { std::string cptime; auto stamp = UNONE::PeGetTimeStamp(image); if (stamp) cptime = UNONE::TmFormatUnixTimeA(stamp, "Y-M-D H:W:S"); ui.buildLabel->setText(StrToQ(cptime)); UNONE::PeUnmapImage(image); } auto info = CacheGetProcessBaseInfo(pid_); ui.cmdlineEdit->setText(WStrToQ(info.CommandLine)); ui.curdirEdit->setText(WStrToQ(info.CurrentDirectory)); ui.parentLabel->setText(WStrToQ(UNONE::StrFormatW(L"%s(%d)", QToWChars(pinfo_.name), pinfo_.ppid)));; ui.userLabel->setText(WStrToQ(UNONE::OsHostNameW() + L"\\" + UNONE::OsUserNameW())); ui.startLabel->setText(WStrToQ(ProcessCreateTime(pid_))); } void ProcessProperties::ShowThreads() { ClearItemModelData(threads_model_); std::vector<DWORD> tids; UNONE::PsGetAllThread(pid_, tids); for (auto tid : tids) { auto tid_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%04X(%d)", tid, tid))); std::wstring ct, kt, ut; RetrieveThreadTimes(tid, ct, kt, ut); auto ct_item = new QStandardItem(WStrToQ(ct)); auto kt_item = new QStandardItem(WStrToQ(kt)); auto ut_item = new QStandardItem(WStrToQ(ut)); auto count = threads_model_->rowCount(); threads_model_->setItem(count, 0, tid_item); threads_model_->setItem(count, 1, kt_item); threads_model_->setItem(count, 2, ut_item); threads_model_->setItem(count, 3, ct_item); } QString qstr = WStrToQ(UNONE::StrFormatW(L"%d", tids.size())); ui.threadCountLabel->setText(qstr); } void ProcessProperties::ShowWindowList() { ClearItemModelData(wnds_model_); std::vector<HWND> wnds; wnds = UNONE::PsGetWnds(pid_); for (auto wnd : wnds) { DWORD tid, pid; tid = GetWindowThreadProcessId(wnd, &pid); auto hwnd_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%08X", wnd))); auto title_item = new QStandardItem(WStrToQ(UNONE::PsGetWndTextW(wnd))); auto class_item = new QStandardItem(WStrToQ(UNONE::PsGetWndClassNameW(wnd))); auto visible_item = new QStandardItem(WStrToQ(IsWindowVisible(wnd) ? L"+":L"-")); auto tid_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%04X(%d)", tid, tid))); auto pid_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%04X(%d)", pid, pid))); auto count = wnds_model_->rowCount(); wnds_model_->setItem(count, 0, hwnd_item); wnds_model_->setItem(count, 1, title_item); wnds_model_->setItem(count, 2, class_item); wnds_model_->setItem(count, 3, visible_item); wnds_model_->setItem(count, 4, tid_item); wnds_model_->setItem(count, 5, pid_item); } }
6,820
C++
.cpp
175
36.811429
146
0.70976
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,163
reverse.cpp
BlackINT3_OpenArk/src/OpenArk/reverse/reverse.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "reverse.h" #include "../common/common.h" #include "../common/utils/compress/zip_utils.h" #include "../openark/openark.h" using namespace Plugin::Compressor; enum { RUN_EXE, RUN_EXE_HIDE, RUN_EXE_BY_CMD, RUN_DIR, RUN_CMD_DIR, RUN_OPEN_URL, }; WINTOOL_ITEM WinAllTools[] = { { RUN_EXE, "procexp", "procexp/procexp.exe", "procexp.zip" }, { RUN_EXE, "procmon", "Procmon/Procmon.exe", "Procmon.zip" }, { RUN_EXE, "pchunter32", "PCHunter/PCHunter32.exe", "PCHunter32.zip" }, { RUN_EXE, "pchunter64", "PCHunter/PCHunter64.exe", "PCHunter64.zip" }, { RUN_EXE, "winobj", "Winobj/Winobj.exe", "Winobj.zip" }, { RUN_EXE, "dbgview", "Dbgview/Dbgview.exe", "Dbgview.zip" }, { RUN_EXE, "apimonitor32", "API Monitor/apimonitor-x86.exe", "API Monitor.zip" }, { RUN_EXE, "apimonitor64", "API Monitor/apimonitor-x64.exe", "API Monitor.zip" }, { RUN_CMD_DIR, "sysinternals", "SysinternalsSuite/", "SysinternalsSuite.zip" }, { RUN_EXE, "nirsoft", "nirsoft_package/NirLauncher.exe", "nirsoft_package.zip" }, { RUN_EXE, "windbg32", "Windbg/x86/windbg.exe", "Windbg32.zip" }, { RUN_EXE, "windbg64", "Windbg/x64/windbg.exe", "Windbg64.zip" }, { RUN_EXE, "x64dbg32", "x64dbg/x32/x32dbg.exe", "x64dbg.zip" }, { RUN_EXE, "x64dbg64", "x64dbg/x64/x64dbg.exe", "x64dbg.zip" }, { RUN_EXE, "ida32", "IDA/ida.exe", "IDA.zip" }, { RUN_EXE, "ida64", "IDA/ida64.exe", "IDA.zip" }, { RUN_EXE, "ollydbg", "OllyDBG/OllyDBG.exe", "OllyDBG.zip" }, { RUN_EXE, "ollyice", "OllyICE/OllyICE.exe", "OllyICE.zip" }, { RUN_EXE, "od52pj", "OD 52pj/OD.exe", "OD 52pj.zip" }, { RUN_EXE, "exeinfope", "ExeinfoPe/exeinfope.exe", "ExeinfoPe.zip" }, { RUN_EXE, "reshacker", "ResourceHacker/ResourceHacker.exe", "ResourceHacker.zip" }, { RUN_EXE, "cffexplorer", "CFF Explorer/CFF Explorer.exe", "CFF Explorer.zip" }, { RUN_EXE, "cheatengine", "Cheat Engine/Cheat Engine.exe", "Cheat Engine.zip" }, { RUN_EXE, "peid", "PEID/PEID.exe", "PEID.zip" }, { RUN_EXE, "hcd", "HCD/HCD.exe", "HCD.zip" }, { RUN_CMD_DIR, "radare", "radare2/bin/", "radare2.zip" }, { RUN_EXE, "notepadxx", "Notepad++/notepad++.exe", "Notepadxx.zip" }, { RUN_EXE, "editor010", "010Editor/010Editor.exe", "010Editor.zip" }, { RUN_EXE, "winhex", "Winhex/winhex.exe", "Winhex.zip" }, { RUN_EXE, "hxd", "HxD/HxD.exe", "HxD.zip" }, { RUN_EXE, "winspy", "WinSpy/WinSpy.exe", "WinSpy.zip" }, { RUN_EXE, "spyxx32", "Spy++/spyxx.exe", "Spyxx32.zip" }, { RUN_EXE, "spyxx64", "Spy++/spyxx_amd64.exe", "Spyxx64.zip" }, { RUN_EXE, "fiddler2", "Fiddler2/Fiddler.exe", "Fiddler2.zip" }, { RUN_EXE, "fiddler4", "Fiddler4/Fiddler.exe", "Fiddler4.zip" }, { RUN_EXE, "wiresharkv1", "Wireshark/Wireshark-win32-1.10.14.exe", "Wireshark-v1.zip" }, { RUN_EXE, "wiresharkv3", "Wireshark/Wireshark-win32-3.2.3.exe", "Wireshark-v3.zip" }, { RUN_EXE, "everything", "Everything/Everything.exe", "Everything.zip" }, { RUN_EXE, "teamviewer", "misc/remote/Teamviewer.exe", "misc/remote/Teamviewer.exe" }, { RUN_EXE, "anydesk", "misc/remote/AnyDesk.exe", "misc/remote/AnyDesk.exe" }, { RUN_EXE, "sunlogin", "misc/remote/SunloginClient.exe", "misc/remote/SunloginClient.exe" }, //2020.09.02 add { RUN_EXE, "pchunternew32", "PCHunterNew/PCHunter32.exe", "PCHunterNew32.zip" }, { RUN_EXE, "pchunternew64", "PCHunterNew/PCHunter64.exe", "PCHunterNew64.zip" }, { RUN_EXE, "wke32", "WKE32.exe", "WKE32.exe" }, { RUN_EXE, "wke64", "WKE64.exe", "WKE64.exe" }, { RUN_EXE, "ghidra", "Ghidra/ghidraRun.bat", "Ghidra.zip" }, { RUN_EXE, "keygener", "Keygener.exe", "Keygener.exe" }, { RUN_EXE, "pygtools", "PYGTools/PYG_TOOLS_VER5.exe", "PYGTools.zip" }, { RUN_EXE, "poolmonx", "PoolMonX/PoolMonX.exe", "PoolMonX.zip" }, { RUN_EXE_BY_CMD, "diskgenius", "DiskGenius/DiskGenius.exe", "DiskGenius.zip" }, //cannot shell open diskgenius directly, WTF { RUN_EXE, "window", "Window.exe", "Window.exe" }, { RUN_CMD_DIR, "curl", "network/curl/", "network/curl.zip" }, { RUN_EXE, "nmap", "network/nmap-setup.exe", "network/nmap-setup.exe" }, { RUN_EXE, "charles", "charles-win64.msi", "charles-win64.msi" }, { RUN_CMD_DIR, "tcpdump", "network/tcpdump/", "network/tcpdump.zip" }, { RUN_EXE, "x7z", "compressor/7z.exe", "compressor/7z.exe" }, { RUN_EXE, "winrar", "compressor/winrar.exe", "compressor/winrar.exe" }, { RUN_EXE, "chrome49", "browser/ChromeStandalone49.exe", "browser/ChromeStandalone49.exe" }, { RUN_EXE, "chrome85", "browser/ChromeStandalone85.exe", "browser/ChromeStandalone85.exe" }, { RUN_EXE, "firefox", "browser/FirefoxSetup.exe", "browser/FirefoxSetup.exe" }, { RUN_EXE, "cpuz", "cpuz/cpuz_x32.exe", "cpuz.zip" }, { RUN_EXE, "aida64", "aida64/aida64.exe", "aida64.zip" }, //2021.11.01 add { RUN_EXE, "dnspy", "reverse/dnSpy/dnSpy.exe", "reverse/dnSpy.zip" }, { RUN_EXE, "die", "reverse/die_win32_portable/die.exe", "reverse/die_win32.zip" }, { RUN_EXE, "pebear", "reverse/PE-bear/PE-bear.exe", "reverse/PE-bear.zip" }, { RUN_EXE, "instdrv", "reverse/InstDrv.exe", "reverse/InstDrv.exe" }, { RUN_EXE, "pdbripper", "reverse/pdbripper/pdbripper.exe", "reverse/pdbripper.zip" }, { RUN_EXE, "instdrv", "reverse/InstDrv.exe", "reverse/InstDrv.exe" }, { RUN_EXE, "loadtest", "reverse/LoadTest.exe", "reverse/LoadTest.exe" }, { RUN_EXE, "notepad2", "misc/Notepad2.exe", "misc/Notepad2.exe" }, { RUN_EXE, "vscode", "misc/VSCodeSetup.exe", "misc/VSCodeSetup.exe" }, { RUN_EXE, "calc", "reverse/Calc.exe", "reverse/Calc.exe" }, { RUN_EXE, "calcfpu", "reverse/CalcFPU.exe", "reverse/CalcFPU.exe" }, { RUN_EXE, "wiztree", "misc/WizTree.exe", "misc/WizTree.zip" }, { RUN_EXE, "rapidee", "misc/rapidee.exe", "misc/rapidee.zip" }, { RUN_EXE, "as_ssd", "misc/AS_SSD/AS_SSD.exe", "misc/AS_SSD.zip" }, { RUN_EXE, "hddog", "misc/HDDog.exe", "misc/HDDog.exe" }, //Linux { RUN_EXE, "cygwin64", "linux/cygwin64/Cygwin.bat", "linux/cygwin64.zip" }, { RUN_EXE, "mobaxterm", "linux/MobaXterm/MobaXterm.exe", "linux/MobaXterm.zip" }, { RUN_EXE, "putty", "linux/putty.exe", "linux/putty.zip" }, { RUN_CMD_DIR, "ssh_win", "linux/ssh-win/", "linux/ssh-win.zip" }, { RUN_EXE, "robo3t", "linux/robo3t-x86_64.exe", "linux/robo3t-x86_64.exe" }, { RUN_EXE, "redistool", "linux/redis-desktop-manager.exe", "linux/redis-desktop-manager.exe" }, { RUN_EXE, "sqlitestudio", "linux/SQLiteStudio/SQLiteStudio.exe", "linux/sqlitestudio.zip" }, //Android { RUN_CMD_DIR, "adb", "android/adb/", "android/adb.zip" }, { RUN_CMD_DIR, "aapt", "android/adb/", "android/adb.zip" }, { RUN_EXE, "jadx", "android/jadx.exe", "android/jadx.exe" }, { RUN_EXE, "jeb", "android/jeb/bin/jeb.exe", "android/jeb.zip" }, { RUN_EXE, "gda", "android/GDA.exe", "android/GDA.exe" }, { RUN_EXE, "jd_gui", "android/jd-gui.exe", "android/jd-gui.exe" }, { RUN_EXE_BY_CMD, "scrcpy", "android/scrcpy-win64/scrcpy.exe", "android/scrcpy-win64.zip" }, { RUN_EXE, "xelfviewer", "android/xelfviewer/xelfviewer.exe", "android/xelfviewer.zip" }, { RUN_EXE, "uleb128", "android/ULEB128.exe", "android/ULEB128.exe" }, { RUN_EXE, "apkstudio", "android/ApkStudio-x64/ApkStudio.exe", "android/ApkStudio-x64.zip" }, { RUN_EXE, "androidkiller", "android/AndroidKiller/AndroidKiller.exe", "android/AndroidKiller.zip" }, { RUN_EXE, "jdk8", "android/jdk8.exe", "android/jdk8.exe" }, //WinDevKits { RUN_OPEN_URL, "jdk", "https://mirrors.huaweicloud.com/java/jdk/", "" }, { RUN_EXE, "jdk11", "android/jdk11.exe", "android/jdk11.exe" }, { RUN_OPEN_URL, "python", "https://www.python.org/downloads/", "" }, { RUN_OPEN_URL, "golang", "https://studygolang.com/dl", "" }, { RUN_OPEN_URL, "visualstudio", "https://visualstudio.microsoft.com/downloads/", "" }, { RUN_OPEN_URL, "androidstudio", "https://developer.android.google.cn/studio/", "" }, { RUN_EXE, "git32", "dev/Git-32bit.exe", "dev/Git-32bit.exe" }, { RUN_EXE, "torgit32", "dev/TortoiseGit-32bit.msi", "dev/TortoiseGit-32bit.msi" }, { RUN_EXE, "torsvn32", "dev/TortoiseSVN-32bit.msi", "dev/TortoiseSVN-32bit.msi" }, { RUN_EXE, "git64", "dev/Git-64bit.exe", "dev/Git-64bit.exe" }, { RUN_EXE, "torgit64", "dev/TortoiseGit-64bit.msi", "dev/TortoiseGit-64bit.msi" }, { RUN_EXE, "torsvn64", "dev/TortoiseSVN-64bit.msi", "dev/TortoiseSVN-64bit.msi" }, { RUN_EXE, "vc2005x64", "dev/vcredist_2005_x64", "" }, { RUN_EXE, "vc2005x86", "dev/vcredist/vcredist_2005_x86.exe", "dev/vcredist/vcredist_2005_x86.exe" }, { RUN_EXE, "vc2008x64", "dev/vcredist/vcredist_2008_x64.exe", "dev/vcredist/vcredist_2008_x64.exe" }, { RUN_EXE, "vc2008x86", "dev/vcredist/vcredist_2008_x86.exe", "dev/vcredist/vcredist_2008_x86.exe" }, { RUN_EXE, "vc2010x64", "dev/vcredist/vcredist_2010_x64.exe", "dev/vcredist/vcredist_2010_x64.exe" }, { RUN_EXE, "vc2010x86", "dev/vcredist/vcredist_2010_x86.exe", "dev/vcredist/vcredist_2010_x86.exe" }, { RUN_EXE, "vc2012x64", "dev/vcredist/vcredist_2012_x64.exe", "dev/vcredist/vcredist_2012_x64.exe" }, { RUN_EXE, "vc2012x86", "dev/vcredist/vcredist_2012_x86.exe", "dev/vcredist/vcredist_2012_x86.exe" }, { RUN_EXE, "vc2013x64", "dev/vcredist/vcredist_2013_x64.exe", "dev/vcredist/vcredist_2013_x64.exe" }, { RUN_EXE, "vc2013x86", "dev/vcredist/vcredist_2013_x86.exe", "dev/vcredist/vcredist_2013_x86.exe" }, { RUN_EXE, "vc2015x64", "dev/vcredist/vcredist_2015_x64.exe", "dev/vcredist/vcredist_2015_x64.exe" }, { RUN_EXE, "vc2015x86", "dev/vcredist/vcredist_2015_x86.exe", "dev/vcredist/vcredist_2015_x86.exe" }, { RUN_EXE, "vc1519x64", "dev/vcredist/vcredist_2015~2019_x64.exe", "dev/vcredist/vcredist_2015~2019_x64.exe" }, { RUN_EXE, "vc1519x86", "dev/vcredist/vcredist_2015~2019_x86.exe", "dev/vcredist/vcredist_2015~2019_x86.exe" }, { RUN_EXE, "dotnet4", "dev/dotnet/dotNetFx40_Full_x86_x64.exe", "dev/dotnet/dotNetFx40_Full_x86_x64.exe" }, }; Reverse::Reverse(QWidget *parent, int tabid) : CommonMainTabObject::CommonMainTabObject((OpenArk*)parent) { ui.setupUi(this); ui.progressBar->setValue(0); ui.progressBar->show(); InitWindowsView(); InitLinuxView(); InitAndroidView(); InitDevKitsView(); CommonMainTabObject::Init(ui.tabWidget, tabid); } Reverse::~Reverse() { } void Reverse::onTabChanged(int index) { CommonMainTabObject::onTabChanged(index); } void Reverse::onExecute() { QString name; static auto is64 = UNONE::OsIs64(); auto sender = QObject::sender(); name = sender->objectName().replace("Btn", ""); if (sender == ui.pchunterBtn) name = is64 ? "pchunter64" : "pchunter32"; if (sender == ui.pchunternewBtn) name = is64 ? "pchunternew64" : "pchunternew32"; if (sender == ui.wkeBtn) name = is64 ? "wke64" : "wke32"; if (sender == ui.gitBtn) name = is64 ? "git64" : "git32"; if (sender == ui.torgitBtn) name = is64 ? "torgit64" : "torgit32"; if (sender == ui.torsvnBtn) name = is64 ? "torsvn64" : "torsvn32"; WINTOOL_ITEM wintool; for (int i = 0; i < _countof(WinAllTools); i++) { if (WinAllTools[i].name == name) { wintool = WinAllTools[i]; break; } } DownloadAndExecuteFile(wintool); } void Reverse::DownloadAndExecuteFile(WINTOOL_ITEM wintool) { int type; QString uri, exec; uri = wintool.uri; exec = wintool.exec; type = wintool.type; if (type == RUN_OPEN_URL) { ShellOpenUrl(exec); return; } auto &&filebase = WStrToQ(AppConfigDir() + L"/files/"); if (!UNONE::FsIsExistedW(filebase.toStdWString())) { UNONE::FsCreateDirW(filebase.toStdWString()); } auto &&path = filebase + uri; auto &&url = AppFsUrl() + "/" + uri; exec = filebase + exec; auto Run = [&](int type, QString exe)->bool { if (UNONE::FsIsExistedW(QToWStr(exe))) { if (type == RUN_EXE) ShellRun(exe, ""); if (type == RUN_EXE_HIDE) ShellRunCmdExe(exe, SW_HIDE); else if (type == RUN_CMD_DIR) ShellRunCmdDir(exe); else if (type == RUN_DIR) ExploreFile(exe); else if (type == RUN_EXE_BY_CMD) ShellRunCmdExe(exe, SW_HIDE); return true; } return false; }; static bool pending = false; if (Run(type, exec)) return; if (pending) { QMessageBox::critical(NULL, tr("Error"), tr("Download pending, wait for a while...")); return; } pending = true; UNONE::FsCreateDirW(UNONE::FsPathToDirW(QToWStr(path))); file = new QFile(path); file->open(QIODevice::WriteOnly); QNetworkAccessManager *accessmgr = new QNetworkAccessManager(this); accessmgr->setNetworkAccessible(QNetworkAccessManager::Accessible); QUrl qurl(url); QNetworkRequest request(qurl); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream"); reply = accessmgr->get(request); connect((QObject *)reply, SIGNAL(readyRead()), this, SLOT(readContent())); connect(accessmgr, &QNetworkAccessManager::finished, [&, Run, type, path, exec](QNetworkReply*) { if (reply->error() != QNetworkReply::NoError) { QMessageBox::critical(NULL, tr("Error"), tr("Download failed, err:%1").arg(reply->error())); ui.progressBar->setValue(0); ui.progressBar->setMaximum(100); file->close(); DeleteFileW(QToWStr(path).c_str()); pending = false; return; } reply->deleteLater(); file->flush(); file->close(); auto filepath = path.toStdString(); if (UNONE::FsPathToExtensionA(filepath) == ".zip") { //Unpack auto dir = UNONE::FsPathToDirA(filepath); ZipUtils::UnpackToDir(filepath, ZipUtils::UNPACK_CURRENT, dir); //Clean DeleteFileA(filepath.c_str()); } //Run Run(type, exec); pending = false; }); connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onProgress(qint64, qint64))); } void Reverse::readContent() { file->write(reply->readAll()); } void Reverse::onProgress(qint64 bytesSent, qint64 bytesTotal) { ui.progressBar->setMaximum(bytesTotal); ui.progressBar->setValue(bytesSent); } void Reverse::InitWindowsView() { QList<QPushButton*> buttons = ui.windowsBox->findChildren<QPushButton*>(); for (auto &btn : buttons) { connect(btn, SIGNAL(clicked()), this, SLOT(onExecute())); } connect(ui.toolsfolderBtn, &QPushButton::clicked, [] { auto folder = AppConfigDir() + L"\\files"; ShellRun(WStrToQ(folder), ""); }); } void Reverse::InitLinuxView() { QList<QPushButton*> buttons = ui.linuxBox->findChildren<QPushButton*>(); for (auto &btn : buttons) { connect(btn, SIGNAL(clicked()), this, SLOT(onExecute())); } } void Reverse::InitAndroidView() { QList<QPushButton*> buttons = ui.androidBox->findChildren<QPushButton*>(); for (auto &btn : buttons) { connect(btn, SIGNAL(clicked()), this, SLOT(onExecute())); } } void Reverse::InitDevKitsView() { QList<QPushButton*> buttons = ui.devkitsBox->findChildren<QPushButton*>(); for (auto &btn : buttons) { connect(btn, SIGNAL(clicked()), this, SLOT(onExecute())); } }
15,302
C++
.cpp
318
45.896226
126
0.680434
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,164
about.cpp
BlackINT3_OpenArk/src/OpenArk/about/about.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "about.h" #include "../common/common.h" About::About(QWidget* parent) { ui.setupUi(this); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); setAttribute(Qt::WA_ShowModal, true); setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags()& ~(Qt::WindowMaximizeButtonHint| Qt::WindowMinimizeButtonHint)| Qt::MSWindowsFixedSizeDialogHint); connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(close())); } About::~About() { }
1,305
C++
.cpp
29
43.724138
128
0.675824
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,165
utilities.cpp
BlackINT3_OpenArk/src/OpenArk/utilities/utilities.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "utilities.h" #include <common/common.h> #include <openark/openark.h> #include <settings/settings.h> #include <arkdrv-api/arkdrv-api.h> #define MODEL_STRING(model, row, columm) (model->index(row, columm).data(Qt::DisplayRole).toString()) #define RECYCLEBIN "RecycleBin" struct { int s = 0; int dir = s++; int filecnt = s++; int detail = s++; int sumsize = s++; } JUNKS; bool JunksSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); auto column = left.column(); if ((column == JUNKS.filecnt || column == JUNKS.sumsize)) return s1.toUInt() < s2.toUInt(); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } Utilities::Utilities(QWidget *parent, int tabid) : CommonMainTabObject::CommonMainTabObject((OpenArk*)parent), scanjunks_thread_(nullptr), cleanjunks_thread_(nullptr) { ui.setupUi(this); qRegisterMetaType<JunkCluster>("JunkCluster"); InitCleanerView(); InitSystemToolsView(); CommonMainTabObject::Init(ui.tabWidget, tabid); } Utilities::~Utilities() { if (scanjunks_thread_) scanjunks_thread_->terminate(); scanjunks_thread_ = nullptr; } void Utilities::RecordAppServer(const QString &svr) { app_server_ = svr; } void Utilities::onTabChanged(int index) { CommonMainTabObject::onTabChanged(index); } void Utilities::onOpJunkfiles(int op, JunkCluster cluster) { bool existed = false; int rows = junks_model_->rowCount(); int seq = rows; for (int i = 0; i < rows; i++) { if (cluster.dir == MODEL_STRING(junks_model_, i, JUNKS.dir)) { seq = i; existed = true; break; } } auto &items = cluster.items; DWORD64 sumsize = cluster.sumsize; DWORD filecnt = items.size(); if (existed) { if (op == 0) { filecnt += MODEL_STRING(junks_model_, seq, JUNKS.filecnt).toULong(); sumsize += MODEL_STRING(junks_model_, seq, JUNKS.sumsize).toULongLong(); } else { filecnt = MODEL_STRING(junks_model_, seq, JUNKS.filecnt).toULong() - filecnt; sumsize = MODEL_STRING(junks_model_, seq, JUNKS.sumsize).toULongLong() - sumsize; } } QStandardItem *dir_item; if (cluster.dir == RECYCLEBIN) { dir_item = new QStandardItem(QIcon(":/OpenArk/systools/recyclebin.png"), cluster.dir); } else { dir_item = new QStandardItem(LoadIcon(cluster.dir), cluster.dir); } dir_item->setCheckable(true); dir_item->setCheckState(Qt::Checked); QStandardItem *filecnt_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%d", filecnt))); QStandardItem *sumsize_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%lld B", sumsize))); QStandardItem *detail_item; if (sumsize > GB) { detail_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%.2f GB", (double)sumsize / GB))); } else if (sumsize > MB) { detail_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%.2f MB", (double)sumsize / MB))); } else if (sumsize > KB) { detail_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%.2f KB", (double)sumsize/KB))); } else { detail_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%lld Bytes", sumsize))); } junks_model_->setItem(seq, JUNKS.dir, dir_item); junks_model_->setItem(seq, JUNKS.filecnt, filecnt_item); junks_model_->setItem(seq, JUNKS.sumsize, sumsize_item); junks_model_->setItem(seq, JUNKS.detail, detail_item); if (items.size() > 0) { auto path = items.first().path; int maxcnt = 65; int ellipsis = 5; if (path.size() > maxcnt) { int s1 = (maxcnt - ellipsis) / 2; auto p1 = path.mid(0, s1); auto p2 = QString(".").repeated(ellipsis); auto p3 = path.right(s1); path = p1 + p2 + p3; } ui.fileLabel->setText(path); } } void Utilities::onAppendJunkfiles(JunkCluster cluster) { onOpJunkfiles(0, cluster); } void Utilities::onCleanJunkfiles(JunkCluster cluster) { onOpJunkfiles(1, cluster); } void ScanJunksThread::run() { QList<JunkItem> items; auto SendToUI = [&](QString dir, DWORD64 sumsize = 0) { JunkCluster cluster; if (!sumsize) { for (auto &item : items) { sumsize += item.size; } } cluster.dir = dir; cluster.sumsize = sumsize; cluster.items = items; emit appendJunks(cluster); bool existed = false; for (auto &c : junks_cluster_) { if (cluster.dir == c.dir) { c.sumsize = sumsize; c.items.append(items); existed = true; } } if (!existed)junks_cluster_.push_back(cluster); items.clear(); }; std::function<bool(wchar_t*, wchar_t*, void*)> ScanCallback; ScanCallback = [&](wchar_t* path, wchar_t* name, void* param)->bool { if (UNONE::FsIsDirW(path)) { UNONE::FsEnumDirectoryW(path, ScanCallback, param); } JunkItem item; item.name = WCharsToQ(name); item.path = WCharsToQ(path); DWORD64 fsize = 0; UNONE::FsGetFileSizeW(path, fsize); item.size = fsize; items.push_back(item); if (items.size() >= 50) { SendToUI(*(QString*)param); } return true; }; std::function<bool(wchar_t*, wchar_t*, void*)> ScanCallbackCustom; QStringList clear_suffixes_list = custom_suffex_.split(QRegExp("[,;]")); ScanCallbackCustom = [&](wchar_t* path, wchar_t* name, void* param)->bool { if (UNONE::FsIsDirW(path)) { UNONE::FsEnumDirectoryW(path, ScanCallbackCustom, param); } QFileInfo file_info = QFileInfo(WCharsToQ(path)); QString suffix = "." + file_info.suffix(); if (custom_suffex_.isEmpty() || clear_suffixes_list.contains(suffix, Qt::CaseInsensitive)){ JunkItem item; item.name = WCharsToQ(name); item.path = WCharsToQ(path); DWORD64 fsize = 0; UNONE::FsGetFileSizeW(path, fsize); item.size = fsize; items.push_back(item); SendToUI(*(QString*)param); } return true; }; junks_cluster_.clear(); if (is_custom_scan_) { for (int i = 0; i < custom_path_.size(); i++) { SendToUI(custom_path_[i]); UNONE::FsEnumDirectoryW(custom_path_[i].toStdWString(), ScanCallbackCustom, &custom_path_[i]); } } if (is_builtin_scan_) { auto &&junkdirs = OpenArkConfig::Instance()->GetJunkDirs(); for (auto &dir : junkdirs) { if (!UNONE::FsIsExistedW(dir.toStdWString())) continue; UNONE::FsEnumDirectoryW(dir.toStdWString(), ScanCallback, &dir); if (items.size() >= 0) { SendToUI(dir); } } // RecycleBin SHQUERYRBINFO bi; bi.cbSize = sizeof(SHQUERYRBINFO); HRESULT hr = SHQueryRecycleBin(NULL, &bi); if (hr == S_OK) { items.clear(); auto nums = bi.i64NumItems; while (nums--) { JunkItem junk; items.append(junk); } SendToUI(RECYCLEBIN, bi.i64Size); } } } void CleanJunksThread::run() { for (auto &cluster : junks_cluster_) { int cnt = 0; JunkCluster c; c.dir = cluster.dir; c.sumsize = 0; if (cluster.dir == RECYCLEBIN) { auto flags = SHERB_NOCONFIRMATION | SHERB_NOPROGRESSUI | SHERB_NOSOUND; SHEmptyRecycleBin(NULL, NULL, flags); continue; } for (auto &item : cluster.items) { bool ret; auto &&path = item.path.toStdWString(); if (UNONE::FsIsDirW(path)) { ret = UNONE::FsDeleteDirectoryW(path); } else { ret = DeleteFileW(path.c_str()); } c.sumsize += item.size; c.items.append(item); if (c.items.size() > 199) { emit cleanJunks(c); c.sumsize = 0; c.items.clear(); } } if (c.items.size() > 0) { emit cleanJunks(c); c.sumsize = 0; c.items.clear(); } } } void Utilities::InitCleanerView() { junks_model_ = new QStandardItemModel; junks_model_->setHorizontalHeaderLabels(QStringList() << tr("Directory") << tr("FileCount") << tr("Detail") << tr("SumSize")); QTreeView *view = ui.junksView; proxy_junks_ = new JunksSortFilterProxyModel(view); proxy_junks_->setSourceModel(junks_model_); proxy_junks_->setDynamicSortFilter(true); proxy_junks_->setFilterKeyColumn(1); view->setModel(proxy_junks_); view->selectionModel()->setModel(proxy_junks_); view->header()->setSortIndicator(-1, Qt::AscendingOrder); view->setSortingEnabled(true); view->viewport()->installEventFilter(this); view->installEventFilter(this); view->setEditTriggers(QAbstractItemView::NoEditTriggers); view->setColumnWidth(JUNKS.dir, 700); view->setColumnWidth(JUNKS.filecnt, 100); view->setColumnWidth(JUNKS.sumsize, 170); connect(ui.settingBtn, &QPushButton::clicked, this, [&] { auto about = new Settings(this); about->raise(); about->SetActiveTab(TAB_SETTINGS_CLEAN); about->show(); }); connect(ui.scanBtn, &QPushButton::clicked, this, [&] { ClearItemModelData(junks_model_); ui.cleanBtn->setEnabled(false); ui.scanBtn->setEnabled(false); ui.statusLabel->setText(tr("[STATUS] Scanning...")); ui.statusLabel->setStyleSheet("color:purple"); if (!scanjunks_thread_) { scanjunks_thread_ = new ScanJunksThread(); connect(scanjunks_thread_, SIGNAL(appendJunks(JunkCluster)), this, SLOT(onAppendJunkfiles(JunkCluster))); connect(scanjunks_thread_, &QThread::finished, this, [&] { ui.cleanBtn->setEnabled(true); ui.scanBtn->setEnabled(true); ui.statusLabel->setText(tr("[STATUS] Scan completed...")); ui.statusLabel->setStyleSheet("color:green"); }); } scanjunks_thread_->is_custom_scan_ = (ui.customScanCheckBox->checkState() == Qt::Checked); scanjunks_thread_->is_builtin_scan_ = (ui.builtinScanCheckBox->checkState() == Qt::Checked); scanjunks_thread_->custom_path_ = OpenArkConfig::Instance()->GetValue("clean_path_list").toStringList(); scanjunks_thread_->custom_suffex_ = OpenArkConfig::Instance()->GetValue("clean_file_suffix").toString(); scanjunks_thread_->start(QThread::NormalPriority); }); connect(ui.cleanBtn, &QPushButton::clicked, this, [&] { ui.cleanBtn->setEnabled(false); ui.scanBtn->setEnabled(false); ui.statusLabel->setText(tr("[STATUS] Cleaning...")); ui.statusLabel->setStyleSheet("color:purple"); if (!cleanjunks_thread_) { cleanjunks_thread_ = new CleanJunksThread(); connect(cleanjunks_thread_, SIGNAL(cleanJunks(JunkCluster)), this, SLOT(onCleanJunkfiles(JunkCluster))); connect(cleanjunks_thread_, &QThread::finished, this, [&] { ui.cleanBtn->setEnabled(true); ui.scanBtn->setEnabled(true); RemoveCleanerItems(); ui.statusLabel->setText(tr("[STATUS] Clean completed...")); ui.statusLabel->setStyleSheet("color:green"); }); } removed_rows_.clear(); QList<JunkCluster> clusters; int rows = junks_model_->rowCount(); for (int i = 0; i < rows; i++) { auto stat = junks_model_->item(i, JUNKS.dir)->checkState(); if (stat == Qt::Checked) { removed_rows_.push_back(i); for (auto &c : scanjunks_thread_->junks_cluster_) { if (c.dir == MODEL_STRING(junks_model_, i, JUNKS.dir)) { clusters.append(c); break; } } } } cleanjunks_thread_->setJunkCluster(clusters); cleanjunks_thread_->start(QThread::NormalPriority); }); } void Utilities::InitSystemToolsView() { ui.hideBtn0->setVisible(false); ui.hideBtn1->setVisible(false); ui.hideBtn2->setVisible(false); ui.hideBtn3->setVisible(false); connect(ui.cmdBtn, &QPushButton::clicked, [] {ShellRun("cmd.exe", "/k cd /d %userprofile%"); }); connect(ui.wslBtn, &QPushButton::clicked, [] {ShellRun("wsl.exe", ""); }); connect(ui.powershellBtn, &QPushButton::clicked, [] {ShellRun("powershell.exe", ""); }); connect(ui.calcBtn, &QPushButton::clicked, [] {ShellRun("calc.exe", ""); }); connect(ui.regeditBtn, &QPushButton::clicked, [] {ShellRun("regedit.exe", ""); }); connect(ui.servicesBtn, &QPushButton::clicked, [] {ShellRun("services.msc", ""); }); connect(ui.taskmgrBtn, &QPushButton::clicked, [] {ShellRun("taskmgr.exe", ""); }); connect(ui.programsBtn, &QPushButton::clicked, [] {ShellRun("control.exe", "appwiz.cpl"); }); connect(ui.envBtn, &QPushButton::clicked, [] {ShellRun("SystemPropertiesAdvanced.exe", ""); }); connect(ui.pcnameBtn, &QPushButton::clicked, [] {ShellRun("SystemPropertiesComputerName.exe", ""); }); connect(ui.fastrebootBtn, &QPushButton::clicked, [&] { if (QMessageBox::warning(this, tr("Warning"), tr("Are you sure to reboot?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { UNONE::OsFastReboot(); } }); connect(ui.fastpoweroffBtn, &QPushButton::clicked, [&] { if (QMessageBox::warning(this, tr("Warning"), tr("Are you sure to poweroff?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { UNONE::OsFastPoweroff(); } }); connect(ui.resetexplorerBtn, &QPushButton::clicked, [&] { auto pid = OsGetExplorerPid(); auto path = UNONE::OsWinDirW() + L"\\explorer.exe"; if (pid != -1) { PsKillProcess(pid); } UNONE::PsCreateProcessW(path); }); connect(ui.killexplorerBtn, &QPushButton::clicked, [&] { auto pid = OsGetExplorerPid(); PsKillProcess(pid); }); connect(ui.sysinfoBtn, &QPushButton::clicked, [] {ShellRun("cmd.exe", "/c systeminfo |more & pause"); }); connect(ui.datetimeBtn, &QPushButton::clicked, [] {ShellRun("control.exe", "date/time"); }); connect(ui.tasksBtn, &QPushButton::clicked, [] {ShellRun("taskschd.msc", "/s"); }); connect(ui.versionBtn, &QPushButton::clicked, [] {ShellRun("winver.exe", ""); }); connect(ui.deskiconsBtn, &QPushButton::clicked, [] {ShellRun("rundll32.exe", "shell32.dll,Control_RunDLL desk.cpl,,0"); }); connect(ui.wallpaperBtn, &QPushButton::clicked, [] { if (UNONE::OsMajorVer() <= 5) ShellRun("rundll32.exe", "shell32.dll,Control_RunDLL desk.cpl,,0"); else ShellRun("control.exe", "/name Microsoft.Personalization /page pageWallpaper"); }); connect(ui.devmgrBtn, &QPushButton::clicked, [] {ShellRun("devmgmt.msc", ""); }); connect(ui.diskmgrBtn, &QPushButton::clicked, [] {ShellRun("diskmgmt.msc", ""); }); connect(ui.resmonBtn, &QPushButton::clicked, [] {ShellRun("resmon.exe", ""); }); connect(ui.perfBtn, &QPushButton::clicked, [] {ShellRun("perfmon.exe", ""); }); connect(ui.perfsetBtn, &QPushButton::clicked, [] {ShellRun("SystemPropertiesPerformance.exe", ""); }); connect(ui.powerBtn, &QPushButton::clicked, [] {ShellRun("control.exe", "powercfg.cpl,,3"); }); connect(ui.usersBtn, &QPushButton::clicked, [] {ShellRun("lusrmgr.msc", ""); }); connect(ui.uacBtn, &QPushButton::clicked, [] {ShellRun("UserAccountControlSettings.exe", ""); }); connect(ui.evtBtn, &QPushButton::clicked, [] {ShellRun("eventvwr.msc", ""); }); connect(ui.gpoBtn, &QPushButton::clicked, [] {ShellRun("gpedit.msc", ""); }); connect(ui.secpolBtn, &QPushButton::clicked, [] {ShellRun("secpol.msc", ""); }); connect(ui.certBtn, &QPushButton::clicked, [] {ShellRun("certmgr.msc", ""); }); connect(ui.credBtn, &QPushButton::clicked, [] {ShellRun("control.exe", "/name Microsoft.CredentialManager"); }); connect(ui.firewallBtn, &QPushButton::clicked, [] {ShellRun("control.exe", "firewall.cpl"); }); connect(ui.proxyBtn, &QPushButton::clicked, [] {ShellRun("rundll32.exe", "shell32.dll,Control_RunDLL inetcpl.cpl,,4"); }); connect(ui.netconnBtn, &QPushButton::clicked, [] {ShellRun("control.exe", "ncpa.cpl"); }); connect(ui.hostsBtn, &QPushButton::clicked, [&] {ShellRun("notepad.exe", WStrToQ(UNONE::OsSystem32DirW() + L"\\drivers\\etc\\hosts")); }); connect(ui.ipv4Btn, &QPushButton::clicked, [] {ShellRun("cmd.exe", "/k ipconfig|findstr /i ipv4"); }); connect(ui.ipv6Btn, &QPushButton::clicked, [] {ShellRun("cmd.exe", "/k ipconfig|findstr /i ipv6"); }); connect(ui.routeBtn, &QPushButton::clicked, [] {ShellRun("cmd.exe", "/k route print"); }); connect(ui.sharedBtn, &QPushButton::clicked, [] {ShellRun("fsmgmt.msc", ""); }); } void Utilities::RemoveCleanerItems() { int delta = 0; for (auto r : removed_rows_) { junks_model_->removeRows(r - delta, 1); delta++; } removed_rows_.clear(); }
16,290
C++
.cpp
418
36.244019
139
0.689176
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,166
common.cpp
BlackINT3_OpenArk/src/OpenArk/common/common.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "common.h" #include "../openark/openark.h"
848
C++
.cpp
17
48.823529
77
0.628916
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,167
qt-wrapper.cpp
BlackINT3_OpenArk/src/OpenArk/common/qt-wrapper/qt-wrapper.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "qt-wrapper.h" #include "../common/common.h" OpenArk *openark = nullptr; QTranslator *app_tr = nullptr; QApplication *app = nullptr; QSize OpenArkTabStyle::sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const { QSize s = QProxyStyle::sizeFromContents(type, option, size, widget); if (type == QStyle::CT_TabBarTab) { s.transpose(); s.rwidth() = 140; s.rheight() = 30; } return s; } void OpenArkTabStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { if (element == CE_TabBarTabLabel) { const QStyleOptionTab* tabopt = reinterpret_cast<const QStyleOptionTab*>(option); if (tabopt) { QRect rect = tabopt->rect; if (tabopt->state & QStyle::State_Selected) { painter->save(); painter->setPen(0xb9b9b9); painter->setBrush(QBrush(0xffffff)); if (tabopt->position != QStyleOptionTab::End) { painter->drawRect(rect.adjusted(0, 0, 20, 0)); } else { painter->drawRect(rect.adjusted(0, 0, 20, -1)); } painter->restore(); painter->save(); painter->setPen(0x00868b); QTextOption option; option.setAlignment(Qt::AlignCenter); QFont font = QFont("Microsoft YaHei", 11, QFont::Bold); font.setPixelSize(15); painter->setFont(font); painter->drawText(rect, tabopt->text, option); painter->restore(); } else { painter->save(); painter->setPen(0xb9b9b9); painter->setBrush(QBrush(0xf0f0f0)); if (tabopt->position != QStyleOptionTab::End) { painter->drawRect(rect.adjusted(0, 0, 20, 0)); } else { painter->drawRect(rect.adjusted(0, 0, 20, -1)); } painter->restore(); painter->save(); QTextOption option; option.setAlignment(Qt::AlignCenter); QFont font = QFont("Microsoft YaHei", 11); font.setPixelSize(15); painter->setFont(font); painter->drawText(rect, tabopt->text, option); painter->restore(); } return; } } else if (element == CE_TabBarTab) { QProxyStyle::drawControl(element, option, painter, widget); } } OpenArkLanguage* OpenArkLanguage::langobj_ = nullptr; OpenArkLanguage* OpenArkLanguage::Instance() { if (langobj_) return langobj_; langobj_ = new OpenArkLanguage; return langobj_; } void OpenArkLanguage::ChangeLanguage(int lang) { curlang_ = lang; switch (lang) { case -1: if (QLocale::system().language() == QLocale::Chinese) { return ChangeLanguage(1); } else { return ChangeLanguage(0); } break; case 0: if (app_tr) { app->removeTranslator(app_tr); //emit languageChaned(); } break; case 1: if (app_tr) { app_tr->load(":/OpenArk/lang/openark_zh.qm"); app->installTranslator(app_tr); //emit languageChaned(); } default: break; } } QIcon LoadIcon(QString file_path) { static struct { QMutex lck; QMap<QString, QIcon> d; } icon_cache; QMutexLocker locker(&icon_cache.lck); if (icon_cache.d.contains(file_path)) { auto it = icon_cache.d.find(file_path); return it.value(); } QFileInfo file_info(file_path); QFileIconProvider provider; QIcon &ico = provider.icon(file_info); for (auto qs : ico.availableSizes()) { if (!ico.pixmap(qs).isNull()) { icon_cache.d.insert(file_path, ico); return ico; } } ico = QIcon(":/OpenArk/revtools/default.ico"); icon_cache.d.insert(file_path, ico); return ico; } bool IsContainAction(QMenu *menu, QObject *obj) { QAction *action = qobject_cast<QAction*>(obj); for (auto a : menu->actions()) { if (action == a) { return true; } } return false; } bool ExploreFile(QString file_path) { QString cmdline = "explorer.exe /select," + file_path; return UNONE::PsCreateProcessW(cmdline.toStdWString(), SW_SHOW, NULL); } QString GetItemModelData(QAbstractItemModel *model, int row, int column) { return model->data(model->index(row, column)).toString(); //auto idx = model->index(row, column); //return idx.sibling(row, column).data().toString(); } QString GetItemViewData(QAbstractItemView *view, int row, int column) { auto idx = view->rootIndex(); return idx.sibling(row, column).data().toString(); } int GetCurViewRow(QAbstractItemView *view) { return view->currentIndex().row(); } int GetCurViewColumn(QAbstractItemView *view) { return view->currentIndex().column(); } QModelIndex GetCurItemView(QAbstractItemView *view, int column) { auto idx = view->currentIndex(); return idx.sibling(idx.row(), column); } QString GetCurItemViewData(QAbstractItemView *view, int column) { auto idx = view->currentIndex(); return idx.sibling(idx.row(), column).data().toString(); } void SetCurItemViewData(QAbstractItemView *view, int column, QString val) { auto idx = view->currentIndex(); view->model()->setData(idx.sibling(idx.row(), column), val); } void ExpandTreeView(const QModelIndex& index, QTreeView* view) { if (!index.isValid()) { return; } int childCount = index.model()->rowCount(index); for (int i = 0; i < childCount; i++) { const QModelIndex &child = index.child(i, 0); ExpandTreeView(child, view); } if (!view->isExpanded(index)) { view->expand(index); } } void ClearItemModelData(QStandardItemModel* model, int pos) { model->removeRows(pos, model->rowCount()); } QString MsToTime(LONGLONG ms) { return WStrToQ(UNONE::TmFormatMsW(ms, L"Y-M-D H:W:S", NULL)); } void SetDefaultTableViewStyle(QTableView* view, QStandardItemModel* model) { view->setModel(model); view->setSortingEnabled(true); view->verticalHeader()->hide(); view->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); view->horizontalHeader()->setStretchLastSection(true); view->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); view->horizontalHeader()->setMinimumSectionSize(100); view->verticalHeader()->setDefaultSectionSize(25); view->selectionModel()->selectedIndexes(); view->setEditTriggers(false); } void SetDefaultTreeViewStyle(QTreeView* view, QStandardItemModel* model) { view->setModel(model); view->header()->setDefaultAlignment(Qt::AlignLeft); //view->header()->setSectionResizeMode(QHeaderView::ResizeToContents); view->header()->setMinimumSectionSize(100); view->setSortingEnabled(true); } void SetDefaultTreeViewStyle(QTreeView* view, QStandardItemModel* model, QSortFilterProxyModel *proxy, std::vector<std::pair<int, QString>>& layout) { proxy->setSourceModel(model); proxy->setDynamicSortFilter(true); proxy->setFilterKeyColumn(1); view->setModel(proxy); view->selectionModel()->setModel(proxy); view->header()->setSortIndicator(-1, Qt::AscendingOrder); view->header()->setStretchLastSection(false); view->setSortingEnabled(true); view->setEditTriggers(QAbstractItemView::NoEditTriggers); QStringList name_list; for (int i = 0; i < layout.size(); i++) { name_list << layout[i].second; } model->setHorizontalHeaderLabels(name_list); for (int i = 0; i < layout.size(); i++) { if (layout[i].first) view->setColumnWidth(i, layout[i].first); } } int GetLayoutIndex(std::vector<std::pair<int, QString>> &layout, QString name) { for (int i = 0; i < layout.size(); i++) { if (layout[i].second == name) return i; } return 0; } void SetLineBgColor(QStandardItemModel *model, int row, const QBrush &abrush) { for (int i = 0; i < model->columnCount(); i++) { model->item(row, i)->setBackground(abrush); } } void SetLineHidden(QTreeView *view, int row, bool hide) { view->setRowHidden(row, view->rootIndex(), hide); } bool JsonParse(const QByteArray &data, QJsonObject &obj) { QJsonParseError err; QJsonDocument doc; doc = QJsonDocument::fromJson(data, &err); if (err.error != QJsonParseError::NoError) { return false; } if (!doc.isObject()) { return false; } obj = doc.object(); return true; } bool JsonGetValue(const QJsonObject &obj, const QString &key, QJsonValue &val) { if (!obj.contains(key)) { return false; } val = obj[key]; return true; } bool JsonGetValue(const QByteArray &data, const QString &key, QJsonValue &val) { QJsonObject obj; if (!JsonParse(data, obj)) { return false; } if (!JsonGetValue(obj, key, val)) { return false; } return JsonGetValue(obj, key, val); } void ShellOpenUrl(QString url) { ShellExecuteW(NULL, L"open", url.toStdWString().c_str(), NULL, NULL, SW_SHOW); } void ShellRun(QString cmdline, QString param) { ShellExecuteW(NULL, L"open", cmdline.toStdWString().c_str(), param.toStdWString().c_str(), NULL, SW_SHOW); } void ShellRunHide(QString cmdline, QString param) { ShellExecuteW(NULL, L"open", cmdline.toStdWString().c_str(), param.toStdWString().c_str(), NULL, SW_HIDE); } void ShellRunCmdExe(QString exe, int show) { auto cmdline = "cmd /c " + exe; UNONE::PsCreateProcessW(cmdline.toStdWString(), show); } void ShellRunCmdDir(QString dir) { auto cmdline = "cmd /k cd /D" + dir; UNONE::PsCreateProcessW(cmdline.toStdWString()); } QString PidFormat(DWORD pid) { if (pid == -1) return "N/A"; return QString("%1").arg(pid); } QString NameFormat(QString name) { return name.replace(" *32", ""); }
9,810
C++
.cpp
334
27.098802
134
0.714558
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,169
win-wrapper.cpp
BlackINT3_OpenArk/src/OpenArk/common/win-wrapper/win-wrapper.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "win-wrapper.h" #include "../common/common.h" #include <QString> #include <QtCore> #include <arkdrv-api/arkdrv-api.h> #include <shlwapi.h> #pragma comment(lib, "shlwapi.lib") std::wstring FormatFileTime(FILETIME *file_tm) { SYSTEMTIME systm; FileTimeToSystemTime(file_tm, &systm); UNONE::TmConvertZoneTime(systm, NULL); return UNONE::TmFormatSystemTimeW(systm, L"Y-M-D H:W:S"); } std::wstring CalcFileTime(FILETIME *file_tm) { SYSTEMTIME systm; FileTimeToSystemTime(file_tm, &systm); LARGE_INTEGER li; li.HighPart = file_tm->dwHighDateTime; li.LowPart = file_tm->dwLowDateTime; auto val = UNONE::TmFileTimeToMs(*file_tm); int hours = val / (3600 * 1000); int mins = (val % (3600 * 1000)) / (60 * 1000); int secs = (val % (60 * 1000)) / 1000; int mss = (val % (1000)); return UNONE::StrFormatW(L"%d:%02d:%02d.%03d", hours, mins, secs, mss); } bool RetrieveThreadTimes(DWORD tid, std::wstring& ct, std::wstring& kt, std::wstring& ut) { HANDLE thd = ArkDrvApi::Process::OpenThread(THREAD_QUERY_INFORMATION, FALSE, tid); if (!thd) { return false; } FILETIME create_tm; FILETIME exit_tm; FILETIME kern_tm; FILETIME user_tm; if (!GetThreadTimes(thd, &create_tm, &exit_tm, &kern_tm, &user_tm)) { CloseHandle(thd); return false; } CloseHandle(thd); ct = FormatFileTime(&create_tm); kt = CalcFileTime(&kern_tm); ut = CalcFileTime(&user_tm); return true; } std::wstring ProcessCreateTime(__in DWORD pid) { HANDLE Process = ArkDrvApi::Process::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); if (!Process) { return L""; } FILETIME create_tm; FILETIME exit_tm; FILETIME kern_tm; FILETIME user_tm; if (!GetProcessTimes(Process, &create_tm, &exit_tm, &kern_tm, &user_tm)) { CloseHandle(Process); return L""; } CloseHandle(Process); return FormatFileTime(&create_tm); } LONGLONG ProcessCreateTimeValue(__in DWORD pid) { HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); if (!phd) { return 0; } FILETIME create_tm; FILETIME exit_tm; FILETIME kern_tm; FILETIME user_tm; if (!GetProcessTimes(phd, &create_tm, &exit_tm, &kern_tm, &user_tm)) { CloseHandle(phd); return 0; } CloseHandle(phd); return UNONE::TmFileTimeToMs(create_tm); } #include <Dbghelp.h> #pragma comment(lib, "Dbghelp.lib") bool CreateDump(DWORD pid, const std::wstring& path, bool mini) { if (UNONE::PsIsX64(pid) && !UNONE::PsIsX64(GetCurrentProcessId())) { MsgBoxError("Can't dump 64-bit process."); return false; } MINIDUMP_TYPE dmp_type; if (mini) { dmp_type = (MINIDUMP_TYPE)(MiniDumpWithThreadInfo | MiniDumpWithFullMemoryInfo | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithDataSegs); } else { dmp_type = (MINIDUMP_TYPE)(MiniDumpWithThreadInfo | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation | MiniDumpWithProcessThreadData | MiniDumpWithDataSegs | MiniDumpWithFullMemory | MiniDumpWithHandleData); } HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); if (!phd) { return false; } HANDLE fd = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (fd == INVALID_HANDLE_VALUE) { CloseHandle(phd); return false; } BOOL ret = MiniDumpWriteDump(phd, pid, fd, dmp_type, NULL, NULL, NULL); CloseHandle(fd); CloseHandle(phd); if (ret) { MsgBoxInfo(QObject::tr("Create dump ok.")); } else { MsgBoxError(QObject::tr("Create dump failed.")); } return ret == TRUE; } // Clipboard void ClipboardCopyData(const std::string &data) { OpenClipboard(NULL); EmptyClipboard(); HGLOBAL hd = GlobalAlloc(GMEM_MOVEABLE, data.size() + 1); LPWSTR buf = (LPWSTR)GlobalLock(hd); memcpy(buf, data.c_str(), data.size()); GlobalUnlock(hd); EmptyClipboard(); SetClipboardData(CF_TEXT, buf); CloseClipboard(); } BOOL CALLBACK RetrieveWndCallback(HWND wnd, LPARAM param) { DWORD pid; std::vector<HWND> &wnds = *(std::vector<HWND>*)param; wnds.push_back(wnd); return TRUE; } std::vector<HWND> GetSystemWnds() { std::vector<HWND> wnds; EnumChildWindows(GetDesktopWindow(), (WNDENUMPROC)RetrieveWndCallback, (LPARAM)&wnds); return wnds; } int64_t FileTimeToInt64(FILETIME tm) { int64_t high = (int64_t)tm.dwHighDateTime; return high << 32 | tm.dwLowDateTime; } double GetSystemUsageOfCPU() { static int64_t s_idle = 0, s_kernel = 0, s_user = 0; FILETIME tm1, tm2, tm3; GetSystemTimes(&tm1, &tm2, &tm3); auto idle = FileTimeToInt64(tm1) - s_idle; auto kernel = FileTimeToInt64(tm2) - s_kernel; auto user = FileTimeToInt64(tm3) - s_user; s_idle = FileTimeToInt64(tm1); s_kernel = FileTimeToInt64(tm2); s_user = FileTimeToInt64(tm3); return (double)(kernel + user - idle) * 100 / (kernel + user); } double GetSystemUsageOfMemory() { PERFORMANCE_INFORMATION perf = { 0 }; GetPerformanceInfo(&perf, sizeof(perf)); return (1.0 - (double)perf.PhysicalAvailable / perf.PhysicalTotal) * 100; } SIZE_T GetProcessPrivateWorkingSet(DWORD pid) { PROCESS_MEMORY_COUNTERS_EX mm_info; if (!UNONE::MmGetProcessMemoryInfo(pid, mm_info)) return 0; HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); if (!phd) { return 0; } PPSAPI_WORKING_SET_INFORMATION ws; DWORD size = sizeof(PSAPI_WORKING_SET_BLOCK) * 1024 * 1024 * 4; ws = (PPSAPI_WORKING_SET_INFORMATION)new char[size]; mm_info.WorkingSetSize; if (!QueryWorkingSet(phd, ws, size)) { ERR(L"QueryWorkingSet pid:%d, err:%d", pid, GetLastError()); return 0; } SIZE_T shared = 0; for (size_t i = 0; i < ws->NumberOfEntries; i++) { if (ws->WorkingSetInfo[i].Shared) shared += PAGE_SIZE; } delete[] ws; CloseHandle(phd); return shared; } void SetWindowOnTop(HWND wnd, bool ontop) { DWORD style = ::GetWindowLong(wnd, GWL_EXSTYLE); if (ontop) { style |= WS_EX_TOPMOST; ::SetWindowLong(wnd, GWL_EXSTYLE, style); ::SetWindowPos(wnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREPOSITION | SWP_NOSIZE | SWP_SHOWWINDOW); } else { style &= ~WS_EX_TOPMOST; ::SetWindowLong(wnd, GWL_EXSTYLE, style); ::SetWindowPos(wnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREPOSITION | SWP_NOSIZE | SWP_SHOWWINDOW); } } void WinShowProperties(const std::wstring &path) { SHELLEXECUTEINFOW shell; shell.hwnd = NULL; shell.lpVerb = L"properties"; shell.lpFile = path.c_str(); shell.lpDirectory = NULL; shell.lpParameters = NULL; shell.nShow = SW_SHOWNORMAL; shell.fMask = SEE_MASK_INVOKEIDLIST; shell.lpIDList = NULL; shell.cbSize = sizeof(SHELLEXECUTEINFOW); ShellExecuteExW(&shell); } bool GetCertOwner(const QString &path, QString &owner) { std::vector<UNONE::CertInfoW> infos; bool ret = UNONE::SeGetCertInfoW(path.toStdWString(), infos); if (ret) { owner = WStrToQ(infos[0].owner); } return ret; } struct OBJECTNAME_THREAD_DATA { HANDLE hd; HANDLE query_evt; HANDLE alloc_evt; HANDLE start_evt; WCHAR* ObjectName; }; #include <memory> static __NtQueryObject pNtQueryObjectPtr = NULL; DWORD WINAPI ObGetObjectNameThread(LPVOID params) { auto caller = (OBJECTNAME_THREAD_DATA*)params; HANDLE hd = caller->hd; HANDLE query_evt = caller->query_evt; HANDLE alloc_evt = caller->alloc_evt; HANDLE start_evt = caller->start_evt; WCHAR* &obj_name = caller->ObjectName; NTSTATUS status; ULONG bufsize; POBJECT_NAME_INFORMATION buf; SetEvent(start_evt); if (pNtQueryObjectPtr == NULL) { return false; } status = pNtQueryObjectPtr(hd, ObjectNameInformation, NULL, 0, &bufsize); if (status != STATUS_INFO_LENGTH_MISMATCH) { return false; } std::unique_ptr<CHAR> ptr(new(std::nothrow) CHAR[bufsize]); buf = (POBJECT_NAME_INFORMATION)ptr.get(); if (buf == nullptr) { } status = pNtQueryObjectPtr(hd, ObjectNameInformation, buf, bufsize, &bufsize); if (!NT_SUCCESS(status)) { return false; } auto& name_buf = buf->Name.Buffer; auto& name_size = buf->Name.Length; if (name_buf == NULL) { return false; } SetEvent(query_evt); WaitForSingleObject(alloc_evt, INFINITE); obj_name = (WCHAR*)malloc(name_size + 2); memset(obj_name, 0, name_size + 2); if (obj_name != NULL) { memcpy(obj_name, name_buf, name_size); } SetEvent(query_evt); return true; } bool ObGetObjectName(HANDLE hd, std::string& obj_name) { bool ret = false; OBJECTNAME_THREAD_DATA caller; caller.hd = hd; auto& query_evt = caller.query_evt = CreateEventA(NULL, FALSE, FALSE, NULL); if (query_evt == NULL) { return false; } auto& alloc_evt = caller.alloc_evt = CreateEventA(NULL, FALSE, FALSE, NULL); if (alloc_evt == NULL) { CloseHandle(query_evt); return false; } auto& start_evt = caller.start_evt = CreateEventA(NULL, FALSE, FALSE, NULL); if (start_evt == NULL) { CloseHandle(query_evt); CloseHandle(alloc_evt); return false; } auto& temp_name = caller.ObjectName = NULL; DWORD Tid; if (pNtQueryObjectPtr == NULL) { pNtQueryObjectPtr = (__NtQueryObject)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQueryObject"); } HANDLE thd = CreateThread(NULL, 0, ObGetObjectNameThread, &caller, 0, &Tid); if (thd != NULL) { DWORD stat = WaitForSingleObject(start_evt, 5000); if (stat == WAIT_OBJECT_0) { stat = WaitForSingleObject(query_evt, 10); if (stat == WAIT_TIMEOUT) { TerminateThread(thd, ERROR_TIMEOUT); } else { SetEvent(alloc_evt); WaitForSingleObject(query_evt, INFINITE); if (temp_name != NULL) { obj_name = std::move(UNONE::StrToA(temp_name)); free(temp_name); ret = true; } } } CloseHandle(thd); } CloseHandle(start_evt); CloseHandle(query_evt); CloseHandle(alloc_evt); return ret; } bool ExtractResource(const QString &res, const QString &path) { QFile f(res); if (!f.open(QIODevice::ReadOnly)) { return false; } auto &&data = f.readAll().toStdString(); auto &&dst = path.toStdWString(); UNONE::FsCreateDirW(UNONE::FsPathToDirW(dst)); if (!UNONE::FsWriteFileDataW(dst, data)) { return false; } return true; } bool WriteFileDataW(__in const std::wstring& fpath, __in int64_t offset, __in const std::string& fdata) { bool result = false; bool read_only = false; DWORD saved_attr = GetFileAttributesW(fpath.c_str()); if (saved_attr != INVALID_FILE_ATTRIBUTES) { if (saved_attr & FILE_ATTRIBUTE_READONLY) { read_only = true; SetFileAttributesW(fpath.c_str(), saved_attr&(~FILE_ATTRIBUTE_READONLY)); } } HANDLE fd = CreateFileW(fpath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (fd != INVALID_HANDLE_VALUE) { DWORD writelen; LARGE_INTEGER li; li.QuadPart = offset; SetFilePointer(fd, li.LowPart, &li.HighPart, FILE_BEGIN); if (WriteFile(fd, fdata.data(), (DWORD)fdata.size(), &writelen, NULL)) { if (fdata.size() == writelen) { result = true; } else { ERR(L"WriteFile %s err, expected-size:%d actual-size:%d", fpath.c_str(), fdata.size(), writelen); } } else { ERR(L"WriteFile %s err:%d", fpath.c_str(), GetLastError()); } CloseHandle(fd); } else { ERR(L"CreateFileW %s err:%d", fpath.c_str(), GetLastError()); } if (read_only) SetFileAttributesW(fpath.c_str(), saved_attr); return result; } bool ReadFileDataW(__in const std::wstring &fpath, __in int64_t offset, __in int64_t readsize, __out std::string &fdata) { bool result = false; DWORD fsize = 0; HANDLE fd = CreateFileW(fpath.c_str(), GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (fd == INVALID_HANDLE_VALUE) { ERR(L"CreateFileW %s err:%d", fpath.c_str(), GetLastError()); return false; } fsize = GetFileSize(fd, NULL); if (fsize == INVALID_FILE_SIZE) { ERR(L"GetFileSize %s err:%d", fpath.c_str(), GetLastError()); CloseHandle(fd); return false; } if ((offset+readsize) > fsize) { WARN(L"read offset out of bound"); readsize = fsize - offset; } LARGE_INTEGER li; li.QuadPart = offset; SetFilePointer(fd, li.LowPart, &li.HighPart, FILE_BEGIN); char* buff = new(std::nothrow) char[readsize]; if (buff == NULL) { ERR(L"alloc memory err"); CloseHandle(fd); return false; } DWORD readlen; if (ReadFile(fd, buff, readsize, &readlen, NULL)) { if (readlen == readsize) { try { fdata.assign(buff, readsize); result = true; } catch (std::exception& e) { fdata.clear(); ERR("c++ exception: %s", e.what()); } catch (...) { fdata.clear(); ERR("c++ exception: unknown"); } } else { ERR(L"ReadFile %s err, expected-size:%d actual-size:%d", fpath.c_str(), readsize, readlen); } } else { ERR(L"ReadFile %s err:%d", fpath.c_str(), GetLastError()); } delete[] buff; CloseHandle(fd); return result; } bool ReadStdout(const std::wstring& cmdline, std::wstring& output, DWORD& exitcode, DWORD timeout /*= INFINITE*/) { const int blksize = 512; SECURITY_ATTRIBUTES sa; sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; sa.nLength = sizeof(sa); HANDLE rstdin = NULL; HANDLE wstdout = NULL; BOOL ret = CreatePipe(&rstdin, &wstdout, &sa, 64 * 0x1000); if (!ret) { ERR("CreatePipe failed, err:%d", GetLastError()); return false; } STARTUPINFOW si = { 0 }; PROCESS_INFORMATION pi = { 0 }; GetStartupInfoW(&si); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.wShowWindow = SW_HIDE; si.hStdOutput = wstdout; si.hStdError = wstdout; ret = CreateProcessW(NULL, (LPWSTR)cmdline.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi); CloseHandle(wstdout); if (!ret) { CloseHandle(rstdin); ERR(L"CreateProcessW %s failed, err:%d", cmdline.c_str(), GetLastError()); return false; } if (WaitForSingleObject(pi.hProcess, timeout) == WAIT_TIMEOUT) { TerminateProcess(pi.hProcess, 1); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(rstdin); return false; } GetExitCodeProcess(pi.hProcess, &exitcode); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); bool result = false; char *buf = new(std::nothrow) char[blksize]; if (buf == nullptr) { CloseHandle(rstdin); return false; } while (1) { DWORD readlen = 0; if (ReadFile(rstdin, buf, blksize, &readlen, NULL)) { output.append(UNONE::StrToW(std::string(buf, readlen))); if (blksize > readlen) { result = true; break; } } else { if (GetLastError() == ERROR_BROKEN_PIPE) { result = true; break; } } } CloseHandle(rstdin); delete[] buf; return result; } DWORD PsGetPidByWindowW(wchar_t *cls, wchar_t *title) { DWORD pid = INVALID_PID; HWND wnd = FindWindowW(cls, title); if (wnd != NULL) { GetWindowThreadProcessId(wnd, &pid); } return pid; } DWORD OsGetExplorerPid() { return PsGetPidByWindowW(L"Progman", L"Program Manager"); } /*++ Description: load driver registry Arguments: file_path - driver file path srv_name - driver service name Return: bool --*/ bool ObLoadDriverRegistryW(__in const std::wstring &file_path, __in std::wstring srv_name) { HKEY subkey = NULL; do { std::wstring driver_path = UNONE::FsPathStandardW(L"\\??\\" + file_path); DWORD dispos; std::wstring key_name = L"SYSTEM\\CurrentControlSet\\services\\" + srv_name; LONG result = RegCreateKeyExW(HKEY_LOCAL_MACHINE, key_name.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &subkey, &dispos); if (result != ERROR_SUCCESS) { UNONE_ERROR(L"RegCreateKeyExW %s err:%d", key_name.c_str(), result); return false; } DWORD start = SERVICE_DEMAND_START; result = RegSetValueExW(subkey, L"Start", 0, REG_DWORD, (BYTE*)&start, sizeof(start)); if (result != ERROR_SUCCESS) { UNONE_ERROR(L"RegSetValueW err:%d", result); break; } DWORD type = SERVICE_KERNEL_DRIVER; result = RegSetValueExW(subkey, L"Type", 0, REG_DWORD, (BYTE*)&type, sizeof(type)); if (result != ERROR_SUCCESS) { UNONE_ERROR(L"RegSetValueW err:%d", result); break; } DWORD errctl = SERVICE_ERROR_NORMAL; result = RegSetValueExW(subkey, L"ErrorControl", 0, REG_DWORD, (BYTE*)&errctl, sizeof(errctl)); if (result != ERROR_SUCCESS) { UNONE_ERROR(L"RegSetValueW err:%d", result); break; } result = RegSetValueExW(subkey, L"ImagePath", 0, REG_EXPAND_SZ, (BYTE*)driver_path.c_str(), (DWORD)driver_path.size() * 2); if (result != ERROR_SUCCESS) { UNONE_ERROR(L"RegSetValueW err:%d", result); break; } } while (0); if (subkey) RegCloseKey(subkey); return true; } bool ObUnloadDriverRegistryW(__in const std::wstring &srv_name) { std::wstring key_name = L"SYSTEM\\CurrentControlSet\\services\\" + srv_name; SHDeleteKeyW(HKEY_LOCAL_MACHINE, key_name.c_str()); return true; } std::wstring ArkPsGetProcessPathW(__in DWORD pid = GetCurrentProcessId()) { bool activate = false; auto &&path = UNONE::PsGetProcessPathW(pid); if (path.empty()) { UNONE::InterCreateTlsValue(ArkDrvApi::Process::OpenProcessR0, UNONE::PROCESS_VID); path = UNONE::PsGetProcessPathW(pid); activate = true; } if (activate) UNONE::InterDeleteTlsValue(UNONE::PROCESS_VID); return path; } bool PsKillProcess(__in DWORD pid) { bool result = false; HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_TERMINATE, FALSE, pid); if (phd) { if (TerminateProcess(phd, 1)) result = true; CloseHandle(phd); } return result; } // temp function ULONG64 GetFreeLibraryAddress32(DWORD pid) { ULONG64 addr = 0; #ifdef _AMD64_ std::vector<UNONE::MODULE_BASE_INFOW> mods; UNONE::PsGetModulesInfoW(pid, mods); auto it = std::find_if(std::begin(mods), std::end(mods), [](UNONE::MODULE_BASE_INFOW &info) { return UNONE::StrCompareIW(info.BaseDllName, L"kernel32.dll"); }); if (it == std::end(mods)) { UNONE_ERROR("not found kernel32.dll"); return NULL; } ULONG64 base = it->DllBase; auto &&path = UNONE::OsSyswow64DirW() + L"\\kernel32.dll"; auto image = UNONE::PeMapImageByPathW(path); if (!image) { UNONE_ERROR("MapImage %s failed, err:%d", path.c_str(), GetLastError()); return NULL; } auto pFreeLibrary = UNONE::PeGetProcAddress(image, "FreeLibrary"); UNONE::PeUnmapImage(image); if (pFreeLibrary == NULL) { UNONE_ERROR("PsGetProcAddress err:%d", GetLastError()); return NULL; } addr = (ULONG64)pFreeLibrary - (ULONG64)image + base; #else addr = (ULONG64)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "FreeLibrary"); #endif return addr; } ULONG64 GetFreeLibraryAddress(DWORD pid) { ULONG64 addr = 0; if (UNONE::PsIsX64(pid)) { addr = (ULONG64)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "FreeLibrary"); } else { addr = GetFreeLibraryAddress32(pid); } return addr; } std::string OsWinVersionInfo() { //from https://github.com/BlackINT3/unone std::string winver; auto major = UNONE::OsMajorVer(); auto minor = UNONE::OsMinorVer(); auto release = UNONE::OsBuildNumber(); SYSTEM_INFO info; GetSystemInfo(&info); OSVERSIONINFOEX os; os.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); GetVersionEx((OSVERSIONINFO *)&os); if (major == 10 && minor == 0) { if (os.dwPlatformId == VER_PLATFORM_WIN32_NT) { if (release >= 22000) winver = "Windows 11"; else winver = "Windows 10"; } else { switch (release) { case 14393: winver = "Windows Server 2016"; break; case 17763: case 18363: case 19041: case 19042: winver = "Windows Server 2019"; break; case 20348: winver = "Windows Server 2022"; break; } } } else { switch (major) { case 4: switch (minor) { case 0: if (os.dwPlatformId == VER_PLATFORM_WIN32_NT) winver = "Windows NT 4.0"; else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) winver = "Windows 95"; break; case 10: winver = "Windows 98"; break; case 90: winver = "Windows ME"; break; } break; case 5: switch (major) { case 0: winver = "Windows 2000"; break; case 1: winver = "Windows XP"; break; case 2: if (os.wProductType == VER_NT_WORKSTATION && info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) winver = "Windows XP Professional x64 Edition"; else if (GetSystemMetrics(SM_SERVERR2) == 0) winver = "Windows Server 2003"; else if (GetSystemMetrics(SM_SERVERR2) != 0) winver = "Windows Server 2003 R2"; break; } break; case 6: switch (minor) { case 0: if (os.wProductType == VER_NT_WORKSTATION) winver = "Windows Vista"; else winver = "Windows Server 2008"; break; case 1: if (os.wProductType == VER_NT_WORKSTATION) winver = "Windows 7"; else winver = "Windows Server 2008 R2"; break; case 2: if (os.wProductType == VER_NT_WORKSTATION) winver = "Windows 8"; else winver = "Windows Server 2012"; break; case 3: if (os.wProductType == VER_NT_WORKSTATION) winver = "Windows 8.1"; else winver = "Windows Server 2012 R2"; } break; } } return winver; } std::string OsReleaseNumber() { /* //c++11 std::map<DWORD, DWORD> tables = { { 10240, 1507 }, { 10586, 1511} ,{ 14393, 1607 } ,{ 15063, 1703 } ,{ 16299, 1709 } ,{ 17134, 1803 } , { 17763, 1809 }, { 18362, 1903 } ,{ 18363, 1909 } ,{ 19041, 2004 }, { 19042, 20H2 } };*/ std::pair<DWORD, std::string> pairs[] = { std::make_pair(10240, "1507"), std::make_pair(10586, "1511"), std::make_pair(14393, "1607"), std::make_pair(15063, "1703"), std::make_pair(16299, "1709"), std::make_pair(17134, "1803"), std::make_pair(17763, "1809"), std::make_pair(18362, "1903"), std::make_pair(18363, "1909"), std::make_pair(19041, "2004"), std::make_pair(19042, "20H2"), std::make_pair(19043, "21H1"), std::make_pair(19044, "21H2"), std::make_pair(22000, "21H2"), }; std::map<DWORD, std::string> tables(pairs, pairs + _countof(pairs)); DWORD build = UNONE::OsBuildNumber(); auto it = tables.find(build); if (it != tables.end()) return it->second; return ""; }
22,384
C++
.cpp
755
27.217219
139
0.700074
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,171
disassembly.cpp
BlackINT3_OpenArk/src/OpenArk/common/utils/disassembly/disassembly.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include <unone.h> #include "disassembly.h" #include "udis86/udis86.h" std::string DisasmMemory(ULONG64 pc, char *mem, ULONG memsize, int bits /*= 64*/) { if (mem == nullptr) return "??"; std::string disasm; ud_t ud_obj; /* initialize */ ud_init(&ud_obj); ud_set_mode(&ud_obj, bits); ud_set_syntax(&ud_obj, UD_SYN_INTEL); unsigned char o_do_off = 1; unsigned char o_do_hex = 1; ud_set_pc(&ud_obj, pc); ud_set_input_buffer(&ud_obj, (const uint8_t *)mem, memsize); /* disassembly loop */ while (ud_disassemble(&ud_obj)) { if (o_do_off) disasm += UNONE::StrFormatA("%016llX ", ud_insn_off(&ud_obj)); if (o_do_hex) { const char* hex1, *hex2; hex1 = ud_insn_hex(&ud_obj); hex2 = hex1 + 16; disasm += UNONE::StrFormatA("%-16.16s %-24s\n", hex1, ud_insn_asm(&ud_obj)); /* if (strlen(hex1) > 16) { disasm += UNONE::StrFormatA("\n"); if (o_do_off) disasm += UNONE::StrFormatA("%15s -", ""); disasm += UNONE::StrFormatA("%-16s", hex2); }*/ } else disasm += UNONE::StrFormatA(" %-24s", ud_insn_asm(&ud_obj)); } return disasm; } std::string HexDumpMemory(ULONG64 pc, char *mem, ULONG memsize) { auto hexchars = [&](std::string data)->std::string{ std::string prints; std::string stream; if (mem != nullptr) { stream = UNONE::StrHexStrToStreamA(data);; } else { stream.resize(data.size()/2); } for (unsigned char ch : stream) { if (mem == nullptr) { prints.push_back('?'); continue; } if (!isprint(ch)) prints.push_back('.'); else prints.push_back(ch); } return prints; }; std::string str; if (mem == nullptr) { str.assign(memsize*2, '?'); } else { str = UNONE::StrStreamToHexStrA(std::string(mem, memsize)); } std::string formated; auto &&newbuf = UNONE::StrInsertA(str, 32, "\n"); std::vector<std::string> lines; UNONE::StrSplitLinesA(newbuf, lines); for (auto line : lines) { std::string data; data = UNONE::StrInsertA(line, 2, " "); if (line.size() < 32) { auto padsize = (32 - (line.size() % 32)); data += " " + UNONE::StrInsertA(std::string(padsize, ' '), 2, " "); } formated += UNONE::StrFormatA("%016llX %s %s\n", pc, data.c_str(), hexchars(line).c_str()); pc += line.size() / 2; } return formated; }
3,036
C++
.cpp
94
29.776596
95
0.623085
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,172
zip_utils.cpp
BlackINT3_OpenArk/src/OpenArk/common/utils/compress/zip_utils.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "zip_utils.h" #include "xzip/XUnzip.h" #include "xzip/XZip.h" namespace Plugin { namespace Compressor { bool ZipUtils::UnpackToDir(const std::string& zip_path, WRAPPER_TYPE wrapper_type, const std::string& out_dir) { bool result = true; #ifdef _UNICODE auto wzip_path = UNONE::StrToW(zip_path); HZIP h_zip = OpenZip((void*)wzip_path.c_str(), 0, ZIP_FILENAME); #else HZIP h_zip = OpenZip((void*)zip_path.c_str(), 0, ZIP_FILENAME); #endif if (h_zip == NULL) { int x = lasterrorU; printf("Open zip:%s err:%d", zip_path.c_str(), lasterrorU); return false; } ZIPENTRY ze; unsigned long ret = 0; for (int index=0; ret==0; index++) { ret = GetZipItemA(h_zip, index, &ze); if (ret == 0) { std::string name = ze.name; if (wrapper_type == UNPACK_SUBDIR) { auto pos = name.find("/"); if (pos != std::string::npos) { name = name.substr(pos+1); } } if (name.empty()) { continue; } std::string&& path = UNONE::FsPathComposeA(out_dir, name); if (ze.attr & FILE_ATTRIBUTE_DIRECTORY) { UNONE::FsCreateDirA(path); continue; } UNONE::FsCreateDirA(UNONE::FsPathToDirA(path)); #ifdef _UNICODE auto wpath = UNONE::StrToW(path); if (UnzipItem(h_zip, index, (void*)wpath.c_str(), 0, ZIP_FILENAME) != 0) { #else if (UnzipItem(h_zip, index, (void*)path.c_str(), 0, ZIP_FILENAME) != 0) { #endif printf("UnzipItem %s to dir:%s err:%d", ze.name, out_dir.c_str(), lasterrorU); result = false; break; } result = true; } } CloseZip(h_zip); return result; } bool ZipUtils::PackDir(const std::string& dir, WRAPPER_TYPE wrapper_type, const std::string& zip_path) { if (!UNONE::FsIsExistedA(dir)) { printf("Dir:%s not existed", dir.c_str()); return false; } #ifdef _UNICODE auto wzip_path = UNONE::StrToW(zip_path); HZIP h_zip = CreateZip((void *)wzip_path.c_str(), 0, ZIP_FILENAME); #else HZIP h_zip = CreateZip((void *)zip_path.c_str(), 0, ZIP_FILENAME); #endif if(h_zip == NULL) { printf("Create zip_path:%s failed, error %d", zip_path.c_str(), lasterrorU); return false; } bool result = true; std::vector<std::string> path_vec; std::string std_dir = UNONE::FsPathStandardA(dir); UNONE::DirEnumCallbackA fcb = [&](__in char* path, __in char* name, __in void* param)->bool { if (UNONE::FsIsDirA(path)) { UNONE::FsEnumDirectoryA(path, fcb, param);; } auto& path_vec = *reinterpret_cast<std::vector<std::string>*>(param); path_vec.push_back(path); return true; }; UNONE::FsEnumDirectoryA(std_dir, fcb, &path_vec); if (wrapper_type == PACK_CURRENT) { std_dir = UNONE::FsPathToDirA(std_dir); } std_dir.append("\\"); for (size_t i = 0; i < path_vec.size(); i++) { ZRESULT zip_ret = 0; const std::string& path = path_vec[i]; std::string rel_name = path; UNONE::StrReplaceA(rel_name, std_dir, ""); auto flag = ZIP_FILENAME; if (UNONE::FsIsDirA(path)) { flag = ZIP_FOLDER; } #ifdef _UNICODE auto wpath = UNONE::StrToW(path); zip_ret = ZipAdd(h_zip, rel_name.c_str(), (void*)wpath.c_str(), 0, flag); #else zip_ret = ZipAdd(h_zip, rel_name.c_str(), (void*)path.c_str(), 0, flag); #endif if (zip_ret != ZR_OK) { printf("ZipAdd file:%s err:%d", path.c_str(), lasterrorU); result = false; break; } } CloseZip(h_zip); if (!result) { DeleteFileA(zip_path.c_str()); } return result; } bool ZipUtils::PackFile(const std::string& file, const std::string& zip_path) { bool result = true; if (!UNONE::FsIsExistedA(file)) { printf("File:%s not exsited", file.c_str()); return false; } #ifdef _UNICODE auto wzip_path = UNONE::StrToW(zip_path); HZIP h_zip = CreateZip((void *)wzip_path.c_str(), 0, ZIP_FILENAME); #else HZIP h_zip = CreateZip((void *)zip_path.c_str(), 0, ZIP_FILENAME); #endif if(h_zip == NULL) { printf("Create zip_path:%s err:%d", zip_path.c_str(), lasterrorU); return false; } ZRESULT zip_ret = 0; std::string&& rel_name = UNONE::FsPathToNameA(file); #ifdef _UNICODE auto wpath = UNONE::StrToW(file); zip_ret = ZipAdd(h_zip, rel_name.c_str(), (void*)wpath.c_str(), 0, ZIP_FILENAME); #else zip_ret = ZipAdd(h_zip, rel_name.c_str(), (void*)file.c_str(), 0, ZIP_FILENAME); #endif if (zip_ret != ZR_OK) { result = false; } CloseZip(h_zip); if (!result) { DeleteFileA(zip_path.c_str()); } return result; } } //namespace Compressor } //namespace Plugin
5,147
C++
.cpp
165
28.775758
112
0.652244
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,175
cache.cpp
BlackINT3_OpenArk/src/OpenArk/common/cache/cache.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "cache.h" #include "../common.h" #include <arkdrv-api/arkdrv-api.h> static struct { QMutex lck; QMap<unsigned int, ProcInfo> d; } proc_info; ProcInfo CacheGetProcInfo(unsigned int pid) { ProcInfo info; CacheGetProcInfo(pid, info); return info; } ProcInfo CacheGetProcInfo(unsigned int pid, ProcInfo& info) { QMutexLocker locker(&proc_info.lck); if (proc_info.d.contains(pid)) { auto it = proc_info.d.find(pid); info = it.value(); if (!info.path.isEmpty()) { return info; } } info.pid = pid; if (info.ppid == -1) info.ppid = UNONE::PsGetParentPid(pid); if (info.parent_existed == -1) { // May be parent id occupied by someone implies parent not existed info.parent_existed = 1; auto ppid = info.ppid; auto tm1 = ProcessCreateTimeValue(pid); auto tm2 = ProcessCreateTimeValue(ppid); if (UNONE::PsIsDeleted(ppid) || (tm1 && tm2 && tm1 < tm2)) info.parent_existed = 0; } bool activate = false; auto &&path = UNONE::PsGetProcessPathW(pid); if (path.empty()) { UNONE::InterCreateTlsValue(ArkDrvApi::Process::OpenProcessR0, UNONE::PROCESS_VID); path = UNONE::PsGetProcessPathW(pid); activate = true; } static bool is_os64 = UNONE::OsIs64(); info.path = WStrToQ(path); if (!path.empty() && path != L"System") { std::wstring corp, desc; UNONE::FsGetFileInfoW(path, L"CompanyName", corp); UNONE::FsGetFileInfoW(path, L"FileDescription", desc); info.corp = WStrToQ(corp); info.desc = WStrToQ(desc); } if (info.name.isEmpty()) info.name = WStrToQ(UNONE::FsPathToNameW(path)); info.ctime = WStrToQ(ProcessCreateTime(pid)); if (is_os64 && !UNONE::PsIsX64(pid)) info.name.append(" *32"); proc_info.d.insert(pid, info); if (activate) UNONE::InterDeleteTlsValue(UNONE::PROCESS_VID); return info; } void CacheGetProcChilds(unsigned int pid, QVector<ProcInfo>& infos) { if (pid == 0) { return; } QMutexLocker locker(&proc_info.lck); for (auto &info : proc_info.d) { if (info.parent_existed == 1 && info.ppid == pid) { infos.push_back(info); } } } void CacheRefreshProcInfo() { QMutexLocker locker(&proc_info.lck); auto &d = proc_info.d; for (auto it = d.begin(); it != d.end(); ) { auto pid = it.key(); if ((pid == INVALID_PID ) || (pid != 0 && UNONE::PsIsDeleted(pid))) { d.erase(it++); } else { it++; } } } static struct { QMutex lck; QMap<unsigned int, UNONE::PROCESS_BASE_INFOW> d; } proc_baseinfo; UNONE::PROCESS_BASE_INFOW CacheGetProcessBaseInfo(DWORD pid) { UNONE::PROCESS_BASE_INFOW info; QMutexLocker locker(&proc_baseinfo.lck); if (proc_baseinfo.d.contains(pid)) { auto it = proc_baseinfo.d.find(pid); info = it.value(); if (!info.ImagePathName.empty()) return info; } bool activate = false; UNONE::PsGetProcessInfoW(pid, info); if (info.ImagePathName.empty()) { UNONE::InterCreateTlsValue(ArkDrvApi::Process::OpenProcessR0, UNONE::PROCESS_VID); UNONE::PsGetProcessInfoW(pid, info); activate = true; } if (activate) UNONE::InterDeleteTlsValue(UNONE::PROCESS_VID); proc_baseinfo.d.insert(pid, info); return info; } static struct { QMutex lck; QMap<QString, FileBaseInfo> d; } filebase_info; FileBaseInfo CacheGetFileBaseInfo(QString path) { QMutexLocker locker(&filebase_info.lck); if (filebase_info.d.contains(path)) { auto it = filebase_info.d.find(path); return it.value(); } std::wstring corp, desc, ver; auto w_path = path.toStdWString(); UNONE::FsGetFileInfoW(w_path, L"CompanyName", corp); UNONE::FsGetFileInfoW(w_path, L"FileDescription", desc); UNONE::FsGetFileVersionW(w_path, ver); auto info = FileBaseInfo{ path, WStrToQ(desc), WStrToQ(ver), WStrToQ(corp) }; filebase_info.d.insert(path, info); return info; }
4,473
C++
.cpp
142
29.408451
84
0.696135
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,176
config.cpp
BlackINT3_OpenArk/src/OpenArk/common/config/config.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "config.h" #include "../common.h" void OpenArkConfig::Init() { auto &&cpath = AppConfigDir() + L"\\openark.ini"; UNONE::FsCreateDirW(UNONE::FsPathToDirW(cpath)); appconf_ = new QSettings(WStrToQ(cpath), QSettings::IniFormat); } int OpenArkConfig::GetLang(ConfOp op, int &lang) { QString section = "/Main/"; QString key = section + "lang"; if (op == CONF_GET) { lang = GetValue(key, -1).toInt(); return lang; } if (op == CONF_SET) { SetValue(key, lang); return lang; } return -1; } QStringList OpenArkConfig::GetJunkDirs() { QStringList dirs; std::vector<std::wstring> junkdirs; // Temp junkdirs.push_back(UNONE::OsEnvironmentW(L"%Temp%")); junkdirs.push_back(UNONE::OsEnvironmentW(L"%windir%\\Temp")); // Recent auto appdata = UNONE::OsEnvironmentW(L"%AppData%"); auto localappdata = UNONE::OsEnvironmentW(L"%LocalAppData%"); junkdirs.push_back(appdata + L"\\Microsoft\\Windows\\Recent"); junkdirs.push_back(appdata + L"\\Microsoft\\Office\\Recent"); // Chrome junkdirs.push_back(localappdata + L"\\Google\\Chrome\\User Data\\Default\\Cache"); junkdirs.push_back(localappdata + L"\\Google\\Chrome\\User Data\\Default\\Code Cache"); // junkdirs.push_back(L"C:\\AppData\\Roaming"); return WVectorToQList(junkdirs); } QString OpenArkConfig::GetConsole(const QString &name) { QString section = "/Console/"; auto key = section + name; if (name == "History.MaxRecords") { return GetValue(key, "2000").toString(); } if (name == "History.FilePath") { auto &&default_path = AppConfigDir() + L"\\console\\history.txt"; if (!UNONE::FsIsExistedW(default_path)) { UNONE::FsCreateDirW(UNONE::FsPathToDirW(default_path)); UNONE::FsWriteFileDataW(default_path, ""); } return GetValue(key, WStrToQ(default_path)).toString(); } return ""; } void OpenArkConfig::GetMainGeometry(int &x, int &y, int &w, int &h) { QString section = "/Main/"; auto key = section + "x"; if (!(Contains(section + "x") || Contains(section + "y") || Contains(section + "w") || Contains(section + "h"))) { return GetMainDefaultGeometry(x, y, w, h); } x = GetValue(section + "x").toInt(); y = GetValue(section + "y").toInt(); w = GetValue(section + "w").toInt(); h = GetValue(section + "h").toInt(); if (GetSystemMetrics(SM_CMONITORS) <= 1 && (x <= 0 || y <= 0)) OpenArkConfig::Instance()->GetMainDefaultGeometry(x, y, w, h); } void OpenArkConfig::GetMainDefaultGeometry(int &x, int &y, int &w, int &h) { QRect desk = QApplication::desktop()->availableGeometry(); double scale = (double)desk.height() / desk.width(); double width = desk.width() / 1.7; double height = width * scale; double pos_x = desk.width() / 8; double pos_y = desk.height() / 8; x = (int)pos_x; y = (int)pos_y; w = (int)width; h = (int)height; return; } void OpenArkConfig::SetMainGeometry(int x, int y, int w, int h) { QString section = "/Main/"; if (x != -1) SetValue(section + "x", x); if (y != -1) SetValue(section + "y", y); if (w != -1) SetValue(section + "w", w); if (h != -1) SetValue(section + "h", h); Sync(); } void OpenArkConfig::GetMainMaxed(bool &maxed) { QString section = "/Main/"; maxed = GetValue(section + "maxed").toBool();; } void OpenArkConfig::SetMainMaxed(bool maxed) { QString section = "/Main/"; SetValue(section + "maxed", maxed);; Sync(); } void OpenArkConfig::GetPrefMainTab(int &idx) { QString section = "/Preference/"; idx = GetValue(section + "main_tab", idx).toInt(); } void OpenArkConfig::SetPrefMainTab(int idx) { QString section = "/Preference/"; SetValue(section + "main_tab", idx); Sync(); } void OpenArkConfig::GetPrefLevel2Tab(int &idx) { QString section = "/Preference/"; idx = GetValue(section + "level2_tab", idx).toInt(); } void OpenArkConfig::SetPrefLevel2Tab(int idx) { QString section = "/Preference/"; SetValue(section + "level2_tab", idx); Sync(); } void OpenArkConfig::SetMainTabMap(int seq, QVector<int> idx) { QString section = "/Preference/"; if (seq >= maintab_map_.size()) return; QString s; for (auto d : idx) { s.append(QString("%1").arg(d, 2, 10, QChar('0'))); } s = QString("%1%2").arg(idx.size()).arg(s); maintab_map_[seq] = s; QString serial; for (int i = 0; i < maintab_map_.size(); i++) { serial.append(maintab_map_[i]); if (i == maintab_map_.size() - 1) break; serial.append(":"); } SetValue(section + "maintab_map", serial); Sync(); } void OpenArkConfig::GetMainTabMap(int seq, QVector<int> &idx) { QString section = "/Preference/"; QString str; str = GetValue(section + "maintab_map").toString(); if (str.isEmpty()) { for (int i = 0; i < TAB_MAX; i++) { str.append("0"); if (i == TAB_MAX - 1) break; str.append(":"); } } maintab_map_ = str.split(":").toVector(); if (seq >= maintab_map_.size()) return; int cnt = maintab_map_[seq].mid(0, 1).toInt(); if (!cnt) return; QString &back = maintab_map_[seq].mid(1); for (int i = 0; i < back.size(); i+=2) { idx.push_back(back.mid(i, 2).toInt()); } } void OpenArkConfig::GetMainTabAllMap(QVector<QVector<int>> &idxs) { QString section = "/Preference/"; QString str; str = GetValue(section + "maintab_map").toString(); if (str.isEmpty()) { for (int i = 0; i < TAB_MAX; i++) { str.append("20000"); if (i == TAB_MAX - 1) break; str.append(":"); } } for (int seq = 0; seq < TAB_MAX; seq++) { QVector<int> idx; maintab_map_ = str.split(":").toVector(); int cnt = maintab_map_[seq].mid(0, 1).toInt(); if (!cnt) return; QString back = maintab_map_[seq].mid(1); for (int i = 0; i < back.size(); i += 2) { idx.push_back(back.mid(i, 2).toInt()); } idxs.push_back(idx); } } OpenArkConfig* OpenArkConfig::confobj_ = nullptr; OpenArkConfig* OpenArkConfig::Instance() { if (confobj_) return confobj_; confobj_ = new OpenArkConfig; return confobj_; } OpenArkConfig::OpenArkConfig() { } OpenArkConfig::~OpenArkConfig() { }
6,676
C++
.cpp
218
28.568807
88
0.661838
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,177
app.cpp
BlackINT3_OpenArk/src/OpenArk/common/app/app.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "../common.h" #include "app.h" void LogOutput(LogOuputLevel lev, const char* func, const wchar_t* format, ...) { QString levelstr; struct { int lev; QString levstr; } levels[] = { { LevelInfo , TR("[INFO]") }, { LevelWarn , TR("<font color=red>[WARN]</font>") }, { LevelErr , TR("<font color=red>[ERR]</font>") }, { LevelDbg , TR("[DBG]") }, }; for (int i = 0; i < _countof(levels); i++) { if (levels[i].lev == lev) { levelstr = levels[i].levstr; break; } } std::wstring prefix = UNONE::StrFormatW( TR("<font color=#E0E2E4>[%s] %s %s </font>").toStdWString().c_str(), UNONE::StrToW(func).c_str(), levelstr.toStdWString().c_str(), format); std::wstring str; va_list lst; va_start(lst, format); str = UNONE::StrFormatVaListW(prefix.c_str(), lst); va_end(lst); openark->onLogOutput(QString::fromStdWString(str)); } void LogOutput(LogOuputLevel lev, const char* func, const char* format, ...) { va_list lst; va_start(lst, format); std::wstring&& wstr = UNONE::StrToW(UNONE::StrFormatVaListA(format, lst)); LogOutput(lev, func, L"%s", wstr.c_str()); va_end(lst); }
1,910
C++
.cpp
52
34.846154
79
0.638275
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,178
cpp-wrapper.cpp
BlackINT3_OpenArk/src/OpenArk/common/cpp-wrapper/cpp-wrapper.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "cpp-wrapper.h" #include "../common/common.h" int VariantInt(std::string val, int radix) { if (val.empty()) { return 0; } if (val.find("0n") == 0) { UNONE::StrReplaceA(val, "0n"); return UNONE::StrToDecimalA(val); } if (val.find("0x") == 0 || val[val.size() - 1] == 'h') { UNONE::StrReplaceA(val, "0x"); return UNONE::StrToHexA(val); } if (val.find("0t") == 0) { UNONE::StrReplaceA(val, "0t"); return UNONE::StrToOctalA(val); } if (val.find("0y") == 0) { UNONE::StrReplaceA(val, "0y"); return UNONE::StrToBinaryA(val); } switch (radix) { case 2: return UNONE::StrToBinaryA(val); case 8: return UNONE::StrToOctalA(val); case 10: return UNONE::StrToDecimalA(val); case 16: return UNONE::StrToHexA(val); default: return UNONE::StrToHexA(val); } } int64_t VariantInt64(std::string val, int radix) { UNONE::StrReplaceA(val, "`"); if (val.empty()) { return 0; } if (val.find("0n") == 0) { UNONE::StrReplaceA(val, "0n"); return UNONE::StrToDecimal64A(val); } if (val.find("0x") == 0 || val[val.size() - 1] == 'h') { UNONE::StrReplaceA(val, "0x"); return UNONE::StrToHex64A(val); } if (val.find("0t") == 0) { UNONE::StrReplaceA(val, "0t"); return UNONE::StrToOctal64A(val); } if (val.find("0y") == 0) { UNONE::StrReplaceA(val, "0y"); return UNONE::StrToBinary64A(val); } switch (radix) { case 2: return UNONE::StrToBinary64A(val); case 8: return UNONE::StrToOctal64A(val); case 10: return UNONE::StrToDecimal64A(val); case 16: return UNONE::StrToHex64A(val); default: return UNONE::StrToHex64A(val); } } std::wstring VariantFilePath(std::wstring path) { UNONE::StrReplaceIW(path, L"file:///"); return std::move(path); }
2,491
C++
.cpp
81
28.82716
77
0.650332
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,179
cmds.cpp
BlackINT3_OpenArk/src/OpenArk/cmds/cmds.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "cmds.h" #include "constants/constants.h" #include "../common/utils/disassembly/disassembly.h" #include <time.h> #include <arkdrv-api/arkdrv-api.h> struct CommandHelpItem { std::wstring cmd; std::string func; std::wstring doc; std::wstring example; } CmdTable[] = { { L".help", "CmdHelp", LR"(show command manuals)", LR"(.help [show commands help and examples] .help ps [show commands help matches *ps*, eg:.ps])"}, { L".cls", "CmdCls", LR"(clear console screen)", L"" }, { L".history", "CmdHistory", LR"(show commands history)" , LR"(.history [show commands history] .history ps [show commands history matched *ps*])" }, { L".exit", "CmdExit", LR"(exit current process)" , L"" }, { L".restart", "CmdRestart", LR"(restart current process)" , L"" }, { L".cmd", "CmdCmd", LR"(sync execute command line, pipe console output)" , LR"(.cmd whoami [PC\Administrator])" }, { L".start", "CmdStart", LR"(async execute command line)" , LR"(.start taskmgr [open taskmgr])" }, { L".ts", "CmdTimeStamp", LR"(show unix timestamp)" , LR"(.ts 1234566/0n22222/0x431203BC [show timestamp])" }, { L".err", "CmdErrorShow", LR"(show LastError or NTSTATUS)" , LR"(.err 2 [show LastError] .err -s c0000034 [show NTSTATUS])" }, { L".fmt", "CmdFormats", LR"(show value formats, default radix is 16(hex))" , LR"(.fmt 0x400/0n1024 [Hex(0x),Dec(0n),Oct(0t),Bin(0y)])" }, { L".msg", "CmdMsg", LR"(show window message id)", LR"(.msg [show message id list] .msg -name button [show message name matched *button*, eg:WM_LBUTTONDOWN...] .msg -id 201/0x201/0n513 [implies WM_LBUTTONDOWN])" }, { L".wnd", "CmdWndInfo", LR"(show window information)", LR"(.wnd [show system window list] .wnd -title Worker [show window title name matched *Worker*] .wnd -class Worker [show window class name matched *Worker*] .wnd -hwnd 778BC/0x778BC/0n489660 [show HWND=778BC window information] .wnd -pid 8880 [show process pid=8880 window list] out: [hwnd] [parent hwnd] [title] [class] [pid.tid] [process name])" }, { L".ps", "CmdProcessInfo", LR"(show process information)", LR"(.ps [show processes list] .ps -name lsass [find process name matched *lsass*] .ps -pid 1234,0n2048,0x3200 [find process pid=1234/0n2048/0x3200, default is decimal] .ps -path \windows [find process path matched *\windows*] .ps -mods 1234 [show module list that process pid=0n1234, default is decimal] .ps -rst -name chrome [restart process name matched *chrome* , be careful!!!] .ps -rst -pid 1234,0n2048,0x3200 [restart process pid=1234/0n2048/0x3200, default is decimal] .ps -rst -path \temp\ [restart process path matched *\temp\* , be careful!!!] .ps -kill -name chrome [kill process name matched *chrome* , be careful!!!] .ps -kill -pid 1234,0n2048,0x3200 [kill process pid=1234/0n2048/0x3200, default is decimal] .ps -kill -path \temp\ [kill process path matched *\temp\* , be careful!!!] .ps -inject 1234 c:\hook.dll [inject hook.dll into pid=0n1234])" }, { L".pstree", "CmdProcessTree", LR"(show process tree)", LR"(.pstree [show process tree] .pstree 1234/0x3200 [show process tree parent id = 1234 or 0x3200])" }, { L".mm", "CmdMemoryEditor", LR"(memory editor)", LR"(.mm [show os memory] .mm i 1234 [show process pid=1234 memory information] .mm r 1234 40000 100 [read process(pid=1234) memory, 0x40000:0x100] .mm w 1234 40000 cccc9090 [write process(pid=1234) memory, 0x40000=>0xcc 0xcc 0x90 0x90)" }, { L".fs", "CmdFileEditor", LR"(file editor)", LR"(.fs [edit file data] .fs i c:\my.txt [show my.txt information] .fs r c:\my.txt 0 100/all [read my.txt, 0:0x100/all] .fs w c:\my.txt 0 cccc9090 [write my.txt, 0x0=>0xcc 0xcc 0x90 0x90)" }, }; Cmds::Cmds(QTextBrowser *parent) : cmd_window_(parent), cmd_cursor_(0) { for (auto &item : CmdTable) { item.doc = LR"(<b>)" + item.doc + LR"(</b>)"; auto tail = LR"(<br>----------------------------------------------------------------------------------------------------------------------------------------------------------------)"; if (item.example.empty()) item.doc.append(tail); else item.example.append(tail); } auto path = OpenArkConfig::Instance()->GetConsole("History.FilePath").toStdWString(); std::string history; std::vector<std::string> vec; UNONE::FsReadFileDataW(path, history); UNONE::StrSplitA(history, "\r\n", vec); for (auto &h : vec) { if (!h.empty()) cmd_history_.push_back(StrToQ(h)); } } Cmds::~Cmds() { UNONE::InterUnregisterLogger(); std::string history; for (auto &h : cmd_history_) { history.append(h.toStdString()); history.append("\r\n"); } auto path = OpenArkConfig::Instance()->GetConsole("History.FilePath").toStdWString(); UNONE::FsWriteFileDataW(path, history); } Q_INVOKABLE void Cmds::CmdHelp(QString cmd, QStringList argv) { #define SHOW_HELP() \ if (!item.example.empty()) CmdOutput(L"%s - %s\n%s", item.cmd.c_str(), item.doc.c_str(), item.example.c_str()); \ else CmdOutput(L"%s - %s", item.cmd.c_str(), item.doc.c_str()); auto argc = argv.size(); if (argc == 0) { for (auto &item : CmdTable) { SHOW_HELP(); } } if (argc == 1) { auto wstr = argv[0].toStdWString(); for (auto &item : CmdTable) { if (UNONE::StrContainIW(item.cmd, wstr)) SHOW_HELP(); } } } Q_INVOKABLE void Cmds::CmdCls(QString cmd, QStringList argv) { cmd_window_->clear(); } Q_INVOKABLE void Cmds::CmdCmd(QString cmd, QStringList argv) { std::wstring line; if (argv.size() == 1) line = VariantFilePath(line); for (size_t i = 0; i < argv.size(); i++) { line.append(argv[i].toStdWString()); if (i != (argv.size()-1)) line.append(L" "); } auto &&cmdline = L"cmd.exe /c " + line; std::wstring out; DWORD code; ReadStdout(cmdline, out, code); out = UNONE::StrTrimW(out); UNONE::StrReplaceW(out, L"\r"); //UNONE::StrReplaceA(out, "\n", "</br>"); CmdOutput(L"%s", out.c_str()); } Q_INVOKABLE void Cmds::CmdStart(QString cmd, QStringList argv) { std::wstring line; if (argv.size() == 1) line = VariantFilePath(line); for (size_t i = 0; i < argv.size(); i++) { line.append(argv[i].toStdWString()); if (i != (argv.size() - 1)) line.append(L" "); } UNONE::PsCreateProcessW(line); } Q_INVOKABLE void Cmds::CmdMsg(QString cmd, QStringList argv) { if (MessageMapTable.empty()) { std::vector<std::string> msgs; UNONE::StrSplitA(MessageRawString, ",", msgs); for (auto& m : msgs) { std::vector<std::string> kv; UNONE::StrSplitA(m, "=", kv); std::string name = kv[0]; int id = UNONE::StrToHex64A(kv[1]); MessageMapTable[id] = name; } } auto argc = argv.size(); if (argc == 0) { for (auto kv : MessageMapTable) { CmdOutput("0x%04X (%d) %s", kv.first, kv.first, kv.second.c_str()); } return; } if (argc == 2) { auto str = argv[1].toStdString(); if (argv[0] == "-name") { for (auto kv : MessageMapTable) { if (UNONE::StrContainIA(kv.second, str)) { CmdOutput("0x%04X (%d) %s", kv.first, kv.first, kv.second.c_str()); } } return; } if (argv[0] == "-id") { for (auto kv : MessageMapTable) { if (kv.first == VariantInt(str)) { CmdOutput("0x%04X (%d) %s", kv.first, kv.first, kv.second.c_str()); } } return; } } CmdException(cmd,ECMD_PARAM_INVALID); } Q_INVOKABLE void Cmds::CmdWndInfo(QString cmd, QStringList argv) { auto OutputWndInfo = [&](HWND w) { DWORD pid, tid; tid = GetWindowThreadProcessId(w, &pid); auto pname = UNONE::PsGetProcessNameW(pid); auto title = UNONE::PsGetWndTextW(w); auto clsname = UNONE::PsGetWndClassNameW(w); auto parent = GetParent(w); CmdOutput(L"%08X %08X [%s] [%s] [%04X.%04X] %s", w, parent, title.c_str(), clsname.c_str(), pid,tid, pname.c_str()); }; auto argc = argv.size(); if (argc == 0) { for (auto w : GetSystemWnds()) { OutputWndInfo(w);} return; } if (argc == 2) { auto wstr = argv[1].toStdWString(); if (argv[0] == "-title") { for (auto w : GetSystemWnds()) { auto title = UNONE::PsGetWndTextW(w); if (!title.empty() && UNONE::StrContainIW(title, wstr)) { OutputWndInfo(w); } } return; } if (argv[0] == "-class") { for (auto w : GetSystemWnds()) { auto title = UNONE::PsGetWndClassNameW(w); if (!title.empty() && UNONE::StrContainIW(title, wstr)) { OutputWndInfo(w); } } return; } if (argv[0] == "-hwnd") { OutputWndInfo((HWND)VariantInt64(UNONE::StrToA(wstr))); return; } if (argv[0] == "-pid") { auto wnds = UNONE::PsGetWnds(VariantInt(UNONE::StrToA(wstr))); for (auto w : wnds) { OutputWndInfo(w); } return; } } CmdException(cmd,ECMD_PARAM_INVALID); } Q_INVOKABLE void Cmds::CmdHistory(QString cmd, QStringList argv) { std::wstring pattern; auto argc = argv.size(); if (argc == 1) {pattern = argv[0].toStdWString();} int i = 0; for (auto &m : cmd_history_) { if (UNONE::StrContainIW(m.toStdWString(), pattern)) { QString line = QString("%1 %2").arg(i).arg(m); if (i == cmd_cursor_) line.insert(0, "* "); CmdOutput(line.toStdWString().c_str()); } i++; } } Q_INVOKABLE void Cmds::CmdTimeStamp(QString cmd, QStringList argv) { auto paramcnt = argv.size(); if (paramcnt == 0) { CmdOutput("%lld", (DWORD64)time(0)); return; } if (paramcnt == 1) { CmdOutput("%s", UNONE::TmFormatUnixTimeA(VariantInt(argv[0].toStdString(), 10), "Y-M-D H:W:S").c_str()); return; } CmdException(cmd,ECMD_PARAM_INVALID); } Q_INVOKABLE void Cmds::CmdErrorShow(QString cmd, QStringList argv) { auto OutErrorMsg = [&](DWORD err, DWORD status = -1) { auto msg = UNONE::OsDosErrorMsgW(err); if (msg.empty()) { CmdOutput(L"%d is invalid error value", err); } else { if (status != -1) CmdOutput(L"%X: %s", status, msg.c_str()); else CmdOutput(L"%d: %s", err, msg.c_str()); } }; auto argc = argv.size(); if (argc == 1) { int64_t val = VariantInt64(argv[0].toStdString(), 10); OutErrorMsg(val); return; } if (argc == 2) { if (argv[0] == "-s") { int64_t val = VariantInt64(argv[1].toStdString()); OutErrorMsg(UNONE::OsNtToDosError(val), val); return; } } CmdException(cmd,ECMD_PARAM_INVALID); } Q_INVOKABLE void Cmds::CmdFormats(QString cmd, QStringList argv) { auto DecToBin = [](int64_t val)->std::string { char bins[128] = { 0 }; itoa(val, bins, 2); std::string str(bins); int v = 8; str = UNONE::StrRepeatA("0", (v - str.size() % v)) + str; str = UNONE::StrInsertA(str, v, " "); return str; }; if (argv.size() == 1) { int64_t val = VariantInt64(argv[0].toStdString()); CmdOutput("HEX: %X", val); CmdOutput("DEC: %d", val); CmdOutput("OCT: %o", val); CmdOutput("BIN: %s", DecToBin(val).c_str()); auto str = UNONE::StrHexStrToStreamA(UNONE::StrFormatA("%llx", val)); for (auto &c : str) { if (c>0 && c<0xff && !isprint(c)) c = '.'; } CmdOutput("STR: %s", str.c_str()); return; } CmdException(cmd,ECMD_PARAM_INVALID); } Q_INVOKABLE void Cmds::CmdExit(QString cmd, QStringList argv) { ExitProcess(0); } Q_INVOKABLE void Cmds::CmdRestart(QString cmd, QStringList argv) { UNONE::PsCreateProcessW(UNONE::PsGetProcessPathW()); ExitProcess(0); } Q_INVOKABLE void Cmds::CmdProcessInfo(QString cmd, QStringList argv) { auto OuputProcessInfo = [&](std::vector<DWORD> pids) { std::wstring out; out = UNONE::StrFormatW(LR"(<table border="1"><tr><td>PID</td><td>PPID</td><td>ProcessName</td><td>CreateTime</td><td>ProcessPath</td><td>CompanyName</td></tr>)"); for (auto pid : pids) { if (!UNONE::PsIsPidExisted(pid)) continue; auto ppid = UNONE::PsGetParentPid(pid); auto name = UNONE::PsGetProcessNameW(pid); auto path = UNONE::PsGetProcessPathW(pid); auto time = ProcessCreateTime(pid); std::wstring corp; UNONE::FsGetFileInfoW(path, L"CompanyName", corp); out.append(UNONE::StrFormatW(L"<tr><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", pid, ppid, name.c_str(), time.c_str(), path.c_str(), corp.c_str())); } out.append(UNONE::StrFormatW(LR"(</table>)")); CmdOutput(out.c_str()); }; auto OuputModulesInfo = [&](DWORD pid) { std::wstring out; out = UNONE::StrFormatW(LR"(<table border="1"><tr><td>ModuleName</td><td></td><td>ModuleBase</td><td>ModuleSize</td><td>CompanyName</td></tr>)"); std::vector<UNONE::MODULE_BASE_INFOW> infos; UNONE::PsGetModulesInfoW(pid, infos); for (auto info : infos) { auto name = info.BaseDllName; auto path = info.FullDllName; auto base = info.DllBase; auto size = info.SizeOfImage; std::wstring corp; UNONE::FsGetFileInfoW(path, L"CompanyName", corp); out.append(UNONE::StrFormatW(L"<tr><td>%s</td><td>0x%X</td><td>0x%X</td><td>%s</td><td>%s</td></tr>", name.c_str(), base, size, path.c_str(), corp.c_str())); } out.append(UNONE::StrFormatW(LR"(</table>)")); CmdOutput(out.c_str()); }; auto ParsePids = [&](std::wstring wstr, std::vector<DWORD> &pids) { std::vector<std::wstring> wvec; UNONE::StrSplitW(wstr, L",", wvec); for (auto s : wvec) { pids.push_back(VariantInt(UNONE::StrToA(s), 10)); } }; auto FindPidsByName = [&](std::wstring& pattern, std::vector<DWORD> &pids) { UNONE::PsEnumProcess([&](PROCESSENTRY32W &entry)->bool { auto pid = entry.th32ProcessID; if (UNONE::StrContainIW(UNONE::PsGetProcessNameW(pid), pattern)) { pids.push_back(pid); } return true; }); }; auto FindPidsByPath = [&](std::wstring& pattern, std::vector<DWORD> &pids) { UNONE::PsEnumProcess([&](PROCESSENTRY32W &entry)->bool { auto pid = entry.th32ProcessID; if (UNONE::StrContainIW(UNONE::PsGetProcessPathW(pid), pattern)) { pids.push_back(pid); } return true; }); }; auto KillPids = [&](std::vector<DWORD> &pids) { for (auto pid : pids) { ProcInfo info; CacheGetProcInfo(pid, info); auto name = QToWStr(info.name); auto path = QToWStr(info.path); bool killed = PsKillProcess(pid); if (killed) { CmdOutput(L"[+] kill pid:%d name:%s path:%s ok", pid, name.c_str(), path.c_str()); } else { CmdOutput(L"[-] kill pid:%d name:%s path:%s err", pid, name.c_str(), path.c_str()); } } }; auto RestartPids = [&](std::vector<DWORD> &pids) { for (auto pid : pids) { ProcInfo info; CacheGetProcInfo(pid, info); auto name = QToWStr(info.name); auto path = QToWStr(info.path); bool killed = PsKillProcess(pid); if (killed) { UNONE::PsCreateProcessW(path); CmdOutput(L"[+] restart pid:%d name:%s path:%s ok", pid, name.c_str(), path.c_str()); } else { CmdOutput(L"[-] kill pid:%d name:%s path:%s err", pid, name.c_str(), path.c_str()); } } }; auto argc = argv.size(); if (argc == 0) { std::vector<DWORD> pids; UNONE::PsGetAllProcess(pids); OuputProcessInfo(pids); return; } if (argc == 2) { std::wstring wstr = argv[1].toStdWString(); std::vector<DWORD> pids; if (argv[0] == "-name") { FindPidsByName(wstr, pids); OuputProcessInfo(pids); return; } if (argv[0] == "-pid") { ParsePids(wstr, pids); OuputProcessInfo(pids); return; } if (argv[0] == "-path") { FindPidsByPath(wstr, pids); OuputProcessInfo(pids); return; } if (argv[0] == "-mods") { OuputModulesInfo(VariantInt(UNONE::StrToA(wstr), 10)); return; } } if (argc == 3) { if (argv[0] == "-kill") { std::wstring wstr = argv[2].toStdWString(); std::vector<DWORD> pids; if (argv[1] == "-name") { FindPidsByName(wstr, pids); KillPids(pids); return; } if (argv[1] == "-pid") { ParsePids(wstr, pids); KillPids(pids); return; } if (argv[1] == "-path") { FindPidsByPath(wstr, pids); KillPids(pids); return; } } if (argv[0] == "-rst") { std::wstring wstr = argv[2].toStdWString(); std::vector<DWORD> pids; if (argv[1] == "-name") { FindPidsByName(wstr, pids); RestartPids(pids); return; } if (argv[1] == "-pid") { ParsePids(wstr, pids); RestartPids(pids); return; } if (argv[1] == "-path") { FindPidsByPath(wstr, pids); RestartPids(pids); return; } } if (argv[0] == "-inject") { DWORD pid = VariantInt(argv[1].toStdString(), 10); auto path = argv[2].toStdWString(); path = UNONE::StrTrimW(path, L" \n\r\t\""); auto thd = UNONE::PsInjectByRemoteThreadW(pid, path); if (thd) { CmdOutput(L"[+] inject pid:%d path:%s ok", pid, path.c_str()); } else { CmdOutput(L"[-] inject pid:%d path:%s err", pid, path.c_str()); } CloseHandle(thd); return; } } CmdException(cmd,ECMD_PARAM_INVALID); } std::vector<DWORD> _PsGetChildPids(__in DWORD pid) { std::vector<DWORD> childs; UNONE::PsEnumProcess([&](PROCESSENTRY32W &entry)->bool { if (pid != 0 && pid == entry.th32ParentProcessID) { childs.push_back(entry.th32ProcessID); } return true; }); return childs; } Q_INVOKABLE void Cmds::CmdProcessTree(QString cmd, QStringList argv) { DISABLE_RECOVER(); int level = 0; std::wstring prefix; std::function<void(DWORD pid, bool last)> OutputProcessTree = [&](DWORD pid, bool last) { //auto path = UNONE::PsGetProcessPathW(pid); auto name = UNONE::PsGetProcessNameW(pid); if (level == 0) { prefix = L"©À©¤"; } else { prefix = UNONE::StrRepeatW(L"©¦&nbsp;&nbsp;", level); if (last) prefix.append(L"©¸©¤"); else prefix.append(L"©À©¤"); } CmdOutput(L"%s%s(%d)", prefix.c_str(), name.c_str(), pid); level++; auto childs = _PsGetChildPids(pid); for (size_t i = 0; i < childs.size(); i++) { OutputProcessTree(childs[i], (i == childs.size() - 1)); } level--; }; auto argc = argv.size(); if (argc == 0) { UNONE::PsEnumProcess([&](PROCESSENTRY32W &entry)->bool { auto ppid = entry.th32ParentProcessID; if (ppid == 0 || UNONE::PsIsDeleted(ppid)) { // root node OutputProcessTree(entry.th32ProcessID, false); } return true; }); return; } if (argc == 1) { OutputProcessTree(VariantInt(argv[0].toStdString(), 10), false); return; } CmdException(cmd,ECMD_PARAM_INVALID); } Q_INVOKABLE void Cmds::CmdMemoryEditor(QString cmd, QStringList argv) { SIZE_T PageSize; auto OutMemoryInfoStyle1 = [&](wchar_t* name, SIZE_T size) { double mb = (double)(size*PageSize) / 1024 / 1024; double gb = round((double)(size*PageSize) / 1024 / 1024 / 1024); CmdOutput(L"%s : %0.2f GB (%0.2f MB)", name, gb, mb); }; auto OutMemoryInfoStyle2 = [&](wchar_t* name, SIZE_T size) { double mb = (double) size / 1024 / 1024; CmdOutput(L"%s : %0.2f MB", name, mb); }; auto argc = argv.size(); if (argc == 0) { PERFORMANCE_INFORMATION perf = { 0 }; GetPerformanceInfo(&perf, sizeof(perf)); PageSize = perf.PageSize; double usage = GetSystemUsageOfMemory(); CmdOutput(L"%s : %d B", L"PageSize", PageSize); CmdOutput(L"%s : %0.2f%%", L"Memory Usage", usage); CmdOutput(L"-------------------------------------------"); OutMemoryInfoStyle1(L"CommitTotal", perf.CommitTotal); OutMemoryInfoStyle1(L"CommitLimit", perf.CommitLimit); OutMemoryInfoStyle1(L"CommitPeak", perf.CommitPeak); CmdOutput(L"-------------------------------------------"); OutMemoryInfoStyle1(L"PhysicalTotal", perf.PhysicalTotal); OutMemoryInfoStyle1(L"PhysicalAvailable", perf.PhysicalAvailable); CmdOutput(L"-------------------------------------------"); OutMemoryInfoStyle1(L"KernelTotal", perf.KernelTotal); OutMemoryInfoStyle1(L"KernelPaged", perf.KernelPaged); OutMemoryInfoStyle1(L"KernelNonpaged", perf.KernelNonpaged); OutMemoryInfoStyle1(L"SystemCache", perf.SystemCache); return; } if (argc == 2) { if (argv[0] == "i") { DWORD pid = VariantInt(argv[1].toStdString(), 10); PROCESS_MEMORY_COUNTERS_EX mm_info; if (!UNONE::MmGetProcessMemoryInfo(pid, mm_info)) return; OutMemoryInfoStyle2(L"Working set", mm_info.WorkingSetSize); OutMemoryInfoStyle2(L"WS Private", mm_info.WorkingSetSize - GetProcessPrivateWorkingSet(pid)); OutMemoryInfoStyle2(L"Private", mm_info.PrivateUsage); OutMemoryInfoStyle2(L"PeakWorkingSet", mm_info.PeakWorkingSetSize); CmdOutput(L"%s : %d", L"PageFaultCount", mm_info.PageFaultCount); CmdOutput(L"-------------------------------------------"); OutMemoryInfoStyle2(L"QuotaPagedPoolUsage", mm_info.QuotaPagedPoolUsage); OutMemoryInfoStyle2(L"QuotaNonPagedPoolUsage", mm_info.QuotaNonPagedPoolUsage); OutMemoryInfoStyle2(L"QuotaPeakPagedPoolUsage", mm_info.QuotaPeakPagedPoolUsage); OutMemoryInfoStyle2(L"QuotaPeakNonPagedPoolUsage", mm_info.QuotaPeakNonPagedPoolUsage); CmdOutput(L"-------------------------------------------"); OutMemoryInfoStyle2(L"PagefileUsage", mm_info.PagefileUsage); OutMemoryInfoStyle2(L"PeakPagefileUsage", mm_info.PeakPagefileUsage); return; } } if (argc == 4) { DWORD pid = VariantInt(argv[1].toStdString(), 10); if (argv[0] == "r") { HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); ON_SCOPE_EXIT([&phd] {if (phd) CloseHandle(phd); }); if (!phd) return ERR(L"OpenProcess pid:%d err:%d", pid, GetLastError()); DWORD64 addr = VariantInt64(argv[2].toStdString()); DWORD size = VariantInt(argv[3].toStdString()); std::string buf; buf.resize(size); SIZE_T readlen; bool ret = ReadProcessMemory(phd, (LPCVOID)addr, (LPVOID)buf.data(), size, &readlen); if (!ret && size != readlen) { return ERR(L"ReadProcessMemory pid:%d err:%d, expect:%d readlen:%d", pid, GetLastError(), size, readlen); } auto &&hexdump = HexDumpMemory(addr, (char*)buf.data(), buf.size()); UNONE::StrReplaceA(hexdump, "<", "&lt;"); return CmdOutput("%s", hexdump.c_str()); } if (argv[0] == "w") { HANDLE phd = ArkDrvApi::Process::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_WRITE, FALSE, pid); ON_SCOPE_EXIT([&phd] {if (phd) CloseHandle(phd); }); if (!phd) return ERR(L"OpenProcess pid:%d err:%d", pid, GetLastError()); DWORD64 addr = VariantInt64(argv[2].toStdString()); auto &&buf = argv[3].toStdString(); UNONE::StrReplaceA(buf, "."); buf = UNONE::StrHexStrToStreamA(buf); SIZE_T writelen; bool ret = WriteProcessMemory(phd, (LPVOID)addr, (LPVOID)buf.data(), buf.size(), &writelen); if (!ret && buf.size() != writelen) { return ERR(L"WriteProcessMemory pid:%d err:%d, expect:%d readlen:%d", pid, GetLastError(), buf.size(), writelen); } return CmdOutput("WriteProcessMemory addr:%llx size:%d ok", addr, writelen); } } CmdException(cmd,ECMD_PARAM_INVALID); } Q_INVOKABLE void Cmds::CmdFileEditor(QString cmd, QStringList argv) { auto argc = argv.size(); if (argc == 2) { if (argv[0] == "i") { DWORD64 size; auto &&path = VariantFilePath(argv[1].toStdWString()); UNONE::FsGetFileSizeW(path, size); CmdOutput(L"FilePath: %s", path.c_str()); CmdOutput(L"FileSize: %f MB, %f KB, %lld Bytes", (double)size / 1024/1024, (double)size/1024, size); return; } } if (argc == 4) { if (argv[0] == "r") { auto &&path = VariantFilePath(argv[1].toStdWString()); std::string buf; DWORD64 offset = 0; if (argv[3] == "all") { UNONE::FsReadFileDataW(path, buf); } else { offset = VariantInt64(argv[2].toStdString()); DWORD64 size = VariantInt(argv[3].toStdString()); ReadFileDataW(path, offset, size, buf); } auto &&hexdump = HexDumpMemory(offset, (char*)buf.data(), buf.size()); UNONE::StrReplaceA(hexdump, "<", "&lt;"); return CmdOutput("%s", hexdump.c_str()); } if (argv[0] == "w") { auto &&path = VariantFilePath(argv[1].toStdWString()); auto &&buf = argv[3].toStdString(); DWORD64 offset = VariantInt64(argv[2].toStdString()); UNONE::StrReplaceA(buf, "."); buf = UNONE::StrHexStrToStreamA(buf); if (WriteFileDataW(path, offset, buf)) { CmdOutput("WriteFile offset:%llx size:%d ok", offset, buf.size()); } return; } } CmdException(cmd,ECMD_PARAM_INVALID); } QString Cmds::CmdGetLast() { QString cmdline; if (cmd_cursor_ > 0) { cmd_cursor_--; cmdline = cmd_history_[cmd_cursor_]; } return cmdline; } QString Cmds::CmdGetNext() { QString cmdline; if (cmd_cursor_ < cmd_history_.size()) { cmdline = cmd_history_[cmd_cursor_]; cmd_cursor_++; } return cmdline; } void Cmds::CmdException(QString cmd, int type) { switch (type) { case ECMD_PARAM_INVALID: CmdErrorOutput(L"[-] Command parameters invalid."); CmdHelp(".help", QStringList()<<cmd); break; case ECMD_NOSUCH_CMD: CmdErrorOutput(L"[-] No such command. (.help to show help-doc)"); break; default: CmdErrorOutput(L"[-] Unknown exception."); break; } } void Cmds::CmdErrorOutput(const std::wstring &err) { CmdOutput(L"<font color=red>%s</font>", err.c_str()); } void Cmds::CmdOutput(const char* format, ...) { va_list lst; va_start(lst, format); std::wstring &&wstr = UNONE::StrToW(UNONE::StrFormatVaListA(format, lst)); CmdOutput(L"%s", wstr.c_str()); va_end(lst); } void Cmds::CmdOutput(const wchar_t* format, ...) { QString log; va_list lst; va_start(lst, format); std::wstring &&wstr = UNONE::StrFormatVaListW(format, lst); log = QString().fromStdWString(wstr); va_end(lst); log.replace("ERROR", "<font color=red>ERROR</font>"); log.replace("err", "<font color=red>err</font>"); log.replace("failed", "<font color=red>failed</font>"); log.replace("fail", "<font color=red>fail</font>"); log.replace("warning", "<font color=red>warning</font>"); log.replace("WRAN", "<font color=red>WRAN</font>"); log.replace("FATAL", "<font color=red>FATAL</font>"); log = QString("<font color=#E0E2E4>%1</font>").arg(log); log.append("\n"); log.replace("\n", "<br/>"); cmd_window_->append(log); } void Cmds::CmdDispatcher(const std::wstring &cmdline) { UNONE::InterUnregisterLogger(); std::wstring wstr = UNONE::StrTrimW(cmdline); //if (!cmd_window_->toPlainText().isEmpty()) CmdOutput(LR"(<hr>)"); CmdOutput(LR"(<b><font color=#8ccf34>C:\>%s</color></b>)", cmdline.c_str()); if (cmd_history_.empty() || QString::compare(WStrToQ(wstr), cmd_history_.back(), Qt::CaseInsensitive)!=0) { auto cnt = OpenArkConfig::Instance()->GetConsole("History.MaxRecords").toInt(); if (cmd_history_.size() >= cnt) { cmd_history_.pop_front(); } cmd_history_.push_back(WStrToQ(wstr)); } cmd_cursor_ = cmd_history_.size(); std::wstring cmd; std::vector<std::wstring> param; std::vector<std::wstring> vec; if (UNONE::StrContainW(wstr, L" ")) { UNONE::StrSplitW(wstr, L" ", vec); for (auto v : vec) { if (!v.empty()) param.push_back(v); } cmd = param[0]; param.erase(param.begin()); } else { cmd = wstr; } QStringList pramlst = WVectorToQList(param); for (auto& item : CmdTable) { if (UNONE::StrCompareIW(item.cmd, cmd)) { UNONE::InterRegisterLogger([&](const std::wstring &log) { CmdOutput(log.c_str()); }); QMetaObject::invokeMethod(this, item.func.c_str(), Qt::QueuedConnection, Q_ARG(QString, WStrToQ(item.cmd)), Q_ARG(QStringList, pramlst)); return; } } CmdException(WStrToQ(cmd), ECMD_NOSUCH_CMD); }
27,543
C++
.cpp
812
31.07266
185
0.65175
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,180
constants.cpp
BlackINT3_OpenArk/src/OpenArk/cmds/constants/constants.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "constants.h" #include "../../common/common.h" #include <arkdrv-api/api-object/api-object.h> //Win7 std::map<int, std::wstring> ObjectTypeTable;// = { { 2,"Type" },{ 3,"Directory" },{ 4,"SymbolicLink" },{ 5,"Token" },{ 6,"Job" },{ 7,"Process" },{ 8,"Thread" },{ 9,"UserApcReserve" },{ 10,"IoCompletionReserve" },{ 11,"DebugObject" },{ 12,"Event" },{ 13,"EventPair" },{ 14,"Mutant" },{ 15,"Callback" },{ 16,"Semaphore" },{ 17,"Timer" },{ 18,"Profile" },{ 19,"KeyedEvent" },{ 20,"WindowStation" },{ 21,"Desktop" },{ 22,"TpWorkerFactory" },{ 23,"Adapter" },{ 24,"Controller" },{ 25,"Device" },{ 26,"Driver" },{ 27,"IoCompletion" },{ 28,"File" },{ 29,"TmTm" },{ 30,"TmTx" },{ 31,"TmRm" },{ 32,"TmEn" },{ 33,"Section" },{ 34,"Session" },{ 35,"Key" },{ 36,"ALPC Port" },{ 37,"PowerRequest" },{ 38,"WmiGuid" },{ 39,"EtwRegistration" },{ 40,"EtwConsumer" },{ 41,"FilterConnectionPort" },{ 42,"FilterCommunicationPort" },{ 43,"PcwObject" } }; char *MessageRawString = "WM_NULL=0x0000,WM_CREATE=0x0001,WM_DESTROY=0x0002,WM_MOVE=0x0003,WM_SIZE=0x0005,WM_ACTIVATE=0x0006,WM_SETFOCUS=0x0007,WM_KILLFOCUS=0x0008,WM_ENABLE=0x000A,WM_SETREDRAW=0x000B,WM_SETTEXT=0x000C,WM_GETTEXT=0x000D,WM_GETTEXTLENGTH=0x000E,WM_PAINT=0x000F,WM_CLOSE=0x0010,WM_QUERYENDSESSION=0x0011,WM_QUIT=0x0012,WM_QUERYOPEN=0x0013,WM_ERASEBKGND=0x0014,WM_SYSCOLORCHANGE=0x0015,WM_ENDSESSION=0x0016,WM_SHOWWINDOW=0x0018,WM_WININICHANGE=0x001A,WM_SETTINGCHANGE=0x001A,WM_DEVMODECHANGE=0x001B,WM_ACTIVATEAPP=0x001C,WM_FONTCHANGE=0x001D,WM_TIMECHANGE=0x001E,WM_CANCELMODE=0x001F,WM_SETCURSOR=0x0020,WM_MOUSEACTIVATE=0x0021,WM_CHILDACTIVATE=0x0022,WM_QUEUESYNC=0x0023,WM_GETMINMAXINFO=0x0024,WM_PAINTICON=0x0026,WM_ICONERASEBKGND=0x0027,WM_NEXTDLGCTL=0x0028,WM_SPOOLERSTATUS=0x002A,WM_DRAWITEM=0x002B,WM_MEASUREITEM=0x002C,WM_DELETEITEM=0x002D,WM_VKEYTOITEM=0x002E,WM_CHARTOITEM=0x002F,WM_SETFONT=0x0030,WM_GETFONT=0x0031,WM_SETHOTKEY=0x0032,WM_GETHOTKEY=0x0033,WM_QUERYDRAGICON=0x0037,WM_COMPAREITEM=0x0039,WM_GETOBJECT=0x003D,WM_COMPACTING=0x0041,WM_COMMNOTIFY=0x0044,WM_WINDOWPOSCHANGING=0x0046,WM_WINDOWPOSCHANGED=0x0047,WM_POWER=0x0048,WM_COPYDATA=0x004A,WM_CANCELJOURNAL=0x004B,WM_NOTIFY=0x004E,WM_INPUTLANGCHANGEREQUEST=0x0050,WM_INPUTLANGCHANGE=0x0051,WM_TCARD=0x0052,WM_HELP=0x0053,WM_USERCHANGED=0x0054,WM_NOTIFYFORMAT=0x0055,WM_CONTEXTMENU=0x007B,WM_STYLECHANGING=0x007C,WM_STYLECHANGED=0x007D,WM_DISPLAYCHANGE=0x007E,WM_GETICON=0x007F,WM_SETICON=0x0080,WM_NCCREATE=0x0081,WM_NCDESTROY=0x0082,WM_NCCALCSIZE=0x0083,WM_NCHITTEST=0x0084,WM_NCPAINT=0x0085,WM_NCACTIVATE=0x0086,WM_GETDLGCODE=0x0087,WM_SYNCPAINT=0x0088,WM_NCMOUSEMOVE=0x00A0,WM_NCLBUTTONDOWN=0x00A1,WM_NCLBUTTONUP=0x00A2,WM_NCLBUTTONDBLCLK=0x00A3,WM_NCRBUTTONDOWN=0x00A4,WM_NCRBUTTONUP=0x00A5,WM_NCRBUTTONDBLCLK=0x00A6,WM_NCMBUTTONDOWN=0x00A7,WM_NCMBUTTONUP=0x00A8,WM_NCMBUTTONDBLCLK=0x00A9,WM_KEYDOWN=0x0100,WM_KEYUP=0x0101,WM_CHAR=0x0102,WM_DEADCHAR=0x0103,WM_SYSKEYDOWN=0x0104,WM_SYSKEYUP=0x0105,WM_SYSCHAR=0x0106,WM_SYSDEADCHAR=0x0107,WM_KEYLAST=0x0108,WM_IME_STARTCOMPOSITION=0x010D,WM_IME_ENDCOMPOSITION=0x010E,WM_IME_COMPOSITION=0x010F,WM_IME_KEYLAST=0x010F,WM_INITDIALOG=0x0110,WM_COMMAND=0x0111,WM_SYSCOMMAND=0x0112,WM_TIMER=0x0113,WM_HSCROLL=0x0114,WM_VSCROLL=0x0115,WM_INITMENU=0x0116,WM_INITMENUPOPUP=0x0117,WM_MENUSELECT=0x011F,WM_MENUCHAR=0x0120,WM_ENTERIDLE=0x0121,WM_MENURBUTTONUP=0x0122,WM_MENUDRAG=0x0123,WM_MENUGETOBJECT=0x0124,WM_UNINITMENUPOPUP=0x0125,WM_MENUCOMMAND=0x0126,WM_CTLCOLORMSGBOX=0x0132,WM_CTLCOLOREDIT=0x0133,WM_CTLCOLORLISTBOX=0x0134,WM_CTLCOLORBTN=0x0135,WM_CTLCOLORDLG=0x0136,WM_CTLCOLORSCROLLBAR=0x0137,WM_CTLCOLORSTATIC=0x0138,WM_MOUSEMOVE=0x0200,WM_LBUTTONDOWN=0x0201,WM_LBUTTONUP=0x0202,WM_LBUTTONDBLCLK=0x0203,WM_RBUTTONDOWN=0x0204,WM_RBUTTONUP=0x0205,WM_RBUTTONDBLCLK=0x0206,WM_MBUTTONDOWN=0x0207,WM_MBUTTONUP=0x0208,WM_MBUTTONDBLCLK=0x0209,WM_MOUSEWHEEL=0x020A,WM_PARENTNOTIFY=0x0210,WM_ENTERMENULOOP=0x0211,WM_EXITMENULOOP=0x0212,WM_NEXTMENU=0x0213,WM_SIZING=0x0214,WM_CAPTURECHANGED=0x0215,WM_MOVING=0x0216,WM_DEVICECHANGE=0x0219,WM_MDICREATE=0x0220,WM_MDIDESTROY=0x0221,WM_MDIACTIVATE=0x0222,WM_MDIRESTORE=0x0223,WM_MDINEXT=0x0224,WM_MDIMAXIMIZE=0x0225,WM_MDITILE=0x0226,WM_MDICASCADE=0x0227,WM_MDIICONARRANGE=0x0228,WM_MDIGETACTIVE=0x0229,WM_MDISETMENU=0x0230,WM_ENTERSIZEMOVE=0x0231,WM_EXITSIZEMOVE=0x0232,WM_DROPFILES=0x0233,WM_MDIREFRESHMENU=0x0234,WM_IME_SETCONTEXT=0x0281,WM_IME_NOTIFY=0x0282,WM_IME_CONTROL=0x0283,WM_IME_COMPOSITIONFULL=0x0284,WM_IME_SELECT=0x0285,WM_IME_CHAR=0x0286,WM_IME_REQUEST=0x0288,WM_IME_KEYDOWN=0x0290,WM_IME_KEYUP=0x0291,WM_MOUSEHOVER=0x02A1,WM_MOUSELEAVE=0x02A3,WM_CUT=0x0300,WM_COPY=0x0301,WM_PASTE=0x0302,WM_CLEAR=0x0303,WM_UNDO=0x0304,WM_RENDERFORMAT=0x0305,WM_RENDERALLFORMATS=0x0306,WM_DESTROYCLIPBOARD=0x0307,WM_DRAWCLIPBOARD=0x0308,WM_PAINTCLIPBOARD=0x0309,WM_VSCROLLCLIPBOARD=0x030A,WM_SIZECLIPBOARD=0x030B,WM_ASKCBFORMATNAME=0x030C,WM_CHANGECBCHAIN=0x030D,WM_HSCROLLCLIPBOARD=0x030E,WM_QUERYNEWPALETTE=0x030F,WM_PALETTEISCHANGING=0x0310,WM_PALETTECHANGED=0x0311,WM_HOTKEY=0x0312,WM_PRINT=0x0317,WM_PRINTCLIENT=0x0318,WM_HANDHELDFIRST=0x0358,WM_HANDHELDLAST=0x035F,WM_AFXFIRST=0x0360,WM_AFXLAST=0x037F,WM_PENWINFIRST=0x0380,WM_PENWINLAST=0x038F,WM_APP=0x8000,WM_USER=0x0400"; std::map<int, std::string> MessageMapTable; // Dynamic retrieve ObjectIndex ID void InitObjectTypeTable() { if (!ObjectTypeTable.empty()) return; std::vector<ARK_OBJECT_TYPE_ITEM> items; ArkDrvApi::Object::ObjectTypeEnum(items); for (auto &item : items) { ObjectTypeTable[item.type_index] = item.type_name; } return; ObjectTypeTable[2] = L"Type"; ObjectTypeTable[3] = L"Directory"; ObjectTypeTable[4] = L"SymbolicLink"; ObjectTypeTable[5] = L"Token"; ObjectTypeTable[6] = L"Job"; ObjectTypeTable[7] = L"Process"; ObjectTypeTable[8] = L"Thread"; auto file = CreateFileW(UNONE::PsGetProcessPathW().c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); auto iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 0); auto desktop = GetThreadDesktop(GetCurrentThreadId()); auto event = CreateEventW(NULL, FALSE, FALSE, NULL); auto mutant = CreateMutexW(NULL, FALSE, NULL); auto semaphore = CreateSemaphoreW(NULL, 1, 1, NULL); auto section = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READONLY, 0, 0x1000, NULL); auto station = GetProcessWindowStation(); HKEY key; RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SYSTEM", &key); typedef NTSTATUS (NTAPI *__NtCreateKeyedEvent)( OUT PHANDLE KeyedEventHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN ULONG Reserved); auto pNtCreateKeyedEvent = (__NtCreateKeyedEvent)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtCreateKeyedEvent"); HANDLE keyed_event; if (pNtCreateKeyedEvent) pNtCreateKeyedEvent(&keyed_event, EVENT_ALL_ACCESS, NULL, 0); typedef NTSTATUS(NTAPI *__NtCreatePort)( OUT PHANDLE PortHandle, IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG MaxConnectInfoLength, IN ULONG MaxDataLength, IN OUT PULONG Reserved OPTIONAL); auto pNtCreatePort = (__NtCreatePort)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtCreatePort"); HANDLE lpc; if (pNtCreatePort) { OBJECT_ATTRIBUTES oa; UNICODE_STRING port_name; port_name.Buffer = L"\\0xbaddbadd"; port_name.Length = sizeof(L"\\0xbaddbadd"); port_name.MaximumLength = port_name.Length; InitializeObjectAttributes(&oa, &port_name, 0, NULL, NULL); pNtCreatePort(&lpc, &oa, 0, 0, NULL); } typedef NTSTATUS(NTAPI *__NtCreateTimer)( OUT PHANDLE TimerHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN int TimerType); auto pNtCreateTimer = (__NtCreateTimer)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtCreateTimer"); HANDLE timer; if (pNtCreateTimer) pNtCreateTimer(&timer, TIMER_ALL_ACCESS, NULL, 0); UNONE::PsEnumHandle(GetCurrentProcessId(), [&](SYSTEM_HANDLE_TABLE_ENTRY_INFO &info)->bool { HANDLE hd = (HANDLE)info.HandleValue; if (hd == file) { ObjectTypeTable[info.ObjectTypeIndex] = L"File"; } else if (hd == iocp) { ObjectTypeTable[info.ObjectTypeIndex] = L"IoCompletion"; } else if (hd == desktop) { ObjectTypeTable[info.ObjectTypeIndex] = L"Desktop"; } else if (hd == event) { ObjectTypeTable[info.ObjectTypeIndex] = L"Event"; } else if (hd == mutant) { ObjectTypeTable[info.ObjectTypeIndex] = L"Mutant"; } else if (hd == semaphore) { ObjectTypeTable[info.ObjectTypeIndex] = L"Semaphore"; } else if (hd == section) { ObjectTypeTable[info.ObjectTypeIndex] = L"Section"; } else if (hd == station) { ObjectTypeTable[info.ObjectTypeIndex] = L"WindowStation"; } else if (hd == key) { ObjectTypeTable[info.ObjectTypeIndex] = L"Key"; } else if (hd == keyed_event) { ObjectTypeTable[info.ObjectTypeIndex] = L"KeyedEvent"; } else if (hd == lpc) { if (UNONE::OsMajorVer() >= 6) ObjectTypeTable[info.ObjectTypeIndex] = L"ALPC Port"; else ObjectTypeTable[info.ObjectTypeIndex] = L"LPC Port"; } else if (hd == timer) { ObjectTypeTable[info.ObjectTypeIndex] = L"Timer"; } return true; }); CloseHandle(file); CloseHandle(iocp); CloseHandle(event); CloseHandle(mutant); CloseHandle(semaphore); CloseHandle(section); RegCloseKey(key); CloseHandle(lpc); CloseHandle(timer); } int GetObjectTypeIndex(wchar_t* name) { for (auto kv : ObjectTypeTable) { if (kv.second == L"File") return kv.first; } return 0; } std::string MbiTypeToString(int type) { std::string str; if (type & MEM_PRIVATE) str += "MEM_PRIVATE | "; if (type & MEM_IMAGE) str += "MEM_IMAGE | "; if (type & MEM_MAPPED) str += "MEM_MAPPED | "; return str.empty() ? "" : str.substr(0, str.size() - 3); } std::string MbiStateToString(int type) { std::string str; if (type & MEM_COMMIT) str += "MEM_COMMIT | "; if (type & MEM_FREE) str += "MEM_FREE | "; if (type & MEM_RESERVE) str += "MEM_RESERVE | "; return str.empty() ? "" : str.substr(0, str.size() - 3); } std::string MbiPageProtectToString(int type) { std::string str; if (type & PAGE_EXECUTE) str += "PAGE_EXECUTE | "; if (type & PAGE_EXECUTE_READ) str += "PAGE_EXECUTE_READ | "; if (type & PAGE_EXECUTE_READWRITE) str += "PAGE_EXECUTE_READWRITE | "; if (type & PAGE_EXECUTE_WRITECOPY) str += "PAGE_EXECUTE_WRITECOPY | "; if (type & PAGE_NOACCESS) str += "PAGE_NOACCESS | "; if (type & PAGE_READONLY) str += "PAGE_READONLY | "; if (type & PAGE_READWRITE) str += "PAGE_READWRITE | "; if (type & PAGE_GUARD) str += "PAGE_GUARD | "; if (type & PAGE_NOCACHE) str += "PAGE_NOCACHE | "; if (type & PAGE_WRITECOMBINE) str += "PAGE_WRITECOMBINE | "; return str.empty() ? "" : str.substr(0, str.size() - 3); }
11,526
C++
.cpp
163
68.447853
4,255
0.744385
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,181
settings.cpp
BlackINT3_OpenArk/src/OpenArk/settings/settings.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "settings.h" #include "../common/common.h" #include <QMessageBox> bool Settings::eventFilter(QObject *obj, QEvent *e) { if (e->type() == QEvent::KeyPress) { QKeyEvent *keyevt = dynamic_cast<QKeyEvent*>(e); if (keyevt->matches(QKeySequence::Cancel)) { close(); } } return QWidget::eventFilter(obj, e); } void Settings::InitConsoleView() { console_model_ = new QStandardItemModel; console_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Value")); SetDefaultTableViewStyle(ui.consoleView, console_model_); InitTableItem(console_model_); QString name; name = "History.MaxRecords"; AppendTableRowNameVaule(console_model_, name, OpenArkConfig::Instance()->GetConsole(name)); name = "History.FilePath"; AppendTableRowNameVaule(console_model_, name, OpenArkConfig::Instance()->GetConsole(name)); } void Settings::InitCleanView() { QString clean_file_suffix = ui.edit_file_suffix->text(); ui.edit_file_suffix->setText(OpenArkConfig::Instance()->GetValue("clean_file_suffix").toString()); QStringList path_list = OpenArkConfig::Instance()->GetValue("clean_path_list").toStringList(); for (int i = 0; i < path_list.size(); i++) ui.listWidget_path->addItem(path_list[i]); connect(ui.add_path_btn, &QPushButton::clicked, [this]() { QString folder = QFileDialog::getExistingDirectory(this, tr("Open Folder"), ""); if (folder.isEmpty()) return; QString path = folder.replace("/", "\\"); if (!path.isEmpty()) ui.listWidget_path->addItem(path); }); connect(ui.del_path_btn, &QPushButton::clicked, [this]() { QListWidgetItem *item = ui.listWidget_path->takeItem(ui.listWidget_path->currentRow()); delete item; }); connect(ui.save_btn, &QPushButton::clicked, [this]() { QStringList path_list; for (int i = 0; i < ui.listWidget_path->count(); i++) { QListWidgetItem * item = ui.listWidget_path->item(i); path_list << item->text(); } OpenArkConfig::Instance()->SetValue("clean_file_suffix", ui.edit_file_suffix->text()); OpenArkConfig::Instance()->SetValue("clean_path_list", path_list); QMessageBox::information(NULL, "", tr("Save Success")); }); } void Settings::InitGeneralView() { QString section = "/Setting.General/"; QString ctxkey = section + "context_menu"; auto ctx = OpenArkConfig::Instance()->GetValue(ctxkey, 0).toInt(); connect(ui.ctxmenuBox, &QCheckBox::toggled, [=](bool checked) { const char *subkey = R"(*\shell\OpenArk)"; if (checked) { UNONE::RegistryKey reg; reg.Create(HKEY_CLASSES_ROOT, subkey, KEY_SET_VALUE); reg.WriteValue("CommandFlags", 0x20); reg.WriteValue("ExtendedSubCommandsKey", "OpenArk"); reg.WriteValue("Icon", QToChars(AppFilePath())); reg.WriteValue("MUIVerb", "OpenArk"); reg.Close(); reg.Create(HKEY_CLASSES_ROOT, R"(OpenArk\shell\scan)", KEY_SET_VALUE); reg.WriteValue("CommandFlags", 0x20); reg.WriteValue("", tr("Scan").toLocal8Bit().toStdString()); reg.CreateKey("command", KEY_SET_VALUE); reg.WriteValue("", QToChars(AppFilePath())); reg.Close(); reg.Create(HKEY_CLASSES_ROOT, R"(OpenArk\shell\unlockfile)", KEY_SET_VALUE); reg.WriteValue("CommandFlags", 0x20); reg.WriteValue("", tr("UnlockFile").toLocal8Bit().toStdString()); reg.CreateKey("command", KEY_SET_VALUE); reg.WriteValue("", QToChars(AppFilePath())); reg.Close(); reg.Create(HKEY_CLASSES_ROOT, R"(OpenArk\shell\settings)", KEY_SET_VALUE); reg.WriteValue("CommandFlags", 0x20); reg.WriteValue("", tr("Settings").toLocal8Bit().toStdString()); reg.CreateKey("command", KEY_SET_VALUE); reg.WriteValue("", QToChars(AppFilePath())); reg.Close(); } else { UNONE::RegistryKey::DeleteKey(HKEY_CLASSES_ROOT, subkey); UNONE::RegistryKey::DeleteKey(HKEY_CLASSES_ROOT, "OpenArk"); } OpenArkConfig::Instance()->SetValue(ctxkey, (int)checked); }); ui.ctxmenuBox->setChecked(ctx); } Settings::Settings(QWidget *parent) { ui.setupUi(this); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); setAttribute(Qt::WA_ShowModal, true); setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags()& ~(Qt::WindowMaximizeButtonHint| Qt::WindowMinimizeButtonHint)| Qt::MSWindowsFixedSizeDialogHint); installEventFilter(this); InitConsoleView(); InitCleanView(); InitGeneralView(); } Settings::~Settings() { } void Settings::closeEvent(QCloseEvent *e) { QString section = "/Console/"; for (int i = 0; i < console_model_->rowCount(); i++) { auto name = console_model_->item(i, 0)->data(Qt::DisplayRole).toString(); auto value = console_model_->item(i, 1)->data(Qt::DisplayRole); auto key = section + name; OpenArkConfig::Instance()->SetValue(key, value); } OpenArkConfig::Instance()->Sync(); }
5,547
C++
.cpp
134
38.895522
128
0.701706
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,182
kernel.cpp
BlackINT3_OpenArk/src/OpenArk/kernel/kernel.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "kernel.h" #include "driver/driver.h" #include "../common/common.h" #include "../common/utils/disassembly/disassembly.h" #include "../openark/openark.h" #include "wingui/wingui.h" #include "../../../OpenArkDrv/arkdrv-api/arkdrv-api.h" struct { int s = 0; int addr = s++; int type = s++; int path = s++; int desc = s++; int ver = s++; int corp = s++; } NOTIFY; bool NotifySortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { bool ok; auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); auto column = left.column(); if ((column == NOTIFY.addr)) return s1.toString().toULongLong(&ok, 16) < s2.toString().toULongLong(&ok, 16); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } bool HotkeySortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } Kernel::Kernel(QWidget *parent, int tabid) : CommonMainTabObject::CommonMainTabObject((OpenArk*)parent) { ui.setupUi(this); setAcceptDrops(true); network_ = nullptr; storage_ = nullptr; memory_ = nullptr; driver_ = nullptr; object_ = nullptr; network_ = new KernelNetwork(); network_->ModuleInit(&ui, this); storage_ = new KernelStorage(); storage_->ModuleInit(&ui, this); object_ = new KernelObject(); object_->ModuleInit(&ui, this); memory_ = new KernelMemory(); memory_->ModuleInit(&ui, this); driver_ = new KernelDriver(); driver_->ModuleInit(&ui, this); InitKernelEntryView(); InitNotifyView(); InitHotkeyView(); CommonMainTabObject::Init(ui.tabWidget, tabid); connect(this, SIGNAL(signalOpen(QString)), parent_, SLOT(onOpen(QString))); } Kernel::~Kernel() { } bool Kernel::eventFilter(QObject *obj, QEvent *e) { bool filtered = false; if (e->type() == QEvent::ContextMenu) { QMenu *menu = nullptr; if (obj == ui.notifyView->viewport()) menu = notify_menu_; else if (obj == ui.hotkeyView->viewport()) menu = hotkey_menu_; QContextMenuEvent *ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt && menu) { menu->move(ctxevt->globalPos()); menu->show(); } } else if (e->type() == QEvent::MouseMove) { QMouseEvent *mouse = static_cast<QMouseEvent *>(e); if (obj == ui.hkFilterEdit) { if (ui.hkFilterEdit->text().isEmpty()) { QString tips(tr("Tips:If you not found the hotkeys,please check the shortcut keys of IME software.(eg:Microsoft/Sogou/Google IME, etc.)")); QToolTip::showText(mouse->globalPos(), tips); return true; } } } if (network_) network_->eventFilter(obj, e); if (driver_) driver_->eventFilter(obj, e); if (filtered) { dynamic_cast<QKeyEvent*>(e)->ignore(); return true; } return QWidget::eventFilter(obj, e); } void Kernel::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } void Kernel::dropEvent(QDropEvent *event) { if (!event->mimeData()->hasUrls()) return; QString path = event->mimeData()->urls()[0].toLocalFile(); onOpenFile(path); } void Kernel::onClickKernelMode() { QString &&drvname = UNONE::OsIs64() ? "OpenArkDrv64.sys" : "OpenArkDrv32.sys"; QString &&srvname = WStrToQ(UNONE::FsPathToPureNameW(drvname.toStdWString())); if (!arkdrv_conn_) { QString drvpath; drvpath = WStrToQ(UNONE::OsEnvironmentW(QToWStr(L"%Temp%\\" + drvname))); DeleteFileW(QToWChars(drvpath)); ExtractResource(":/OpenArk/driver/" + drvname, drvpath); bool installed; if (UNONE::OsMajorVer() <= 6) { SignExpiredDriver(drvpath); RECOVER_SIGN_TIME(); installed = driver_->InstallDriver(drvpath, srvname); } else { installed = driver_->InstallDriver(drvpath, srvname); } if (!installed) { QERR_W("InstallDriver %s err", QToWChars(drvpath)); return; } if (!ArkDrvApi::ConnectDriver()) { ERR("ConnectDriver err"); return; } ui.kernelModeBtn->setText(tr("Exit KernelMode")); INFO("Enter KernelMode ok"); } else { if (!ArkDrvApi::DisconnectDriver()) { ERR("DisconnectDriver err"); return; } if (!driver_->UninstallDriver(srvname)) { QERR_W("UninstallDriver %s err", QToWChars(srvname)); return; } ui.kernelModeBtn->setText(tr("Enter KernelMode")); INFO("Exit KernelMode ok"); } onRefreshKernelMode(); } void Kernel::onRefreshKernelMode() { bool conn = ArkDrvApi::HeartBeatPulse(); if (conn && !arkdrv_conn_) { ui.kernelModeStatus->setText(tr("[KernelMode] Enter successfully...")); ui.kernelModeStatus->setStyleSheet("color:green"); ui.kernelModeBtn->setText(tr("Exit KernelMode")); arkdrv_conn_ = true; onTabChanged(ui.tabWidget->currentIndex()); } if (!conn && arkdrv_conn_) { ui.kernelModeStatus->setText(tr("[KernelMode] Exit successfully...")); ui.kernelModeStatus->setStyleSheet("color:red"); ui.kernelModeBtn->setText(tr("Enter KernelMode")); arkdrv_conn_ = false; } } void Kernel::onOpenFile(QString path) { if (!UNONE::FsIsFileW(path.toStdWString())) return; path = WStrToQ(UNONE::FsPathStandardW(path.toStdWString())); ui.driverFileEdit->setText(path); auto &&name = UNONE::FsPathToPureNameW(path.toStdWString()); ui.serviceEdit->setText(WStrToQ(name)); } void Kernel::onTabChanged(int index) { if (parent_->GetActiveTab() != TAB_KERNEL) return; switch (index) { case TAB_KERNEL_NOTIFY: ShowSystemNotify(); break; case TAB_KERNEL_HOTKEY: ShowSystemHotkey(); break; default: break; } CommonMainTabObject::onTabChanged(index); } void Kernel::InitKernelEntryView() { kerninfo_model_ = new QStandardItemModel; SetDefaultTableViewStyle(ui.kernelInfoView, kerninfo_model_); ui.kernelModeStatus->setText(tr("[KernelMode] Enter kernel mode needed before using the features(Hotkey/Notify/Memory...)")); ui.kernelModeStatus->setStyleSheet("color:red"); kerninfo_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Value")); ui.kernelInfoView->setColumnWidth(0, 120); int up_seq = 0; auto AddSummaryUpItem = [&](QString name, QString value) { kerninfo_model_->setItem(up_seq, 0, new QStandardItem(name)); kerninfo_model_->setItem(up_seq, 1, new QStandardItem(value)); up_seq++; }; SYSTEM_INFO sys; GetSystemInfo(&sys); sys.dwNumberOfProcessors; OSVERSIONINFOEXW info; info.dwOSVersionInfoSize = sizeof(info); GetVersionExW((LPOSVERSIONINFOW)&info); PERFORMANCE_INFORMATION perf = { 0 }; GetPerformanceInfo(&perf, sizeof(perf)); double gb = round((double)(perf.PhysicalTotal*perf.PageSize) / 1024 / 1024 / 1024); AddSummaryUpItem(tr("OperateSystem"), StrToQ(OsWinVersionInfo())); auto major = UNONE::OsMajorVer(); AddSummaryUpItem(tr("MajorVersion"), DWordToDecQ(major)); AddSummaryUpItem(tr("MiniorVersion"), DWordToDecQ(UNONE::OsMinorVer())); if (major >= 10) AddSummaryUpItem(tr("ReleaseNumber"), StrToQ(OsReleaseNumber())); AddSummaryUpItem(tr("BuildNumber"), DWordToDecQ(UNONE::OsBuildNumber())); AddSummaryUpItem(tr("MajorServicePack"), DWordToDecQ(info.wServicePackMajor)); AddSummaryUpItem(tr("MiniorServicePack"), DWordToDecQ(info.wServicePackMinor)); auto range = ArkDrvApi::Memory::MemoryRange(); AddSummaryUpItem(tr("R3 AddressRange"), StrToQ(UNONE::StrFormatA("0x%llX - 0x%llX", range.r3start, range.r3end))); AddSummaryUpItem(tr("R0 AddressRange"), StrToQ(UNONE::StrFormatA("0x%llX - 0x%llX", range.r0start, range.r0end))); AddSummaryUpItem(tr("Page Size"), StrToQ(UNONE::StrFormatA("%d KB", sys.dwPageSize / 1024))); AddSummaryUpItem(tr("Physical Memory"), StrToQ(UNONE::StrFormatA("%d GB", (int)gb))); AddSummaryUpItem(tr("CPU Count"), DWordToDecQ(sys.dwNumberOfProcessors)); AddSummaryUpItem(tr("SystemRoot"), WStrToQ(UNONE::OsWinDirW())); connect(ui.kernelModeBtn, SIGNAL(clicked()), this, SLOT(onClickKernelMode())); connect(ui.kernelInfoView, &QTableView::doubleClicked, [&](QModelIndex idx) { QString &txt = idx.data().toString(); if (txt == tr("ReleaseNumber") || txt == tr("BuildNumber")) { ShellOpenUrl("https://docs.microsoft.com/en-us/windows/release-health/release-information"); } }); arkdrv_conn_ = false; auto timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(onRefreshKernelMode())); timer->setInterval(1000); timer->start(); } void Kernel::InitNotifyView() { QTreeView *view = ui.notifyView; notify_model_ = new QStandardItemModel; proxy_notify_ = new NotifySortFilterProxyModel(view); std::vector<std::pair<int, QString>> layout = { { 150, tr("Callback Entry") }, { 100, tr("Type") }, { 360, tr("Path") }, { 230, tr("Description") }, { 120, tr("Version") }, { 160, tr("Company") } }; SetDefaultTreeViewStyle(view, notify_model_, proxy_notify_, layout); view->viewport()->installEventFilter(this); view->installEventFilter(this); notify_menu_ = new QMenu(); notify_menu_->addAction(tr("Refresh"), this, [&] { ShowSystemNotify(); }); notify_menu_->addSeparator(); notify_menu_->addAction(tr("Delete Notify"), this, [&] { ULONG64 addr; addr = QHexToQWord(NotifyItemData(NOTIFY.addr)); NOTIFY_TYPE type; auto &&qstr = NotifyItemData(NOTIFY.type); if (qstr == tr("CreateProcess")) type = CREATE_PROCESS; else if (qstr == tr("CreateThread")) type = CREATE_THREAD; else if (qstr == tr("LoadImage")) type = LOAD_IMAGE; else if (qstr == tr("CmpCallback")) type = CM_REGISTRY; ArkDrvApi::Notify::NotifyRemove(type, addr); ShowSystemNotify(); }); notify_menu_->addAction(tr("Disassemble Notify"), this, [&] { QString &&qstr = NotifyItemData(NOTIFY.addr); ULONG64 addr = QHexToQWord(qstr); ULONG size = 0x100; auto memrw = new KernelMemoryRW(); memrw->ViewMemory(GetCurrentProcessId(), addr, size); memrw->OpenNewWindow(qobject_cast<QWidget*>(this->parent()), addr, size); //SetActiveTab(QVector<int>({ KernelTabMemory, KernelMemory::View })); }); notify_menu_->addSeparator(); notify_menu_->addAction(tr("Copy"), this, [&] { ClipboardCopyData(NotifyItemData(GetCurViewColumn(ui.driverView)).toStdString()); }); notify_menu_->addAction(tr("Sendto Scanner"), this, [&] { parent_->SetActiveTab(TAB_SCANNER); emit signalOpen(NotifyItemData(NOTIFY.path)); }); notify_menu_->addAction(tr("Explore File"), this, [&] { ExploreFile(NotifyItemData(NOTIFY.path)); }); notify_menu_->addAction(tr("Properties..."), this, [&]() { WinShowProperties(NotifyItemData(NOTIFY.path).toStdWString()); }); } void Kernel::InitHotkeyView() { QTreeView *view = ui.hotkeyView; hotkey_model_ = new QStandardItemModel; proxy_hotkey_ = new HotkeySortFilterProxyModel(view); static std::vector<std::pair<int, QString>> layout = { { 150, tr("Name") }, { 100, tr("PID.TID") }, { 180, tr("Hotkey") }, { 150, tr("HotkeyObject") }, { 100, tr("HotkeyID") }, { 100, tr("HWND") }, { 180, tr("Title") }, { 180, tr("ClassName") }, { 300, tr("Path") }, { 160, tr("Description") } }; SetDefaultTreeViewStyle(view, hotkey_model_, proxy_hotkey_, layout); view->viewport()->installEventFilter(this); view->installEventFilter(this); ui.hkFilterEdit->installEventFilter(this); ui.hkFilterEdit->setMouseTracking(true); hotkey_menu_ = new QMenu(); hotkey_menu_->addAction(tr("Refresh"), this, [&] { ShowSystemHotkey(); }); hotkey_menu_->addSeparator(); hotkey_menu_->addAction(tr("Delete Hotkey"), this, [&] { ULONG32 vkid = QHexToDWord(HotkeyItemData(LAYOUT_INDEX("HotkeyID"))); auto arr = HotkeyItemData(LAYOUT_INDEX("PID.TID")).split("."); ULONG32 pid = QDecToDWord(arr[0]); ULONG32 tid = QDecToDWord(arr[1]); HOTKEY_ITEM item; item.id = vkid; item.pid = pid; item.tid = tid; if (!ArkDrvApi::WinGUI::HotkeyRemoveInfo(item)) { auto err = UNONE::StrFormatW(L"Remove Hotkey %d.%d id:%x err:%s", pid, tid, vkid, UNONE::OsDosErrorMsgW(GetLastError()).c_str()); MsgBoxError(WStrToQ(err)); return; } INFO(L"Remove Hotkey %d.%d id:%x ok", pid, tid, vkid); proxy_hotkey_->removeRows(ui.hotkeyView->currentIndex().row(), 1); }); hotkey_menu_->addSeparator(); hotkey_menu_->addAction(tr("Sendto Scanner"), this, [&] { parent_->SetActiveTab(TAB_SCANNER); emit signalOpen(HotkeyItemData(LAYOUT_INDEX("Path"))); }); hotkey_menu_->addAction(tr("Explore File"), this, [&] { ExploreFile(HotkeyItemData(LAYOUT_INDEX("Path"))); }); hotkey_menu_->addAction(tr("Properties..."), this, [&]() { WinShowProperties(HotkeyItemData(LAYOUT_INDEX("Path")).toStdWString()); }); connect(ui.hkFilterEdit, &QLineEdit::textChanged, [&](QString str) { ShowSystemHotkey(); }); } void Kernel::ShowSystemNotify() { DISABLE_RECOVER(); ClearItemModelData(notify_model_, 0); std::vector<DRIVER_ITEM> infos; ArkDrvApi::Driver::DriverEnumInfo(infos); auto OutputNotify = [&](std::vector<ULONG64> &routines, QString type) { for (auto routine : routines) { QString path; for (auto info : infos) { if (IN_RANGE(routine, info.base, info.size)) { path = WStrToQ(ParseDriverPath(info.path)); break; } } bool microsoft = true; bool existed = true; auto info = CacheGetFileBaseInfo(path); if (info.desc.isEmpty()) { if (!UNONE::FsIsExistedW(info.path.toStdWString())) { info.desc = tr("[-] Driver file not existed!"); existed = false; } } if (!info.corp.contains("Microsoft", Qt::CaseInsensitive)) { microsoft = false; } QStandardItem *addr_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%llX", routine))); QStandardItem *type_item = new QStandardItem(type); QStandardItem *path_item = new QStandardItem(path); QStandardItem *desc_item = new QStandardItem(info.desc); QStandardItem *ver_item = new QStandardItem(info.ver); QStandardItem *corp_item = new QStandardItem(info.corp); auto count = notify_model_->rowCount(); notify_model_->setItem(count, NOTIFY.addr, addr_item); notify_model_->setItem(count, NOTIFY.type, type_item); notify_model_->setItem(count, NOTIFY.path, path_item); notify_model_->setItem(count, NOTIFY.desc, desc_item); notify_model_->setItem(count, NOTIFY.ver, ver_item); notify_model_->setItem(count, NOTIFY.corp, corp_item); if (!existed) SetLineBgColor(notify_model_, count, Qt::red); else if (!microsoft) SetLineBgColor(notify_model_, count, QBrush(0xffffaa)); } }; std::vector<ULONG64> routines; if (!ArkDrvApi::Notify::NotifyEnumProcess(routines)) QERR_W("NotifyEnumProcess err"); OutputNotify(routines, tr("CreateProcess")); if (!ArkDrvApi::Notify::NotifyEnumThread(routines)) QERR_W("NotifyEnumThread err"); OutputNotify(routines, tr("CreateThread")); if (!ArkDrvApi::Notify::NotifyEnumImage(routines)) QERR_W("NotifyEnumImage err"); OutputNotify(routines, tr("LoadImage")); if (!ArkDrvApi::Notify::NotifyEnumRegistry(routines)) QERR_W("NotifyEnumRegistry err"); OutputNotify(routines, tr("CmpCallback")); } void Kernel::ShowSystemHotkey() { DISABLE_RECOVER(); ClearItemModelData(hotkey_model_, 0); auto flt = ui.hkFilterEdit->text(); std::vector<HOTKEY_ITEM> infos; ArkDrvApi::WinGUI::HotkeyEnumInfo(infos); for (auto item : infos) { auto pid = item.pid; ProcInfo cache; CacheGetProcInfo(pid, cache); auto &&path = QToWStr(cache.path); auto &&name = UNONE::FsPathToNameW(path); if (name.empty()) name = UNONE::StrToW((char*)item.name); auto info = CacheGetFileBaseInfo(WStrToQ(path)); auto name_str = WStrToQ(name); auto wnd_str = WStrToQ(UNONE::StrFormatW(L"0x%X", item.wnd)); auto title_str = WStrToQ(UNONE::PsGetWndTextW((HWND)item.wnd)); auto class_str = WStrToQ(UNONE::PsGetWndClassNameW((HWND)item.wnd)); auto hk_str = WStrToQ(UNONE::StrFormatW(L"0x%p", item.hkobj)); auto ptid_str = WStrToQ(UNONE::StrFormatW(L"%d.%d", item.pid, item.tid)); auto vk_str = StrToQ(HotkeyVkToString(item.vk, item.mod1, item.mod2)); auto vkid_str = WStrToQ(UNONE::StrFormatW(L"0x%X", item.id)); auto path_str = WStrToQ(path); auto desc_str = info.desc; if (!flt.isEmpty()) { if (!name_str.contains(flt, Qt::CaseInsensitive) && !wnd_str.contains(flt, Qt::CaseInsensitive) && !title_str.contains(flt, Qt::CaseInsensitive) && !class_str.contains(flt, Qt::CaseInsensitive) && !hk_str.contains(flt, Qt::CaseInsensitive) && !vk_str.contains(flt, Qt::CaseInsensitive) && !ptid_str.contains(flt, Qt::CaseInsensitive) && !path_str.contains(flt, Qt::CaseInsensitive) && !desc_str.contains(flt, Qt::CaseInsensitive) ) continue; } auto name_item = new QStandardItem(LoadIcon(WStrToQ(path)), name_str); auto wnd_item = new QStandardItem(wnd_str); auto title_item = new QStandardItem(title_str); auto class_item = new QStandardItem(class_str); auto hk_item = new QStandardItem(hk_str); auto ptid_item = new QStandardItem(ptid_str); auto vk_item = new QStandardItem(vk_str); auto vkid_item = new QStandardItem(vkid_str); auto path_item = new QStandardItem(path_str); auto desc_item = new QStandardItem(desc_str); auto count = hotkey_model_->rowCount(); int i = 0; hotkey_model_->setItem(count, i++, name_item); hotkey_model_->setItem(count, i++, ptid_item); hotkey_model_->setItem(count, i++, vk_item); hotkey_model_->setItem(count, i++, hk_item); hotkey_model_->setItem(count, i++, vkid_item); hotkey_model_->setItem(count, i++, wnd_item); hotkey_model_->setItem(count, i++, title_item); hotkey_model_->setItem(count, i++, class_item); hotkey_model_->setItem(count, i++, path_item); hotkey_model_->setItem(count, i++, desc_item); } } QString Kernel::NotifyItemData(int column) { return GetCurItemViewData(ui.notifyView, column); } QString Kernel::HotkeyItemData(int column) { return GetCurItemViewData(ui.hotkeyView, column); }
18,441
C++
.cpp
472
36.495763
143
0.709447
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,183
storage.cpp
BlackINT3_OpenArk/src/OpenArk/kernel/storage/storage.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "storage.h" #include "../../../OpenArkDrv/arkdrv-api/arkdrv-api.h" bool UnlockFileSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } KernelStorage::KernelStorage() { } KernelStorage::~KernelStorage() { } void KernelStorage::onTabChanged(int index) { CommonTabObject::onTabChanged(index); } bool KernelStorage::eventFilter(QObject *obj, QEvent *e) { if (e->type() == QEvent::ContextMenu) { QMenu *menu = nullptr; if (obj == ui_->unlockView->viewport()) menu = unlock_menu_; //if (obj == ui_->fsfltView->viewport()) menu = fsflt_menu_; QContextMenuEvent *ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt && menu) { menu->move(ctxevt->globalPos()); menu->show(); } } else if (e->type() == QEvent::MouseMove) { QMouseEvent *mouse = static_cast<QMouseEvent *>(e); if (obj == ui_->inputPathEdit) { if (ui_->inputPathEdit->text().isEmpty()) { QString tips(tr("Tips: \n1. You can copy file or directory and paste to here(Enter key to ShowHold).\n" "2. You need enter kernel mode to view FileHold.\n" "3. Path is case insensitive.")); QToolTip::showText(mouse->globalPos(), tips); return true; } } } else if (e->type() == QEvent::KeyPress) { QKeyEvent *keyevt = dynamic_cast<QKeyEvent*>(e); if ((keyevt->key() == Qt::Key_Enter) || (keyevt->key() == Qt::Key_Return)) { ui_->showHoldBtn->click(); } } return QWidget::eventFilter(obj, e); } void KernelStorage::ModuleInit(Ui::Kernel *ui, Kernel *kernel) { this->ui_ = ui; this->kernel_ = kernel; Init(ui->tabStorage, TAB_KERNEL, TAB_KERNEL_STORAGE); InitFileUnlockView(); //InitFileFilterView(); } void KernelStorage::InitFileUnlockView() { unlock_model_ = new QStandardItemModel; QTreeView *view = ui_->unlockView; proxy_unlock_ = new UnlockFileSortFilterProxyModel(view); std::vector<std::pair<int, QString>> layout = { { 150, tr("ProcessName") }, { 50, tr("PID") }, { 340, tr("FilePath") }, { 250, tr("ProcessPath") }, { 50, tr("Type") }, { 150, tr("FileObject/DllBase") }, { 70, tr("FileHandle") }, }; SetDefaultTreeViewStyle(view, unlock_model_, proxy_unlock_, layout); view->viewport()->installEventFilter(this); view->installEventFilter(this); ui_->inputPathEdit->installEventFilter(this); ui_->inputPathEdit->setMouseTracking(true); unlock_menu_ = new QMenu(); unlock_menu_->addAction(tr("Refresh"), this, [&] { ui_->showHoldBtn->click(); }); unlock_menu_->addAction(tr("Copy"), this, [&] { auto view = ui_->unlockView; ClipboardCopyData(GetCurItemViewData(view, GetCurViewColumn(view)).toStdString()); }); unlock_menu_->addSeparator(); unlock_menu_->addAction(tr("Unlock"), this, [&] { ui_->unlockFileBtn->click(); }); unlock_menu_->addAction(tr("Unlock All"), this, [&] { ui_->unlockFileAllBtn->click(); }); unlock_menu_->addAction(tr("Kill Process"), this, [&] { ui_->killProcessBtn->click(); }); unlock_menu_->addSeparator(); unlock_menu_->addAction(tr("Scan Selected"), this, [&] { kernel_->GetParent()->SetActiveTab(TAB_SCANNER); auto column = GetCurViewColumn(ui_->unlockView); if (column == 0) column = 3; emit kernel_->signalOpen(GetCurItemViewData(ui_->unlockView, column)); }); unlock_menu_->addAction(tr("Explore Selected"), this, [&] { auto column = GetCurViewColumn(ui_->unlockView); if (column == 0) column = 3; ExploreFile(GetCurItemViewData(ui_->unlockView, column)); }); unlock_menu_->addAction(tr("Properties Selected..."), this, [&]() { auto column = GetCurViewColumn(ui_->unlockView); if (column == 0) column = 3; WinShowProperties(GetCurItemViewData(ui_->unlockView, column).toStdWString()); }); connect(ui_->inputPathEdit, &QLineEdit::textChanged, [&](QString str) { if (str.contains("file:///")) { ui_->inputPathEdit->setText(str.replace("file:///", "")); ui_->inputPathEdit->setText(str.replace("/", "\\")); } }); connect(ui_->showHoldBtn, &QPushButton::clicked, [&] { DISABLE_RECOVER(); ClearItemModelData(unlock_model_, 0); QString file = ui_->inputPathEdit->text(); if (file.isEmpty()) { ERR(L"Please input the file path..."); return; } std::wstring origin, path; std::vector<HANDLE_ITEM> items; origin = UNONE::FsPathStandardW(file.toStdWString()); UNONE::ObParseToNtPathW(origin, path); UNONE::StrLowerW(path); ArkDrvApi::Storage::UnlockEnum(path, items); for (auto item : items) { auto pid = (DWORD)item.pid; ProcInfo info; CacheGetProcInfo(pid, info); auto &&ppath = info.path; auto &&pname = info.name; std::wstring fpath; UNONE::ObParseToDosPathW(item.name, fpath); auto item_pname = new QStandardItem(LoadIcon(ppath), pname); auto item_pid = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%d", pid))); auto item_fpath = new QStandardItem(WStrToQ(fpath)); auto item_ftype = new QStandardItem("FILE"); auto item_fobj = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%p", item.object))); auto item_ppath = new QStandardItem(ppath); auto item_fhandle = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%X", (DWORD)item.handle))); auto count = unlock_model_->rowCount(); unlock_model_->setItem(count, 0, item_pname); unlock_model_->setItem(count, 1, item_pid); unlock_model_->setItem(count, 2, item_fpath); unlock_model_->setItem(count, 3, item_ppath); unlock_model_->setItem(count, 4, item_ftype); unlock_model_->setItem(count, 5, item_fobj); unlock_model_->setItem(count, 6, item_fhandle); } // Add process dll path std::vector<DWORD> pids; UNONE::PsGetAllProcess(pids); for (auto pid : pids) { UNONE::PsEnumModule(pid, [&](MODULEENTRY32W& entry)->bool { if (UNONE::StrContainIW(entry.szExePath, origin)) { QString modname = WCharsToQ(entry.szModule); QString modpath = WCharsToQ(entry.szExePath); HANDLE hmodule = entry.hModule; ProcInfo info; CacheGetProcInfo(pid, info); auto &&ppath = info.path; auto &&pname = info.name; auto item_pname = new QStandardItem(LoadIcon(ppath), pname); auto item_pid = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%d", pid))); auto item_fpath = new QStandardItem(modpath); auto item_ppath = new QStandardItem(ppath); auto item_ftype = new QStandardItem("DLL"); auto item_fobj = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%p", hmodule))); auto item_fhandle = new QStandardItem("0"); auto count = unlock_model_->rowCount(); unlock_model_->setItem(count, 0, item_pname); unlock_model_->setItem(count, 1, item_pid); unlock_model_->setItem(count, 2, item_fpath); unlock_model_->setItem(count, 3, item_ppath); unlock_model_->setItem(count, 4, item_ftype); unlock_model_->setItem(count, 5, item_fobj); unlock_model_->setItem(count, 6, item_fhandle); } return true; }); } }); auto CommonUnlock = [&](QString type, DWORD pid, QString fobj, QString fhandle, QString fpath="") { if (type == "DLL") { // Close by kill process if (fpath.compare(CacheGetProcInfo(pid).path, Qt::CaseInsensitive)) { PsKillProcess(pid); return; } // Close by free library ULONG64 remote_routine = GetFreeLibraryAddress(pid); if (remote_routine) { ULONG64 pararm = QHexToQWord(fobj); for (int i = 0; i < 10; i++) { UNONE::PsCreateRemoteThread((DWORD)pid, remote_routine, pararm, 0); INFO("%d %lld %lld", pid, remote_routine, pararm); } } } else { // Close by driver HANDLE_ITEM handle_item = { 0 }; handle_item.pid = HANDLE(pid); handle_item.handle = HANDLE(QHexToDWord(fhandle)); ArkDrvApi::Storage::UnlockClose(handle_item); } }; connect(ui_->unlockFileBtn, &QPushButton::clicked, [&]{ DISABLE_RECOVER(); auto selected = ui_->unlockView->selectionModel()->selectedIndexes(); if (selected.empty()) return; int count = unlock_model_->columnCount(); for (int i = 0; i < selected.size() / count; i++) { auto pid = ui_->unlockView->model()->itemData(selected[i * count + 1]).values()[0].toUInt(); auto fpath = ui_->unlockView->model()->itemData(selected[i * count + 2]).values()[0].toString(); auto type = ui_->unlockView->model()->itemData(selected[i * count + 4]).values()[0].toString(); auto fobj = ui_->unlockView->model()->itemData(selected[i * count + 5]).values()[0].toString(); auto fhandle = ui_->unlockView->model()->itemData(selected[i * count + 6]).values()[0].toString(); CommonUnlock(type, pid, fobj, fhandle, fpath); } ui_->showHoldBtn->click(); }); connect(ui_->unlockFileAllBtn, &QPushButton::clicked, [&] { DISABLE_RECOVER(); for (int i = 0; i < unlock_model_->rowCount(); i++) { QStandardItem *item = unlock_model_->item(i, 1); //pid auto pid = item->text().toUInt(); auto type = unlock_model_->item(i, 4)->text(); auto fobj = unlock_model_->item(i, 5)->text(); auto fhandle = unlock_model_->item(i, 6)->text(); CommonUnlock(type, pid, fobj, fhandle); } ui_->showHoldBtn->click(); }); connect(ui_->killProcessBtn, &QPushButton::clicked, [&] { DISABLE_RECOVER(); auto selected = ui_->unlockView->selectionModel()->selectedIndexes(); if (selected.empty()) return; int count = unlock_model_->columnCount(); for (int i = 0; i < selected.size() / count; i++) { auto pid = ui_->unlockView->model()->itemData(selected[i * count + 1]).values()[0].toUInt(); PsKillProcess(pid); } ui_->showHoldBtn->click(); }); } void KernelStorage::InitFileFilterView() { /* fsflt_model_ = new QStandardItemModel; fsflt_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Value")); SetDefaultTreeViewStyle(ui_->fsfltView, fsflt_model_); ui_->fsfltView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); ui_->fsfltView->viewport()->installEventFilter(this); ui_->fsfltView->installEventFilter(this); fsflt_menu_ = new QMenu(); fsflt_menu_->addAction(tr("ExpandAll"), this, SLOT(onExpandAll()));*/ } void KernelStorage::ShowUnlockFiles() { }
10,952
C++
.cpp
278
36.241007
107
0.67481
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,185
driver.cpp
BlackINT3_OpenArk/src/OpenArk/kernel/driver/driver.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "../../common/common.h" #include "../../../OpenArkDrv/arkdrv-api/arkdrv-api.h" #include <Windows.h> #include <tchar.h> #include "driver.h" #include "Wincrypt.h" #pragma comment(lib, "Crypt32.lib") struct { int s = 0; int name = s++; int base = s++; int path = s++; int number = s++; int desc = s++; int ver = s++; int corp = s++; } DRV; bool DriversSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); auto column = left.column(); if ((column == DRV.base || column == DRV.number)) return s1.toString().toULongLong(nullptr, 16) < s2.toString().toULongLong(nullptr, 16); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } KernelDriver::KernelDriver() { } KernelDriver::~KernelDriver() { } void KernelDriver::onTabChanged(int index) { switch (index) { case TAB_KERNEL_DRIVER_LIST: ShowDrivers(); break; default: break; } CommonTabObject::onTabChanged(index); } bool KernelDriver::eventFilter(QObject *obj, QEvent *e) { if (e->type() == QEvent::ContextMenu) { QMenu *menu = nullptr; if (obj == ui_->driverView->viewport()) menu = drivers_menu_; QContextMenuEvent *ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt && menu) { menu->move(ctxevt->globalPos()); menu->show(); } } return QWidget::eventFilter(obj, e); } void KernelDriver::ModuleInit(Ui::Kernel *mainui, Kernel *kernel) { this->ui_ = mainui; this->kernel_ = kernel; Init(ui_->tabDriver, TAB_KERNEL, TAB_KERNEL_DRIVER); InitDriversView(); InitDriverKitView(); } void KernelDriver::InitDriversView() { QTreeView *view = ui_->driverView; drivers_model_ = new QStandardItemModel; proxy_drivers_ = new DriversSortFilterProxyModel(view); std::vector<std::pair<int, QString>> layout = { { 138, tr("Name") }, { 135, tr("Base") }, { 285, tr("Path") }, { 60, tr("Number") }, { 180, tr("Description") }, { 120, tr("Version") }, { 160, tr("Company") } }; SetDefaultTreeViewStyle(view, drivers_model_, proxy_drivers_, layout); view->viewport()->installEventFilter(this); view->installEventFilter(this); drivers_menu_ = new QMenu(); drivers_menu_->addAction(tr("Refresh"), this, [&] { ShowDrivers(); }); drivers_menu_->addAction(tr("Copy"), this, [&] { ClipboardCopyData(DriversItemData(GetCurViewColumn(ui_->driverView)).toStdString()); }); drivers_menu_->addAction(tr("Sendto Scanner"), this, [&] { kernel_->GetParent()->SetActiveTab(TAB_SCANNER); emit kernel_->signalOpen(DriversItemData(DRV.path)); }); drivers_menu_->addAction(tr("Explore File"), this, [&] { ExploreFile(DriversItemData(DRV.path)); }); drivers_menu_->addAction(tr("Properties..."), this, [&] { WinShowProperties(DriversItemData(DRV.path).toStdWString()); }); } void KernelDriver::InitDriverKitView() { ui_->groupWDF->setVisible(false); connect(ui_->browseBtn, &QPushButton::clicked, this, [&]() { QString file = QFileDialog::getOpenFileName(kernel_, tr("Open File"), "", tr("Driver Files (*.sys);;All Files (*.*)")); kernel_->onOpenFile(file); }); connect(ui_->installBtn, SIGNAL(clicked()), this, SLOT(onInstallNormallyDriver())); connect(ui_->uninstallBtn, SIGNAL(clicked()), this, SLOT(onUninstallDriver())); connect(ui_->writeRegBtn, &QPushButton::clicked, [&] { auto driver = QToWStr(ui_->driverFileEdit->text()); auto service = QToWStr(ui_->serviceEdit->text()); ObLoadDriverRegistryW(driver, service) ? LabelSuccess(ui_->infoLabel, tr("Write registry ok...")) : LabelError(ui_->infoLabel, tr("Write registry failed, open console window to view detail...")); }); connect(ui_->cleanRegBtn, &QPushButton::clicked, [&] { auto service = QToWStr(ui_->serviceEdit->text()); ObUnloadDriverRegistryW(service) ? LabelSuccess(ui_->infoLabel, tr("Clean registry ok...")) : LabelError(ui_->infoLabel, tr("Clean registry failed, open console window to view detail...")); }); } void KernelDriver::onSignDriver() { QString driver = ui_->driverFileEdit->text(); SignExpiredDriver(driver) ? LabelSuccess(ui_->infoLabel, tr("Sign ok...")) : LabelError(ui_->infoLabel, tr("Sign failed, open console window to view detail...")); } void KernelDriver::onInstallNormallyDriver() { InstallDriver(ui_->driverFileEdit->text(), ui_->serviceEdit->text()) ? LabelSuccess(ui_->infoLabel, tr("Install ok...")) : LabelError(ui_->infoLabel, tr("Install failed, open console window to view detail...")); } void KernelDriver::onInstallUnsignedDriver() { onSignDriver(); RECOVER_SIGN_TIME(); onInstallNormallyDriver(); } void KernelDriver::onInstallExpiredDriver() { RECOVER_SIGN_TIME(); onInstallNormallyDriver(); } void KernelDriver::onUninstallDriver() { UninstallDriver(ui_->serviceEdit->text()) ? LabelSuccess(ui_->infoLabel, tr("Uninstall ok...")) : LabelError(ui_->infoLabel, tr("Uninstall failed, open console window to view detail...")); } bool KernelDriver::InstallDriver(QString driver, QString name) { if (driver.isEmpty()) { QERR_W("driver path is empty"); return false; } auto &&path = driver.toStdWString(); return UNONE::ObLoadDriverW(path, name.toStdWString()); } bool KernelDriver::UninstallDriver(QString service) { if (service.isEmpty()) { QERR_W("service is empty"); return false; } return UNONE::ObUnloadDriverW(service.toStdWString()); } void KernelDriver::ShowDrivers() { DISABLE_RECOVER(); ClearItemModelData(drivers_model_, 0); std::vector<LPVOID> drivers; UNONE::ObGetDriverList(drivers); int number = 0; for (auto d : drivers) { static int major = UNONE::OsMajorVer(); auto &&w_path = UNONE::ObGetDriverPathW(d); if (major <= 5) { if (UNONE::StrIndexIW(w_path, L"\\Windows") == 0) { static auto &&drive = UNONE::OsEnvironmentW(L"%SystemDrive%"); w_path = drive + w_path; } else if (w_path.find(L'\\') == std::wstring::npos && w_path.find(L'/') == std::wstring::npos) { static auto &&driverdir = UNONE::OsSystem32DirW() + L"\\drivers\\"; w_path = driverdir + w_path; } } auto &&path = WStrToQ(w_path); auto &&name = WStrToQ(UNONE::ObGetDriverNameW(d)); bool microsoft = true; bool existed = true; auto info = CacheGetFileBaseInfo(path); if (info.desc.isEmpty()) { if (!UNONE::FsIsExistedW(info.path.toStdWString())) { info.desc = tr("[-] Driver file not existed!"); existed = false; } } if (!info.corp.contains("Microsoft", Qt::CaseInsensitive)) { microsoft = false; } auto name_item = new QStandardItem(name); auto base_item = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%p", d))); auto path_item = new QStandardItem(path); auto number_item = new QStandardItem(QString("%1").arg(number)); auto desc_item = new QStandardItem(info.desc); auto ver_item = new QStandardItem(info.ver); auto corp_item = new QStandardItem(info.corp); auto count = drivers_model_->rowCount(); drivers_model_->setItem(count, DRV.name, name_item); drivers_model_->setItem(count, DRV.base, base_item); drivers_model_->setItem(count, DRV.path, path_item); drivers_model_->setItem(count, DRV.number, number_item); drivers_model_->setItem(count, DRV.desc, desc_item); drivers_model_->setItem(count, DRV.ver, ver_item); drivers_model_->setItem(count, DRV.corp, corp_item); if (!existed) SetLineBgColor(drivers_model_, count, Qt::red); else if (!microsoft) SetLineBgColor(drivers_model_, count, QBrush(0xffffaa)); number++; } } QString KernelDriver::DriversItemData(int column) { return GetCurItemViewData(ui_->driverView, column); } bool ImportPrivateKey(const std::string &private_key, WCHAR *passwd, WCHAR *category) { bool ret = false; HCERTSTORE cert_store = NULL; HCERTSTORE cert_dst_store = NULL; PCCERT_CONTEXT cert = NULL; HCRYPTPROV crypt_prov = NULL; do { CRYPT_DATA_BLOB blob; blob.cbData = private_key.size(); blob.pbData = (unsigned char *)private_key.c_str(); cert_store = PFXImportCertStore(&blob, passwd, CRYPT_EXPORTABLE); if (!cert_store) { ERR("PFXImportCertStore err:%d", GetLastError()); break; } DWORD key_spec = 0; BOOL free_prov = FALSE; cert = CertEnumCertificatesInStore(cert_store, NULL); if (!cert) { ERR("CertEnumCertificatesInStore err:%d", GetLastError()); break; } if (!CryptAcquireCertificatePrivateKey(cert, CRYPT_ACQUIRE_COMPARE_KEY_FLAG, NULL, &crypt_prov, &key_spec, &free_prov) || !crypt_prov) { ERR("CryptAcquireCertificatePrivateKey err:%d", GetLastError()); break; } cert_dst_store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_OPEN_EXISTING_FLAG, category); if (!cert_dst_store) { ERR("CertOpenStore err:%d", GetLastError()); break; } ret = CertAddCertificateContextToStore(cert_dst_store, cert, CERT_STORE_ADD_REPLACE_EXISTING, NULL); if (!ret) { ERR("CertAddCertificateContextToStore err:%d", GetLastError()); break; } ret = true; } while (0); if (cert) CertFreeCertificateContext(cert); if (crypt_prov) CryptReleaseContext(crypt_prov, 0); if (cert_dst_store) CertCloseStore(cert_dst_store, 0); if (cert_store) CertCloseStore(cert_store, 0); return ret; } bool SignExpiredDriver(QString driver) { if (driver.isEmpty()) { QERR_W("driver is empty"); return false; } QString res = ":/OpenArk/sign/CSignTool.pfx"; QFile pfx(res); if (!pfx.open(QFileDevice::ReadOnly)) { QERR_W("open resource file %s err", QToWChars(res)); return false; } if (!ImportPrivateKey(pfx.readAll().toStdString(), _T("TrustAsia.com"), _T("My"))) { QERR_W("import pfx certificate file %s err", QToWChars(res)); return false; } auto &&toodir = UNONE::OsEnvironmentW(L"%AppData%\\TrustAsia\\DSignTool"); auto &&signtool = toodir + L"\\CSignTool.exe"; auto &&signcfg = toodir + L"\\Config.xml"; ExtractResource(":/OpenArk/sign/CSignTool.exe", WStrToQ(signtool)); ExtractResource(":/OpenArk/sign/Config.xml", WStrToQ(signcfg)); RECOVER_SIGN_TIME(); std::wstring cmdline; std::wstring &&path = driver.toStdWString(); UNONE::StrFormatW(cmdline, L"%s sign /r Driver /f \"%s\" /ac", signtool.c_str(), path.c_str()); PROCESS_INFORMATION pi; if (!UNONE::PsCreateProcessW(cmdline, SW_HIDE, &pi)) { QERR_W("run cmdline:%s err", cmdline.c_str()); return false; } WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return true; } std::wstring ParseDriverPath(UCHAR *symlnk) { std::wstring &&path = UNONE::StrToW((char*)symlnk); std::wstring sysroot = L"\\SystemRoot"; auto pos = path.find(sysroot); if (pos == 0) path.replace(0, sysroot.size(), UNONE::OsWinDirW()); UNONE::StrReplaceW(path, L"\\??\\"); return path; }
11,496
C++
.cpp
326
32.90184
142
0.700836
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,186
memory.cpp
BlackINT3_OpenArk/src/OpenArk/kernel/memory/memory.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "memory.h" #include <common/common.h> #include <common/utils/disassembly/disassembly.h> #include <common/qt-wrapper/qt-wrapper.h> #include <openark/openark.h> #include <kernel/driver/driver.h> #include <arkdrv-api/arkdrv-api.h> #include <QtUiTools/QtUiTools> #define DEFINE_WIDGET(type, value) auto value = memui_->findChild<type>(#value) KernelMemory::KernelMemory() { } KernelMemory::~KernelMemory() { } void KernelMemory::onTabChanged(int index) { CommonTabObject::onTabChanged(index); } bool KernelMemory::eventFilter(QObject *obj, QEvent *e) { return QWidget::eventFilter(obj, e); } void KernelMemory::ModuleInit(Ui::Kernel *mainui, Kernel *kernel) { this->ui = mainui; Init(ui->tabMemory, TAB_KERNEL, TAB_KERNEL_MEMORY); auto memrw_ = new KernelMemoryRW(); auto memwidget = memrw_->GetWidget(); memwidget->setParent(ui->tabMemoryView); memwidget->layout()->removeWidget(memwidget); ui->verticalLayout_7->addWidget(memwidget); memwidget->show(); } KernelMemoryRW::KernelMemoryRW() { free_init_ = false; maxsize_ = -1; QUiLoader loader; QFile file(":/UI/ui/memory-rw.ui"); file.open(QFile::ReadOnly); memui_ = loader.load(&file); memui_->setAttribute(Qt::WA_DeleteOnClose); file.close(); setAttribute(Qt::WA_DeleteOnClose); connect(memui_, &QWidget::destroyed, this, &QWidget::close); memui_->installEventFilter(this); DEFINE_WIDGET(QPushButton*, readMemBtn); connect(readMemBtn, &QPushButton::clicked, this, [&] { DEFINE_WIDGET(QLineEdit*, pidEdit); DEFINE_WIDGET(QLineEdit*, readAddrEdit); DEFINE_WIDGET(QLineEdit*, readSizeEdit); ULONG64 addr = VariantInt64(readAddrEdit->text().toStdString()); ULONG size = VariantInt(readSizeEdit->text().toStdString()); ULONG pid = VariantInt(pidEdit->text().toStdString(), 10); if (size > PAGE_SIZE * 100) { QMessageBox::warning(this, tr("Warning"), tr("Read size too big, UI maybe no responsible."), QMessageBox::Ok); return; } ViewMemory(pid, addr, size); }); DEFINE_WIDGET(QPushButton*, dumpToFileBtn); connect(dumpToFileBtn, &QPushButton::clicked, this, [&] { DEFINE_WIDGET(QLineEdit*, pidEdit); DEFINE_WIDGET(QLineEdit*, readAddrEdit); DEFINE_WIDGET(QLineEdit*, readSizeEdit); DEFINE_WIDGET(QLabel*, statusLabel); ULONG64 addr = VariantInt64(readAddrEdit->text().toStdString()); ULONG size = VariantInt(readSizeEdit->text().toStdString()); ULONG pid = VariantInt(pidEdit->text().toStdString(), 10); std::string buf; if (!ArkDrvApi::Memory::MemoryRead(pid, addr, size, buf)) { LabelError(statusLabel, tr("Read Memory error, addr:0x%1 size:0x%2").arg(QString::number(addr, 16).toUpper()).arg(QString::number(size, 16).toUpper())); return; } QString filename = WStrToQ(UNONE::StrFormatW(L"%s_%llX_%X", QToWChars(CacheGetProcInfo(pid).name), addr, size)); QString dumpmem = QFileDialog::getSaveFileName(this, tr("Save to"), filename, tr("DumpMemory(*)")); if (!dumpmem.isEmpty()) { UNONE::FsWriteFileDataW(dumpmem.toStdWString(), buf) ? LabelSuccess(statusLabel, tr("Dump memory to file ok")): LabelError(statusLabel, tr("Dump memory to file error")); } }); DEFINE_WIDGET(QPushButton*, writeMemBtn); connect(writeMemBtn, &QPushButton::clicked, this, [&] { DEFINE_WIDGET(QLineEdit*, writeDataEdit); auto data = writeDataEdit->text().toStdString(); UNONE::StrReplaceA(data, " "); data = UNONE::StrHexStrToStreamA(data); WriteMemory(data); }); DEFINE_WIDGET(QPushButton*, writeStringBtn); connect(writeStringBtn, &QPushButton::clicked, this, [&] { DEFINE_WIDGET(QLineEdit*, writeDataEdit); auto data = writeDataEdit->text().toStdString(); WriteMemory(data); }); DEFINE_WIDGET(QLineEdit*, pidEdit); connect(pidEdit, &QLineEdit::textChanged, [&](const QString&) { DEFINE_WIDGET(QLineEdit*, pidEdit); DEFINE_WIDGET(QLabel*, pnameLabel); DEFINE_WIDGET(QLabel*, iconLabel); ULONG pid = VariantInt(pidEdit->text().toStdString(), 10); auto &&name = CacheGetProcInfo(pid).name; if (name.isEmpty()) return; pnameLabel->setText(name); auto pixmap = LoadIcon(CacheGetProcInfo(pid).path).pixmap(iconLabel->size()).scaled(iconLabel->size(), Qt::KeepAspectRatio); iconLabel->setScaledContents(true); iconLabel->setPixmap(pixmap); }); emit pidEdit->textChanged("4"); } KernelMemoryRW::~KernelMemoryRW() { if (free_init_) free_callback_(free_vars_); } bool KernelMemoryRW::eventFilter(QObject *obj, QEvent *e) { if (e->type() == QEvent::KeyPress) { QKeyEvent *keyevt = dynamic_cast<QKeyEvent*>(e); if (keyevt->matches(QKeySequence::Cancel)) { memui_->close(); } } return QWidget::eventFilter(obj, e); } void KernelMemoryRW::ViewMemory(ULONG pid, ULONG64 addr, ULONG size) { bool readok = false; char *mem = nullptr; ULONG memsize = 0; std::string buf; DEFINE_WIDGET(QLineEdit*, pidEdit); pidEdit->setText(QString::number(pid)); auto minsize = MIN(maxsize_, size); if (ArkDrvApi::Memory::MemoryRead(pid, addr, minsize, buf)) { mem = (char*)buf.c_str(); memsize = buf.size(); readok = true; } auto hexdump = HexDumpMemory(addr, mem, memsize); if (size > memsize) { auto hexdump2 = HexDumpMemory(addr+size, nullptr, size-memsize); hexdump.append(hexdump2); } bool isx64 = true; if (ArkDrvApi::Memory::IsKernelAddress(addr)) { isx64 = UNONE::OsIs64(); } else { EN_VID_PROCESS(); isx64 = UNONE::PsIsX64(pid); } auto disasm = DisasmMemory(addr, mem, minsize, isx64 ? 64 : 32); DEFINE_WIDGET(QTextEdit*, hexEdit); DEFINE_WIDGET(QTextEdit*, disasmEdit); DEFINE_WIDGET(QLabel*, regionLabel); DEFINE_WIDGET(QLabel*, statusLabel); hexEdit->setText(StrToQ(hexdump)); disasmEdit->setText(StrToQ(disasm)); std::vector<DRIVER_ITEM> infos; ArkDrvApi::Driver::DriverEnumInfo(infos); QString path; for (auto info : infos) { if (IN_RANGE(addr, info.base, info.size)) { path = WStrToQ(ParseDriverPath(info.path)); regionLabel->setText(path); break; } } readok ? LabelSuccess(statusLabel, tr("Read Memory successfully, addr:0x%1 size:0x%2").arg(QString::number(addr, 16).toUpper()).arg(QString::number(size, 16).toUpper())) : LabelError(statusLabel, tr("Read Memory error, addr:0x%1 size:0x%2").arg(QString::number(addr, 16).toUpper()).arg(QString::number(size, 16).toUpper())); } void KernelMemoryRW::ViewMemory(ULONG pid, std::string data) { return ViewMemory(pid, (ULONG64)data.c_str(), data.size()); } void KernelMemoryRW::WriteMemory(std::string data) { DEFINE_WIDGET(QLineEdit*, pidEdit); DEFINE_WIDGET(QLineEdit*, writeAddrEdit); DEFINE_WIDGET(QLabel*, statusLabel); ULONG64 addr = VariantInt64(writeAddrEdit->text().toStdString()); if (ArkDrvApi::Memory::IsKernelAddress(addr)) { if (QMessageBox::warning(this, tr("Warning"), tr("Write kernel memory maybe cause BSOD, are you sure to write?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { return; } } ULONG pid = VariantInt(pidEdit->text().toStdString(), 10); ArkDrvApi::Memory::MemoryWrite(pid, addr, data) ? LabelSuccess(statusLabel, tr("Write Memory successfully, addr:0x%1").arg(QString::number(addr, 16).toUpper())) : LabelError(statusLabel, tr("Write Memory error, addr:0x%1").arg(QString::number(addr, 16).toUpper())); }
7,979
C++
.cpp
208
36.057692
172
0.720341
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,187
network.cpp
BlackINT3_OpenArk/src/OpenArk/kernel/network/network.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include <WinSock2.h> #include <arkdrv-api/arkdrv-api.h> #include "network.h" /* //https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/8fd93a3d-a794-4233-9ff7-09b89eed6b1f/compiling-with-wfp?forum=wfp #include "include/fwpmu.h" #pragma comment(lib, "fwpuclnt.lib") #pragma comment(lib, "Rpcrt4.lib") BOOLEAN GuidEqual(_In_ const GUID* pGUIDAlpha, _In_ const GUID* pGUIDOmega) { RPC_STATUS status = RPC_S_OK; UINT32 areEqual = FALSE; do { if (pGUIDAlpha == 0 || pGUIDOmega == 0) { if ((pGUIDAlpha == 0 && pGUIDOmega) || (pGUIDAlpha && pGUIDOmega == 0)) break; } if (pGUIDAlpha == 0 && pGUIDOmega == 0) { areEqual = TRUE; break; } areEqual = UuidEqual((UUID*)pGUIDAlpha, (UUID*)pGUIDOmega, &status); } while (false); return (BOOLEAN)areEqual; } bool EnumWfpCallouts(std::vector<CALLOUT_INFO>& CalloutIDs) { bool Result = false; HANDLE EngineHandle = NULL; UINT32 status = NO_ERROR; FWPM_SESSION session = { 0 }; HANDLE EnumHandle = NULL; FWPM_CALLOUT_ENUM_TEMPLATE* pCalloutEnumTemplate = NULL; session.displayData.name = L"WFPSampler's User Mode Session"; session.flags = 0; do { status = FwpmEngineOpen0(0, RPC_C_AUTHN_WINNT, 0, &session, &EngineHandle); if (status != NO_ERROR) { break; } status = FwpmCalloutCreateEnumHandle(EngineHandle, pCalloutEnumTemplate, &EnumHandle); if (status != NO_ERROR) { break; } UINT32 NumEntries = 0; FWPM_CALLOUT** ppCallouts = 0; status = FwpmCalloutEnum0(EngineHandle, EnumHandle, 0xFFFFFFFF, &ppCallouts, &NumEntries); if (status != NO_ERROR) { break; } if (ppCallouts) { for (DWORD Index = 0; Index < NumEntries; Index++) { CALLOUT_INFO CalloutInfo; CalloutInfo.CalloutId = ppCallouts[Index]->calloutId; RtlCopyMemory(&CalloutInfo.CalloutKey, &ppCallouts[Index]->calloutKey, sizeof(GUID)); CalloutIDs.push_back(CalloutInfo); } Result = true; } } while (false); if (EnumHandle) { FwpmCalloutDestroyEnumHandle(EngineHandle, EnumHandle); } if (EngineHandle) { status = FwpmEngineClose(EngineHandle); } if (pCalloutEnumTemplate) { delete pCalloutEnumTemplate; pCalloutEnumTemplate = NULL; } return Result; } UINT64 GetFilterIDByCalloutKey(const GUID* CalloutKey) { UINT64 Result = 0; HANDLE EngineHandle = NULL; LONG Status = NO_ERROR; FWPM_SESSION Session = { 0 }; HANDLE EnumHandle = 0; FWPM_FILTER_ENUM_TEMPLATE* pFilterEnumTemplate = NULL; Session.displayData.name = L"WFPSampler's User Mode Session"; Session.flags = 0; do { Status = FwpmEngineOpen(0, RPC_C_AUTHN_WINNT, 0, &Session, &EngineHandle); if (Status != NO_ERROR) { break; } UINT32 NumEntries = 0; FWPM_FILTER** ppFilters = 0; Status = FwpmFilterCreateEnumHandle0(EngineHandle, pFilterEnumTemplate, &EnumHandle); if (Status != NO_ERROR) { break; } Status = FwpmFilterEnum0(EngineHandle, EnumHandle, 0xFFFFFFFF, &ppFilters, &NumEntries); if (Status != NO_ERROR) { break; } if (Status == NO_ERROR && ppFilters && NumEntries) { for (UINT32 Index = 0; Index < NumEntries; Index++) { if (GuidEqual(&ppFilters[Index]->action.calloutKey, CalloutKey)) { Result = ppFilters[Index]->filterId; break; } } } } while (false); if (EngineHandle) { Status = FwpmEngineClose(EngineHandle); } if (pFilterEnumTemplate) { delete pFilterEnumTemplate; pFilterEnumTemplate = NULL; } return Result; } bool DeleteFilterById(UINT64 FilterId) { bool Result = false; HANDLE EngineHandle = NULL; LONG Status = NO_ERROR; FWPM_SESSION Session = { 0 }; Session.displayData.name = L"WFPSampler's User Mode Session"; Session.flags = 0; do { Status = FwpmEngineOpen(0, RPC_C_AUTHN_WINNT, 0, &Session, &EngineHandle); if (Status != NO_ERROR) { break; } Status = FwpmFilterDeleteById(EngineHandle, FilterId); if (Status != NO_ERROR) { break; } Result = true; } while (false); if (EngineHandle) { Status = FwpmEngineClose(EngineHandle); } return Result; } */ bool WfpSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } #define QVariantHex(s1) s1.toString().toULongLong(nullptr, 16) #define QVariantStrcmp(s1, s2) QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) bool PortSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); auto column = left.column(); if ((column == 1 || column == 2)) { auto list1 = s1.toString().split(":"); auto list2 = s2.toString().split(":"); auto ip1 = list1[0]; auto ip2 = list2[0]; if (ip1 != ip2) return ip1 < ip2; return QHexToDWord(list1[1]) < QHexToDWord(list2[1]); } if ((column == 4)) return QVariantHex(s1) < QVariantHex(s2); return QVariantStrcmp(s1, s2) < 0; } KernelNetwork::KernelNetwork() { } KernelNetwork::~KernelNetwork() { } void KernelNetwork::onTabChanged(int index) { switch (index) { //case TAB_KERNEL_NETWORK_WFP: ShowWfpInfo(); break; case TAB_KERNEL_NETWORK_PORT: onShowPortInfo(); break; default: break; } CommonTabObject::onTabChanged(index); } bool KernelNetwork::eventFilter(QObject *obj, QEvent *e) { if (e->type() == QEvent::ContextMenu) { QMenu *menu = nullptr; if (obj == ui_->hostsFileListWidget) menu = hosts_menu_; if (obj == ui_->portView) menu = port_menu_; QContextMenuEvent *ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt && menu) { menu->move(ctxevt->globalPos()); menu->show(); } } if (e->type() == QEvent::KeyPress) { QKeyEvent *keyevt = dynamic_cast<QKeyEvent*>(e); if (keyevt->matches(QKeySequence::Delete)) { for (auto &action : hosts_menu_->actions()) { if (action->text() == tr("Delete")) emit action->trigger(); } } if (keyevt->matches(QKeySequence::Refresh)) { onShowPortInfo(); } } return QWidget::eventFilter(obj, e); } void KernelNetwork::ModuleInit(Ui::Kernel *ui, Kernel *kernel) { this->ui_ = ui; this->kernel_ = kernel; Init(ui->tabNetwork, TAB_KERNEL, TAB_KERNEL_NETWORK); //InitWfpView(); InitHostsView(); InitPortView(); //onTabChanged(ui_->tabNetwork->currentIndex()); } void KernelNetwork::InitWfpView() { /* wfp_model_ = new QStandardItemModel; QTreeView *view = ui_->wfpView; proxy_wfp_ = new WfpSortFilterProxyModel(view); proxy_wfp_->setSourceModel(wfp_model_); proxy_wfp_->setDynamicSortFilter(true); proxy_wfp_->setFilterKeyColumn(1); view->setModel(proxy_wfp_); view->selectionModel()->setModel(proxy_wfp_); view->header()->setSortIndicator(-1, Qt::AscendingOrder); view->setSortingEnabled(true); view->viewport()->installEventFilter(kernel_); view->installEventFilter(kernel_); std::pair<int, QString> colum_layout[] = { { 130, tr("ID") }, { 100, tr("Key") }, { 200, tr("Name") }, }; QStringList name_list; for (auto p : colum_layout) { name_list << p.second; } wfp_model_->setHorizontalHeaderLabels(name_list); for (int i = 0; i < _countof(colum_layout); i++) { view->setColumnWidth(i, colum_layout[i].first); } view->setEditTriggers(QAbstractItemView::NoEditTriggers); */ } void KernelNetwork::InitHostsView() { hosts_dir_ = UNONE::OsSystem32DirW() + L"\\drivers\\etc"; hosts_file_ = hosts_dir_ + L"\\hosts"; auto GetCurrentHostsName = [=]()->std::wstring { std::wstring hosts; auto cur = ui_->hostsFileListWidget->currentItem(); if (cur) { hosts = cur->text().toStdWString(); } return std::move(hosts); }; auto GetCurrentHostsPath = [=]()->std::wstring { std::wstring hosts = GetCurrentHostsName(); if (!hosts.empty()) hosts = hosts_dir_ + L"\\" + hosts; return std::move(hosts); }; auto RefreshHostsData = [=]() { std::string data; auto &&hosts = GetCurrentHostsPath(); UNONE::FsReadFileDataW(hosts, data); ui_->hostsDataEdit->setText(StrToQ(data)); }; auto WriteHostsData = [=](std::wstring path = L"") { std::string data = ui_->hostsDataEdit->toPlainText().toStdString(); std::wstring hosts; if (path.empty()) hosts = GetCurrentHostsPath(); else hosts = path; UNONE::StrReplaceA(data, "\n", "\r\n"); UNONE::FsWriteFileDataW(hosts, data); }; auto RefreshHostsList = [=]() { auto row = ui_->hostsFileListWidget->currentRow(); ui_->hostsFileListWidget->clear(); std::vector<std::wstring> names; UNONE::DirEnumCallbackW fcb = [&](wchar_t* path, wchar_t* name, void* param)->bool { if (UNONE::FsIsDirW(path)) return true; size_t yy=UNONE::StrIndexIW(std::wstring(name), std::wstring(L"hosts")); if (UNONE::StrIndexIW(std::wstring(name), std::wstring(L"hosts")) != 0) return true; names.push_back(name); return true; }; UNONE::FsEnumDirectoryW(hosts_dir_, fcb); for (auto &n : names) { ui_->hostsFileListWidget->addItem(WStrToQ(n)); } ui_->hostsFileListWidget->setCurrentRow(row); }; connect(ui_->hostsFileListWidget, &QListWidget::itemSelectionChanged, [=] { RefreshHostsData(); }); connect(ui_->hostsRefreshBtn, &QPushButton::clicked, [=] { RefreshHostsData(); RefreshHostsList(); }); connect(ui_->hostsSaveBtn, &QPushButton::clicked, [=] { WriteHostsData(); }); connect(ui_->hostsBackupBtn, &QPushButton::clicked, [=] { bool ok; SYSTEMTIME systime; GetSystemTime(&systime); QString def = WStrToQ(UNONE::TmFormatSystemTimeW(systime, L"YMD-HWS")); QString text = QInputDialog::getText(this, tr("Hosts Backup"), tr("Please input file name: (hosts-***)"), QLineEdit::Normal, def, &ok); if (ok && !text.isEmpty()) { auto &&hosts = hosts_dir_ + L"\\hosts-" + text.toStdWString(); WriteHostsData(hosts); RefreshHostsList(); } }); connect(ui_->hostsClearBtn, &QPushButton::clicked, [=] { ui_->hostsDataEdit->clear(); }); connect(ui_->hostsDirBtn, &QPushButton::clicked, [&] { ShellRun(WStrToQ(hosts_dir_), ""); }); if (!UNONE::FsIsExistedW(hosts_file_)) UNONE::FsWriteFileDataW(hosts_file_, "# 127.0.0.1 localhost\n# ::1 localhost"); RefreshHostsList(); ui_->hostsFileListWidget->setCurrentRow(0); ui_->hostsFileListWidget->installEventFilter(this); hosts_menu_ = new QMenu(); hosts_menu_->addAction(tr("Mark as Main"), kernel_, [=] { WriteHostsData(hosts_file_); RefreshHostsList(); ui_->hostsFileListWidget->setCurrentRow(0); }); hosts_menu_->addAction(tr("Rename"), kernel_, [=] { bool ok; std::wstring &&old = GetCurrentHostsPath(); auto && name = UNONE::FsPathToNameW(old); UNONE::StrReplaceIW(name, L"hosts-"); QString text = QInputDialog::getText(this, tr("Hosts Rename"), tr("Please input file name: (hosts-***)"), QLineEdit::Normal, WStrToQ(name), &ok); if (ok) { DeleteFileW(old.c_str()); std::wstring hosts; if (!text.isEmpty()) { hosts = hosts_dir_ + L"\\hosts-" + text.toStdWString(); } else { hosts = hosts_dir_ + L"\\hosts"; } WriteHostsData(hosts); RefreshHostsList(); } }); hosts_menu_->addAction(tr("Backup"), kernel_, [=] { emit ui_->hostsBackupBtn->click(); }); auto copy_menu = new QMenu(); copy_menu->addAction(tr("File Name"))->setData(0); copy_menu->addAction(tr("File Path"))->setData(1); copy_menu->setTitle(tr("Copy")); connect(copy_menu, &QMenu::triggered, [=](QAction* action) { auto idx = action->data().toInt(); std::wstring data; switch (idx) { case 0: data = GetCurrentHostsName(); break; case 1: data = GetCurrentHostsPath(); break; } ClipboardCopyData(UNONE::StrToA(data)); }); hosts_menu_->addAction(tr("Refresh"), kernel_, [=] { emit ui_->hostsRefreshBtn->click(); }); hosts_menu_->addAction(copy_menu->menuAction()); hosts_menu_->addSeparator(); hosts_menu_->addAction(tr("Delete"), kernel_, [=] { DeleteFileW(GetCurrentHostsPath().c_str()); emit ui_->hostsRefreshBtn->click(); }, QKeySequence::Delete); hosts_menu_->addAction(tr("Delete Non-Main"), kernel_, [=] { if (QMessageBox::warning(this, tr("Warning"), tr("Are you sure to delete all hosts file(include backups)?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { return; } for (int i = 0; i < ui_->hostsFileListWidget->count(); i++) { auto name = ui_->hostsFileListWidget->item(i)->text(); if (!name.compare("hosts", Qt::CaseInsensitive)) continue; auto path = hosts_dir_ + L"\\" + QToWStr(name); DeleteFileW(path.c_str()); } emit ui_->hostsRefreshBtn->click(); }); } void KernelNetwork::InitPortView() { QTreeView *view = ui_->portView; port_model_ = new QStandardItemModel; proxy_port_ = new PortSortFilterProxyModel(view); std::vector<std::pair<int, QString>> layout = { { 50, tr("Protocol") }, { 135, tr("Local address") }, { 145, tr("Foreign address") }, { 100, tr("State") }, { 50, tr("PID") }, { 530, tr("Process Path") }, }; SetDefaultTreeViewStyle(view, port_model_, proxy_port_, layout); view->viewport()->installEventFilter(this); view->installEventFilter(this); port_menu_ = new QMenu(); port_menu_->addAction(tr("Refresh"), this, [&] { onShowPortInfo(); }, QKeySequence::Refresh); port_menu_->addAction(tr("Copy"), this, [&] { auto view = ui_->portView; ClipboardCopyData(GetCurItemViewData(view, GetCurViewColumn(view)).toStdString()); }); port_menu_->addSeparator(); port_menu_->addAction(tr("Kill Process"), this, [&] { auto pid = GetCurItemViewData(ui_->portView, 4).toInt(); PsKillProcess(pid); onShowPortInfo(); }); port_menu_->addSeparator(); port_menu_->addAction(tr("Sendto Scanner"), this, [&] { kernel_->GetParent()->SetActiveTab(TAB_SCANNER); emit kernel_->signalOpen(GetCurItemViewData(ui_->portView, 5)); }); port_menu_->addAction(tr("Explore File"), this, [&] { ExploreFile(GetCurItemViewData(ui_->portView, 5)); }); port_menu_->addAction(tr("Properties..."), this, [&]() { WinShowProperties(GetCurItemViewData(ui_->portView, 5).toStdWString()); }); connect(ui_->locaIPv4Btn, &QPushButton::clicked, [] {ShellRun("cmd.exe", "/k ipconfig|findstr /i ipv4"); }); connect(ui_->locaIPv6Btn, &QPushButton::clicked, [] {ShellRun("cmd.exe", "/k ipconfig|findstr /i ipv6"); }); connect(ui_->ipv4CheckBox, SIGNAL(clicked()), this, SLOT(onShowPortInfo())); connect(ui_->ipv6CheckBox, SIGNAL(clicked()), this, SLOT(onShowPortInfo())); connect(ui_->tcpListenCheckBox, SIGNAL(clicked()), this, SLOT(onShowPortInfo())); connect(ui_->tcpConnCheckBox, SIGNAL(clicked()), this, SLOT(onShowPortInfo())); connect(ui_->udpListenCheckBox, SIGNAL(clicked()), this, SLOT(onShowPortInfo())); connect(ui_->portFilterEdit, &QLineEdit::textChanged, [&](QString str) {onShowPortInfo(); }); ui_->ipv4CheckBox->setChecked(true); ui_->tcpListenCheckBox->setChecked(true); } void KernelNetwork::ShowWfpInfo() { DISABLE_RECOVER(); ClearItemModelData(wfp_model_, 0); std::vector<CALLOUT_INFO> infos; //EnumWfpCallouts(infos); for (auto item : infos) { auto id_item = new QStandardItem(DWordToHexQ(item.CalloutId)); auto key_item = new QStandardItem(DWordToHexQ(item.CalloutKey)); auto name_item = new QStandardItem(item.ModuleName); auto count = wfp_model_->rowCount(); wfp_model_->setItem(count, 0, id_item); wfp_model_->setItem(count, 1, key_item); wfp_model_->setItem(count, 2, name_item); } } void KernelNetwork::onShowPortInfo() { DISABLE_RECOVER(); ClearItemModelData(port_model_, 0); auto ipv4 = ui_->ipv4CheckBox->isChecked(); auto ipv6 = ui_->ipv6CheckBox->isChecked(); auto tcpls = ui_->tcpListenCheckBox->isChecked(); auto tcpconn = ui_->tcpConnCheckBox->isChecked(); auto udpls = ui_->udpListenCheckBox->isChecked(); std::vector<ARK_NETWORK_ENDPOINT_ITEM> items; std::vector<ARK_NETWORK_ENDPOINT_ITEM> newers; if (tcpls || tcpconn) { if (ipv4) ArkDrvApi::Network::EnumTcp4Endpoints(items); if (ipv6) ArkDrvApi::Network::EnumTcp6Endpoints(items); for (auto &item : items) { if (tcpls && item.state == 2) newers.push_back(item); if (tcpconn && item.state != 2) newers.push_back(item); } } if (udpls) { items.clear(); if (ipv4) ArkDrvApi::Network::EnumUdp4Endpoints(items); if (ipv6) ArkDrvApi::Network::EnumUdp6Endpoints(items); newers.insert(newers.end(), items.begin(), items.end()); } auto flt = ui_->portFilterEdit->text(); for (auto &item : newers) { auto protocol = CharsToQ(item.protocol); auto local = CharsToQ(item.local); auto remote = CharsToQ(item.remote); auto readable_state = (item.tran_ver == ARK_NETWORK_TCP) ? CharsToQ(item.readable_state) : ""; auto pidstr = WStrToQ(UNONE::StrFormatW(L"%d", item.pid)); ProcInfo pi; CacheGetProcInfo(item.pid, pi); if (!flt.isEmpty()) { if (!protocol.contains(flt, Qt::CaseInsensitive) && !local.contains(flt, Qt::CaseInsensitive) && !remote.contains(flt, Qt::CaseInsensitive) && !readable_state.contains(flt, Qt::CaseInsensitive) && !pidstr.contains(flt, Qt::CaseInsensitive) && !pi.path.contains(flt, Qt::CaseInsensitive) ) continue; } auto item_0 = new QStandardItem(protocol); auto item_1 = new QStandardItem(local); auto item_2 = new QStandardItem(remote); auto item_3 = new QStandardItem(readable_state); auto item_4 = new QStandardItem(pidstr); auto item_5 = new QStandardItem(LoadIcon(pi.path), pi.path); auto count = port_model_->rowCount(); port_model_->setItem(count, 0, item_0); port_model_->setItem(count, 1, item_1); port_model_->setItem(count, 2, item_2); port_model_->setItem(count, 3, item_3); port_model_->setItem(count, 4, item_4); port_model_->setItem(count, 5, item_5); } }
18,515
C++
.cpp
570
29.738596
147
0.687724
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,188
object.cpp
BlackINT3_OpenArk/src/OpenArk/kernel/object/object.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "object.h" #include <arkdrv-api/arkdrv-api.h> bool ObjectTypesSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); auto column = left.column(); if ((column == 1 || column == 3 || column == 4)) return s1.toString().toULongLong(nullptr, 16) < s2.toString().toULongLong(nullptr, 16); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } bool ObjectSectionsSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto s1 = sourceModel()->data(left); auto s2 = sourceModel()->data(right); auto column = left.column(); if ((column == 2 || column == 3)) return s1.toString().toULongLong(nullptr, 16) < s2.toString().toULongLong(nullptr, 16); return QString::compare(s1.toString(), s2.toString(), Qt::CaseInsensitive) < 0; } KernelObject::KernelObject() { } KernelObject::~KernelObject() { } void KernelObject::onTabChanged(int index) { switch (index) { case TAB_KERNEL_OBJECT_TYPES: ShowObjectTypes(); break; case TAB_KERNEL_OBJECT_SECTIONS: ShowObjectSections(); break; default: break; } CommonTabObject::onTabChanged(index); } bool KernelObject::eventFilter(QObject *obj, QEvent *e) { if (e->type() == QEvent::ContextMenu) { QMenu *menu = nullptr; if (obj == ui_->objectTypesView->viewport()) menu = objtypes_menu_; if (obj == ui_->objectSectionsView->viewport()) menu = objsections_menu_; QContextMenuEvent *ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt && menu) { menu->move(ctxevt->globalPos()); menu->show(); } } if (e->type() == QEvent::KeyPress) { QKeyEvent *keyevt = dynamic_cast<QKeyEvent*>(e); if (keyevt->matches(QKeySequence::Refresh)) { ShowObjectTypes(); } } return QWidget::eventFilter(obj, e); } void KernelObject::ModuleInit(Ui::Kernel *ui, Kernel *kernel) { this->ui_ = ui; Init(ui->tabObject, TAB_KERNEL, TAB_KERNEL_OBJECT); InitObjectTypesView(); InitObjectSectionsView(); } void KernelObject::InitObjectTypesView() { QTreeView *view = ui_->objectTypesView; objtypes_model_ = new QStandardItemModel; proxy_objtypes_ = new ObjectTypesSortFilterProxyModel(view); std::vector<std::pair<int, QString>> layout = { { 170, tr("TypeObject") }, { 80, tr("TypeIndex") }, { 227, tr("TypeName") }, { 110, tr("TotalObjectsNum") }, { 110, tr("TotalHandlesNum") }, }; SetDefaultTreeViewStyle(view, objtypes_model_, proxy_objtypes_, layout); view->viewport()->installEventFilter(this); view->installEventFilter(this); objtypes_menu_ = new QMenu(); objtypes_menu_->addAction(tr("Refresh"), this, [&] { ShowObjectTypes(); }, QKeySequence::Refresh); objtypes_menu_->addAction(tr("Copy"), this, [&] { auto view = ui_->objectTypesView; ClipboardCopyData(GetCurItemViewData(view, GetCurViewColumn(view)).toStdString()); }); } void KernelObject::InitObjectSectionsView() { QTreeView *view = ui_->objectSectionsView; objsections_model_ = new QStandardItemModel; proxy_objsections_ = new ObjectSectionsSortFilterProxyModel(view); std::vector<std::pair<int, QString>> layout = { { 220, tr("SectionDirectory") }, { 350, tr("SectionName") }, { 90, tr("SectionSize") }, { 80, tr("SessionID") }, { 80, tr("SessionName") }, }; SetDefaultTreeViewStyle(view, objsections_model_, proxy_objsections_, layout); view->viewport()->installEventFilter(this); view->installEventFilter(this); objsections_menu_ = new QMenu(); objsections_menu_->addAction(tr("Refresh"), this, [&] { ShowObjectSections(); }); objsections_menu_->addAction(tr("Copy"), this, [&] { auto view = ui_->objectSectionsView; ClipboardCopyData(GetCurItemViewData(view, GetCurViewColumn(view)).toStdString()); }); auto GetSectionData = [&](QTreeView *view, ULONG64 &map_addr, ULONG &map_size, HANDLE &map_hd){ map_size = map_addr = 0; std::string section_data; auto name = GetCurItemViewData(view, 1); auto size = VariantInt(GetCurItemViewData(view, 2).toStdString(), 16); auto session = GetCurItemViewData(view, 3); std::wstring prefix, section_name; std::wstring map_name; section_name = name.toStdWString(); if (session.isEmpty()) { prefix = L"Global"; map_name = UNONE::StrFormatW(L"%s\\%s", prefix.c_str(), section_name.c_str()); } else { prefix = L""; map_name = section_name; } map_hd = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, map_name.c_str()); if (!map_hd) { auto msg = UNONE::StrFormatW(L"OpenFileMappingW %s err:%d", map_name.c_str(), GetLastError()); ERR(msg.c_str()); QMessageBox::critical(NULL, tr("Error"), WStrToQ(msg)); return; } map_addr = (ULONG64)MapViewOfFileEx(map_hd, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0, NULL); if (!map_addr) map_addr = (ULONG64)MapViewOfFileEx(map_hd, FILE_MAP_READ, 0, 0, 0, NULL); if (!map_addr) { auto msg = UNONE::StrFormatW(L"MapViewOfFileEx %s err:%d", map_name.c_str(), GetLastError()); CloseHandle(map_hd); ERR(msg.c_str()); QMessageBox::critical(NULL, tr("Error"), WStrToQ(msg)); return; } map_size = size; }; objsections_menu_->addAction(tr("Dump to File"), this, [&] { ULONG64 map_addr; ULONG map_size; HANDLE map_hd; GetSectionData(ui_->objectSectionsView, map_addr, map_size, map_hd); if (!map_addr) return; std::string data((char*)map_addr, map_size); QString filename = WStrToQ(UNONE::StrFormatW(L"%X_%X", map_addr, map_size)); QString dumpmem = QFileDialog::getSaveFileName(this, tr("Save to"), filename, tr("DumpMemory(*)")); if (!dumpmem.isEmpty()) { UNONE::FsWriteFileDataW(dumpmem.toStdWString(), data) ? MsgBoxInfo(tr("Dump memory to file ok")) : MsgBoxError(tr("Dump memory to file error")); } }); objsections_menu_->addAction(tr("Memory Edit"), this, [&] { ULONG64 map_addr; ULONG map_size; HANDLE map_hd; GetSectionData(ui_->objectSectionsView, map_addr, map_size, map_hd); if (!map_addr) return; auto memrw = new KernelMemoryRW(); QList<QVariant> vars{ map_addr, (uint)map_hd}; memrw->RegFreeCallback([&](QList<QVariant> vars) { PVOID addr = (PVOID)vars[0].toLongLong(); HANDLE hd = (HANDLE)vars[1].toUInt(); UnmapViewOfFile(addr); CloseHandle(hd); }, vars); memrw->SetMaxSize(map_size); map_size = MIN(map_size, PAGE_SIZE); memrw->ViewMemory(GetCurrentProcessId(), map_addr, map_size); memrw->OpenNewWindow(qobject_cast<QWidget*>(this->parent()), map_addr, map_size); }); } void KernelObject::ShowObjectTypes() { DISABLE_RECOVER(); ClearItemModelData(objtypes_model_, 0); std::vector<ARK_OBJECT_TYPE_ITEM> items; ArkDrvApi::Object::ObjectTypeEnum(items); for (auto item : items) { auto item_0 = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%p", item.type_object))); auto item_1 = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%d", item.type_index))); auto item_2 = new QStandardItem(WStrToQ(item.type_name)); auto item_3 = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%d", item.total_objects))); auto item_4 = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"%d", item.total_handles))); auto count = objtypes_model_->rowCount(); objtypes_model_->setItem(count, 0, item_0); objtypes_model_->setItem(count, 1, item_1); objtypes_model_->setItem(count, 2, item_2); objtypes_model_->setItem(count, 3, item_3); objtypes_model_->setItem(count, 4, item_4); } } void KernelObject::ShowObjectSections() { DISABLE_RECOVER(); ClearItemModelData(objsections_model_, 0); std::vector<ARK_OBJECT_SECTION_ITEM> items; ArkDrvApi::Object::ObjectSectionEnum(items); for (auto item : items) { auto item_0 = new QStandardItem(WStrToQ(item.section_dir)); auto item_1 = new QStandardItem(WStrToQ(item.section_name)); auto item_2 = new QStandardItem(WStrToQ(UNONE::StrFormatW(L"0x%x", item.section_size))); QString idx; if (item.session_id != ARK_SESSION_GLOBAL) idx = WStrToQ(UNONE::StrFormatW(L"%d", item.session_id)); auto item_3 = new QStandardItem(idx); auto item_4 = new QStandardItem(WStrToQ(item.session_name)); auto count = objsections_model_->rowCount(); objsections_model_->setItem(count, 0, item_0); objsections_model_->setItem(count, 1, item_1); objsections_model_->setItem(count, 2, item_2); objsections_model_->setItem(count, 3, item_3); objsections_model_->setItem(count, 4, item_4); } }
9,137
C++
.cpp
227
37.770925
108
0.702137
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,189
wingui.cpp
BlackINT3_OpenArk/src/OpenArk/kernel/wingui/wingui.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "wingui.h" #include <unone.h> struct { std::string vk_str; UINT32 vk; } VkStrTables[] = { { "LBUTTON",0x01 }, { "RBUTTON",0x02 }, { "CANCEL",0x03 }, { "MBUTTON",0x04 }, { "XBUTTON1",0x05 }, { "XBUTTON2",0x06 }, { "BACK",0x08 }, { "TAB",0x09 }, { "CLEAR",0x0C }, { "RETURN",0x0D }, { "SHIFT",0x10 }, { "CONTROL",0x11 }, { "MENU",0x12 }, { "PAUSE",0x13 }, { "CAPITAL",0x14 }, { "KANA",0x15 }, { "HANGEUL",0x15 }, { "HANGUL",0x15 }, { "JUNJA",0x17 }, { "FINAL",0x18 }, { "HANJA",0x19 }, { "KANJI",0x19 }, { "ESCAPE",0x1B }, { "CONVERT",0x1C }, { "NONCONVERT",0x1D }, { "ACCEPT",0x1E }, { "MODECHANGE",0x1F }, { "SPACE",0x20 }, { "PRIOR",0x21 }, { "NEXT",0x22 }, { "END",0x23 }, { "HOME",0x24 }, { "LEFT",0x25 }, { "UP",0x26 }, { "RIGHT",0x27 }, { "DOWN",0x28 }, { "SELECT",0x29 }, { "PRINT",0x2A }, { "EXECUTE",0x2B }, { "SNAPSHOT",0x2C }, { "INSERT",0x2D }, { "DELETE",0x2E }, { "HELP",0x2F }, { "LWIN",0x5B }, { "RWIN",0x5C }, { "APPS",0x5D }, { "SLEEP",0x5F }, { "NUMPAD0",0x60 }, { "NUMPAD1",0x61 }, { "NUMPAD2",0x62 }, { "NUMPAD3",0x63 }, { "NUMPAD4",0x64 }, { "NUMPAD5",0x65 }, { "NUMPAD6",0x66 }, { "NUMPAD7",0x67 }, { "NUMPAD8",0x68 }, { "NUMPAD9",0x69 }, { "MULTIPLY",0x6A }, { "ADD",0x6B }, { "SEPARATOR",0x6C }, { "SUBTRACT",0x6D }, { "DECIMAL",0x6E }, { "DIVIDE",0x6F }, { "F1",0x70 }, { "F2",0x71 }, { "F3",0x72 }, { "F4",0x73 }, { "F5",0x74 }, { "F6",0x75 }, { "F7",0x76 }, { "F8",0x77 }, { "F9",0x78 }, { "F10",0x79 }, { "F11",0x7A }, { "F12",0x7B }, { "F13",0x7C }, { "F14",0x7D }, { "F15",0x7E }, { "F16",0x7F }, { "F17",0x80 }, { "F18",0x81 }, { "F19",0x82 }, { "F20",0x83 }, { "F21",0x84 }, { "F22",0x85 }, { "F23",0x86 }, { "F24",0x87 }, { "NUMLOCK",0x90 }, { "SCROLL",0x91 }, { "OEM_NEC_EQUAL",0x92 }, { "OEM_FJ_JISHO",0x92 }, { "OEM_FJ_MASSHOU",0x93 }, { "OEM_FJ_TOUROKU",0x94 }, { "OEM_FJ_LOYA",0x95 }, { "OEM_FJ_ROYA",0x96 }, { "LSHIFT",0xA0 }, { "RSHIFT",0xA1 }, { "LCONTROL",0xA2 }, { "RCONTROL",0xA3 }, { "LMENU",0xA4 }, { "RMENU",0xA5 }, { "BROWSER_BACK",0xA6 }, { "BROWSER_FORWARD",0xA7 }, { "BROWSER_REFRESH",0xA8 }, { "BROWSER_STOP",0xA9 }, { "BROWSER_SEARCH",0xAA }, { "BROWSER_FAVORITES",0xAB }, { "BROWSER_HOME",0xAC }, { "VOLUME_MUTE",0xAD }, { "VOLUME_DOWN",0xAE }, { "VOLUME_UP",0xAF }, { "MEDIA_NEXT_TRACK",0xB0 }, { "MEDIA_PREV_TRACK",0xB1 }, { "MEDIA_STOP",0xB2 }, { "MEDIA_PLAY_PAUSE",0xB3 }, { "LAUNCH_MAIL",0xB4 }, { "LAUNCH_MEDIA_SELECT",0xB5 }, { "LAUNCH_APP1",0xB6 }, { "LAUNCH_APP2",0xB7 }, { "OEM_1",0xBA }, { "OEM_PLUS",0xBB }, { "OEM_COMMA",0xBC }, { "OEM_MINUS",0xBD }, { "OEM_PERIOD",0xBE }, { "OEM_2",0xBF }, { "OEM_3",0xC0 }, { "OEM_4",0xDB }, { "OEM_5",0xDC }, { "OEM_6",0xDD }, { "OEM_7",0xDE }, { "OEM_8",0xDF }, { "OEM_AX",0xE1 }, { "OEM_102",0xE2 }, { "ICO_HELP",0xE3 }, { "ICO_00",0xE4 }, { "PROCESSKEY",0xE5 }, { "ICO_CLEAR",0xE6 }, { "PACKET",0xE7 }, { "OEM_RESET",0xE9 }, { "OEM_JUMP",0xEA }, { "OEM_PA1",0xEB }, { "OEM_PA2",0xEC }, { "OEM_PA3",0xED }, { "OEM_WSCTRL",0xEE }, { "OEM_CUSEL",0xEF }, { "OEM_ATTN",0xF0 }, { "OEM_FINISH",0xF1 }, { "OEM_COPY",0xF2 }, { "OEM_AUTO",0xF3 }, { "OEM_ENLW",0xF4 }, { "OEM_BACKTAB",0xF5 }, { "ATTN",0xF6 }, { "CRSEL",0xF7 }, { "EXSEL",0xF8 }, { "EREOF",0xF9 }, { "PLAY",0xFA }, { "ZOOM",0xFB }, { "NONAME",0xFC }, { "PA1",0xFD }, { "OEM_CLEAR",0xFE } }; std::string HotkeyVkToString(UINT32 vk, UINT16 mod1, UINT16 mod2) { std::string vks; if (mod1 & MOD_WIN) vks.append("+Win"); if (mod1 & MOD_CONTROL) vks.append("+Ctrl"); if (mod1 & MOD_ALT) vks.append("+Alt"); if (mod1 & MOD_SHIFT) vks.append("+Shift"); //if (mod2 & MOD_NOREPEAT) vks.append("[NoRepeat]"); if (vk >= 0x30 && vk <= 0x5A) { vks.append("+"); vks.push_back((char)vk); } else { if (vk) { std::string cap; for (auto t : VkStrTables) { if (t.vk == vk) { cap = UNONE::StrToLowerA(t.vk_str); cap[0] -= 32; vks.append("+" + cap); break; } } if (cap.empty()) vks.append(UNONE::StrFormatA("+(Unknown VK:%d)", vk)); } } vks = UNONE::StrTrimA(vks, "+"); return std::move(vks); }
4,801
C++
.cpp
208
21.783654
77
0.572082
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,190
openark.cpp
BlackINT3_OpenArk/src/OpenArk/openark/openark.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "openark.h" #include "common/common.h" #include "process-mgr/process-mgr.h" #include "scanner/scanner.h" #include "coderkit/coderkit.h" #include "bundler/bundler.h" #include "settings/settings.h" #include "about/about.h" #include "cmds/cmds.h" #include "kernel/kernel.h" #include "reverse/reverse.h" #include "utilities/utilities.h" #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #define APP_CHKUPT_SERVER "http://upt.blackint3.com/openark/version.txt" #define APP_MESSAGE_PATTERN \ "%{if-debug}<font color=#E0E2E4>%{endif}"\ "%{if-info}<font color=#E0E2E4>%{endif}"\ "%{if-warning}<font color=red>%{endif}"\ "%{if-critical}<font color=red>%{endif}"\ "[%{function}:%{line}]"\ "%{if-debug}[DBG]%{endif}%{if-info}[INFO]%{endif}%{if-warning}[WARN]%{endif}%{if-critical}[ERR]%{endif}"\ "%{message}</font>" void QtMessageHandlerCallback(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QString fmt = msg; if (!msg.isEmpty()) { fmt = qFormatLogMessage(type, context, msg); } openark->onLogOutput(fmt); } OpenArk::OpenArk(QWidget *parent) : QMainWindow(parent) { openark = this; qSetMessagePattern(APP_MESSAGE_PATTERN); qInstallMessageHandler(QtMessageHandlerCallback); UNONE::InterRegisterLogger([&](const std::wstring &log) { onLogOutput(WStrToQ(log)); }); ui.setupUi(this); int x, y, w, h; OpenArkConfig::Instance()->GetMainGeometry(x, y, w, h); move(x, y); resize(w, h); bool maxed = false; OpenArkConfig::Instance()->GetMainMaxed(maxed); if (maxed) showMaximized(); ui.splitter->setStretchFactor(0, 1); ui.splitter->setStretchFactor(1, 5); QString title = QString(tr("OpenArk v%1 ").arg(AppVersion())); title.append(tr(" [build:%1] ").arg(AppBuildTime())); UNONE::PeX64((CHAR*)GetModuleHandleW(NULL)) ? title.append(tr("64-Bit")) : title.append(tr("32-Bit")); setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint); setWindowTitle(title); QWidget *widget = new QWidget(); QLabel *link = new QLabel(widget); link->setText("<a style='color:blue;a{text-decoration: none}' href=\"https://github.com/BlackINT3/OpenArk\">"+ tr("Project on Github")+"</a>&nbsp;"); link->setOpenExternalLinks(true); stool_ = new QToolBar(widget); stool_->setObjectName(QStringLiteral("statusToolBar")); stool_->setIconSize(QSize(16, 16)); stool_->addAction(ui.actionConsole); stool_->addSeparator(); stool_->addAction(ui.actionModule); stool_->addAction(ui.actionHandle); stool_->addAction(ui.actionMemory); ui.actionModule->setChecked(false); ui.actionHandle->setChecked(false); ui.actionMemory->setChecked(false); connect(ui.actionModule, SIGNAL(triggered(bool)), this, SLOT(onActionPtool(bool))); connect(ui.actionHandle, SIGNAL(triggered(bool)), this, SLOT(onActionPtool(bool))); connect(ui.actionMemory, SIGNAL(triggered(bool)), this, SLOT(onActionPtool(bool))); //stool_->setStyleSheet("background-color:red"); QGridLayout *layout = new QGridLayout(widget); layout->setMargin(0); layout->addWidget(stool_, 0, 0, 1, 1, Qt::AlignVCenter | Qt::AlignLeft); layout->addWidget(link, 0, 1, 1, 1, Qt::AlignVCenter | Qt::AlignRight); //ui.statusBar->setStyleSheet("QToolButton: {background-color: red; }"); ui.statusBar->setSizeGripEnabled(false); ui.statusBar->setFixedHeight(28); ui.statusBar->addWidget(widget, 1); connect(ui.actionConsole, SIGNAL(triggered(bool)), this, SLOT(onActionConsole(bool))); ui.consoleWidget->hide(); ui.actionOnTop->setCheckable(true); ui.actionExit->setShortcut(QKeySequence(Qt::ALT + Qt::Key_F4)); // Language QActionGroup *langs = new QActionGroup(this); langs->setExclusive(true); langs->addAction(ui.actionEnglish); langs->addAction(ui.actionZhcn); int lang = OpenArkLanguage::Instance()->GetLanguage(); if (lang == 0) { ui.actionEnglish->setChecked(true); } else if (lang == 1) { ui.actionZhcn->setChecked(true); } connect(langs, SIGNAL(triggered(QAction*)), this, SLOT(onActionLanguage(QAction*))); connect(ui.actionRun, &QAction::triggered, this, [=]() { UNONE::PsCreateProcessW(L"rundll32.exe shell32.dll,#61"); }); connect(ui.actionExit, &QAction::triggered, this, [=]() { QApplication::quit(); }); connect(ui.actionAbout, SIGNAL(triggered(bool)), this, SLOT(onActionAbout(bool))); connect(ui.actionSettings, SIGNAL(triggered(bool)), this, SLOT(onActionSettings(bool))); connect(ui.actionOpen, SIGNAL(triggered(bool)), this, SLOT(onActionOpen(bool))); connect(ui.actionRefresh, SIGNAL(triggered(bool)), this, SLOT(onActionRefresh(bool))); connect(ui.actionReset, SIGNAL(triggered(bool)), this, SLOT(onActionReset(bool))); connect(ui.actionOnTop, SIGNAL(triggered(bool)), this, SLOT(onActionOnTop(bool))); connect(ui.actionGithub, SIGNAL(triggered(bool)), this, SLOT(onActionGithub(bool))); connect(ui.actionManuals, SIGNAL(triggered(bool)), this, SLOT(onActionManuals(bool))); connect(ui.actionCheckUpdate, SIGNAL(triggered(bool)), this, SLOT(onActionCheckUpdate(bool))); connect(ui.actionCoderKit, SIGNAL(triggered(bool)), this, SLOT(onActionCoderKit(bool))); connect(ui.actionScanner, SIGNAL(triggered(bool)), this, SLOT(onActionScanner(bool))); connect(ui.actionBundler, SIGNAL(triggered(bool)), this, SLOT(onActionBundler(bool))); cmds_ = new Cmds(ui.cmdOutWindow); cmds_->hide(); cmds_->setParent(ui.cmdOutWindow); ui.cmdInput->installEventFilter(this); ui.cmdOutWindow->installEventFilter(this); ui.cmdOutWindow->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui.cmdInput, SIGNAL(returnPressed()), this, SLOT(onCmdInput())); connect(ui.cmdButton, SIGNAL(clicked()), this, SLOT(onCmdHelp())); connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int))); connect(ui.cmdOutWindow, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(onShowConsoleMenu(const QPoint &))); int main_idx = 1; QVector<int> level2_idx; QVector<QVector<int>> idxs; OpenArkConfig::Instance()->GetPrefMainTab(main_idx); OpenArkConfig::Instance()->GetMainTabAllMap(idxs); auto CreateTabPage = [&](QWidget *widget, QWidget *origin) { int idx = ui.tabWidget->indexOf(origin); QString text = ui.tabWidget->tabText(idx); ui.tabWidget->removeTab(idx); ui.tabWidget->insertTab(idx, widget, text); }; auto processmgr = new ProcessMgr(this); CreateTabPage(processmgr, ui.tabProcessMgr); auto scanner = new Scanner(this, TAB_SCANNER); CreateTabPage(scanner, ui.tabScanner); auto coderkit = new CoderKit(this, TAB_CODERKIT); CreateTabPage(coderkit, ui.tabCoderKit); auto bundler = new Bundler(this); CreateTabPage(bundler, ui.tabBundler); auto kernel = new Kernel(this, TAB_KERNEL); CreateTabPage(kernel, ui.tabKernel); auto utilities = new Utilities(this, TAB_UTILITIES); CreateTabPage(utilities, ui.tabUtilities); auto reverse = new Reverse(this, TAB_REVERSE); CreateTabPage(reverse, ui.tabReverse); for (int tab = 0; tab < TAB_MAX; tab++) { level2_idx = idxs[tab]; switch (tab) { case TAB_KERNEL: kernel->SetActiveTab(level2_idx); break; case TAB_CODERKIT: coderkit->SetActiveTab(level2_idx); break; case TAB_SCANNER: scanner->SetActiveTab(level2_idx); break; case TAB_UTILITIES: utilities->SetActiveTab(level2_idx); break; case TAB_REVERSE: reverse->SetActiveTab(level2_idx); break; } } SetActiveTab(main_idx); chkupt_timer_ = new QTimer(); chkupt_timer_->setInterval(1000); chkupt_timer_->start(); connect(chkupt_timer_, &QTimer::timeout, this, [&]() { onActionCheckUpdate(false); chkupt_timer_->stop(); }); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); this->installEventFilter(this); } bool OpenArk::eventFilter(QObject *obj, QEvent *e) { bool filtered = false; if (obj == ui.cmdInput) { if (e->type() == QEvent::KeyPress) { filtered = true; QKeyEvent* keyevt = dynamic_cast<QKeyEvent*>(e); if (keyevt->key() == Qt::Key_Up) { ui.cmdInput->setText(cmds_->CmdGetLast()); } else if (keyevt->key() == Qt::Key_Down) { ui.cmdInput->setText(cmds_->CmdGetNext()); } else if (keyevt->key() == Qt::Key_Tab) { ui.cmdOutWindow->setFocus(); } else { filtered = false; } } } else if (obj == ui.cmdOutWindow) { if (e->type() == QEvent::KeyPress) { filtered = true; QKeyEvent* keyevt = dynamic_cast<QKeyEvent*>(e); if (keyevt->key() == Qt::Key_Tab) { ui.cmdInput->setFocus(); } else { filtered = false; } } } else if (obj == this) { if (e->type() == QEvent::Resize) { auto evt = dynamic_cast<QResizeEvent*>(e); old_window_size_ = evt->oldSize(); OpenArkConfig::Instance()->SetMainGeometry(-1, -1, evt->size().width(), evt->size().height()); } else if (e->type() == QEvent::Move) { auto evt = dynamic_cast<QMoveEvent*>(e); old_window_pos_ = evt->oldPos(); OpenArkConfig::Instance()->SetMainGeometry(evt->pos().x() - 8, evt->pos().y() - 31, -1, -1); } } if (filtered) { QKeyEvent* keyevt = dynamic_cast<QKeyEvent*>(e); keyevt->ignore(); return true; } return QWidget::eventFilter(obj, e); } void OpenArk::changeEvent(QEvent *e) { if (e->type() != QEvent::WindowStateChange) return; if (windowState() == Qt::WindowMaximized) { OpenArkConfig::Instance()->SetMainGeometry(old_window_pos_.x(), old_window_pos_.y(), old_window_size_.width(), old_window_size_.height()); OpenArkConfig::Instance()->SetMainMaxed(true); } else if (windowState() != Qt::WindowMinimized) { OpenArkConfig::Instance()->SetMainMaxed(false); } } void OpenArk::onActionOpen(bool checked) { QString file = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("All Files (*.*)")); if (file.isEmpty()) return; QMetaObject::invokeMethod(ui.tabWidget->currentWidget(), "onOpenFile", Qt::QueuedConnection, Q_ARG(QString, file)); } void OpenArk::onActionRefresh(bool checked) { QMetaObject::invokeMethod(ui.tabWidget->currentWidget(), "onRefresh", Qt::QueuedConnection); } void OpenArk::onActionReset(bool checked) { QMetaObject::invokeMethod(ui.tabWidget->currentWidget(), "onReset", Qt::QueuedConnection); } void OpenArk::onActionOnTop(bool checked) { HWND wnd = (HWND)winId(); if (checked) { SetWindowOnTop(wnd, true); } else { SetWindowOnTop(wnd, false); } } void OpenArk::onActionAbout(bool checked) { auto about = new About(this); about->raise(); about->show(); } void OpenArk::onActionSettings(bool checked) { auto about = new Settings(this); about->raise(); about->show(); } void OpenArk::onActionConsole(bool checked) { QAction* sender = qobject_cast<QAction*>(QObject::sender()); if (sender->isChecked()) { ui.consoleWidget->show(); ui.cmdInput->setFocus(); } else { ui.consoleWidget->hide(); } } void OpenArk::onActionPtool(bool checked) { QAction* sender = qobject_cast<QAction*>(QObject::sender()); if (!sender->isChecked()) { emit signalShowPtool(-1); return; } if (sender == ui.actionModule) { emit signalShowPtool(0); ui.actionHandle->setChecked(false); ui.actionMemory->setChecked(false); return; } if (sender == ui.actionHandle) { emit signalShowPtool(1); ui.actionModule->setChecked(false); ui.actionMemory->setChecked(false); return; } if (sender == ui.actionMemory) { emit signalShowPtool(2); ui.actionModule->setChecked(false); ui.actionHandle->setChecked(false); return; } } void OpenArk::onActionManuals(bool checked) { ShellOpenUrl("https://openark.blackint3.com/manuals/"); } void OpenArk::onActionGithub(bool checked) { ShellOpenUrl("https://github.com/BlackINT3/OpenArk/"); } void OpenArk::onActionCheckUpdate(bool checked) { QString url = APP_CHKUPT_SERVER; QNetworkRequest req; req.setUrl(QUrl(url)); QNetworkAccessManager *mgr = new QNetworkAccessManager(this); QNetworkReply *reply = mgr->get(req); INFO(L"requset server:%s", url.toStdWString().c_str()); connect(reply, &QNetworkReply::finished, [this, reply, checked]() { if (reply->error() != QNetworkReply::NoError) { auto err = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); ERR(L"request http.err:%d, net.err:%d", err.toInt(), (int)reply->error()); return; } QByteArray data = reply->readAll(); QJsonValue val; QJsonObject obj; INFO("server responsed:%s", data.toStdString().c_str()); if (!JsonParse(data, obj) || !JsonGetValue(obj, "err", val)) { ERR(L"request app-err: json invalid"); return; } if (val.toInt() != 0) { ERR(L"request app-err: %d", val.toInt()); return; } QJsonValue appver, appbd, appurl, appfsurl; if (!JsonGetValue(obj, "appver", appver) || !JsonGetValue(obj, "appbd", appbd) || !JsonGetValue(obj, "appurl", appurl)) { ERR(L"request json err: %d", val.toInt()); return; } if (JsonGetValue(obj, "appfsurl", appfsurl)) { AppFsUrl(appfsurl.toString()); } auto local_ver = AppVersion(); auto local_bd = AppBuildTime(); INFO(L"local appver:%s, build:%s", local_ver.toStdWString().c_str(), local_bd.toStdWString().c_str()); if (local_ver.isEmpty() || local_bd.isEmpty()) { return; } if (local_ver < appver.toString() || local_bd < appbd.toString()) { QString tips = QString(tr("Found new version, app should be updated.\nappver: %1\nappbd: %2\nappurl: %3") .arg(appver.toString()) .arg(appbd.toString()) .arg(appurl.toString())); QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("App Updates"), tips, QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { ShellOpenUrl(appurl.toString()); } return; } if (checked) MsgBoxInfo(tr("OpenArk is latest.")); INFO(L"OpenArk is latest."); reply->deleteLater(); }); } void OpenArk::onActionLanguage(QAction *act) { auto lang = OpenArkLanguage::Instance()->GetLanguage(); auto text = act->text(); if (act == ui.actionEnglish) { if (lang == 0) return; lang = 0; } else if (act == ui.actionZhcn) { if (lang == 1) return; lang = 1; } else { return; } QString tips = tr("Language changed ok, did you restart application now?"); OpenArkConfig::Instance()->GetLang(CONF_SET, lang); QMessageBox::StandardButton reply; reply = QMessageBox::information(this, tr("Information"), tips, QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { onExecCmd(L".restart"); } } void OpenArk::onActionCoderKit(bool checked) { SetActiveTab(TAB_CODERKIT); } void OpenArk::onActionScanner(bool checked) { SetActiveTab(TAB_SCANNER); } void OpenArk::onActionBundler(bool checked) { SetActiveTab(TAB_BUNDLER); } void OpenArk::onLogOutput(QString log) { log.replace("\n", "<br/>"); log.replace("err", "<font color=red>err</font>"); log.replace("error", "<font color=red>error</font>"); log.replace("ERR", "<font color=red>ERR</font>"); log.replace("ERROR", "<font color=red>ERROR</font>"); log = QString("<font color=#E0E2E4>%1</font>").arg(log); ui.cmdOutWindow->append(log); } void OpenArk::onExecCmd(const std::wstring &cmdline) { cmds_->CmdDispatcher(cmdline); } void OpenArk::onOpen(QString path) { QMetaObject::invokeMethod(ui.tabWidget->currentWidget(), "onOpenFile", Qt::QueuedConnection, Q_ARG(QString, path)); } void OpenArk::onCmdHelp() { onExecCmd(L".help"); } void OpenArk::onShowConsoleMenu(const QPoint &pt) { QMenu *menu = ui.cmdOutWindow->createStandardContextMenu(); menu->addSeparator(); menu->addAction(tr("History"), this, SLOT(onConsoleHistory())); menu->addAction(tr("Helps"), this, SLOT(onConsoleHelps())); menu->addAction(tr("Clear"), this, SLOT(onConsoleClear())); menu->exec(ui.cmdOutWindow->mapToGlobal(pt)); delete menu; } void OpenArk::onConsoleHistory() { onExecCmd(L".history"); } void OpenArk::onConsoleClear() { onExecCmd(L".cls"); } void OpenArk::onConsoleHelps() { onExecCmd(L".help"); } void OpenArk::onCmdInput() { QLineEdit* sender = qobject_cast<QLineEdit*>(QObject::sender()); std::wstring input = sender->text().toStdWString(); if (input.empty()) input = cmds_->CmdGetLast().toStdWString(); onExecCmd(input); auto scroll = ui.cmdOutWindow->verticalScrollBar(); scroll->setSliderPosition(scroll->maximum()); sender->clear(); } void OpenArk::onTabChanged(int idx) { if (idx == TAB_PROCESS) onActionRefresh(true); OpenArkConfig::Instance()->SetPrefMainTab(idx); switch (idx) { case TAB_KERNEL: case TAB_CODERKIT: case TAB_SCANNER: case TAB_UTILITIES: case TAB_REVERSE: auto obj = ui.tabWidget->currentWidget(); auto xxx = obj->objectName(); if (obj->objectName().contains("tab")) break; qint32 l2; qRegisterMetaType<qint32>("qint32"); QMetaObject::invokeMethod(obj, "GetActiveTab", Qt::DirectConnection, Q_RETURN_ARG(qint32, l2)); OpenArkConfig::Instance()->SetPrefLevel2Tab(l2); QMetaObject::invokeMethod(obj, "RefreshTab", Qt::DirectConnection); break; } } void OpenArk::StatusBarClear() { } void OpenArk::StatusBarAdd(QWidget *label) { stool_->addSeparator(); stool_->addWidget(label); }
17,649
C++
.cpp
491
33.659878
150
0.718141
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,191
bundler.cpp
BlackINT3_OpenArk/src/OpenArk/bundler/bundler.cpp
#include "bundler.h" #include "../common/common.h" #include "../openark/openark.h" #include "pack/pack.h" #include "icons/icons.h" #include <QFile> Bundler::Bundler(QWidget *parent) : parent_((OpenArk*)parent) { ui.setupUi(this); connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); }); ui.folderLabel->installEventFilter(this); ui.folderLabel->setCursor(Qt::PointingHandCursor); setAcceptDrops(true); QTableView *filesView = ui.filesView; files_model_ = new QStandardItemModel; SetDefaultTableViewStyle(filesView, files_model_); filesView->viewport()->installEventFilter(this); files_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Size(KB)") << tr("Path")); files_menu_ = new QMenu(); files_menu_->addAction(tr("Use the ICON"), this, SLOT(onUseIcon())); connect(ui.openBtn, SIGNAL(clicked()), this, SLOT(onOpenFolder())); connect(ui.selectIconBtn, SIGNAL(clicked()), this, SLOT(onSelectIcon())); connect(ui.saveBtn, SIGNAL(clicked()), this, SLOT(onSaveTo())); } Bundler::~Bundler() { } bool Bundler::eventFilter(QObject *obj, QEvent *e) { if (obj == ui.folderLabel) { if (e->type() == QEvent::MouseButtonPress) { ShellExecuteW(NULL, L"open", files_folder_.toStdWString().c_str(), NULL, NULL, SW_SHOW); } } else if (obj == ui.filesView->viewport()) { if (e->type() == QEvent::ContextMenu) { QContextMenuEvent* ctxevt = dynamic_cast<QContextMenuEvent*>(e); if (ctxevt != nullptr) { files_menu_->move(ctxevt->globalPos()); files_menu_->show(); } } } return QWidget::eventFilter(obj, e); } void Bundler::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } void Bundler::dropEvent(QDropEvent *event) { if (!event->mimeData()->hasUrls()) return; QString& path = event->mimeData()->urls()[0].toLocalFile(); if (!UNONE::FsIsDirW(path.toStdWString())) return; OpenFolderImpl(path); } void Bundler::onRefresh() { OpenFolderImpl(files_folder_); } void Bundler::onOpenFolder() { QString folder = QFileDialog::getExistingDirectory(this, tr("Open Folder"), ""); if (folder.isEmpty()) return; OpenFolderImpl(folder); } void Bundler::onSelectIcon() { QString file = QFileDialog::getOpenFileName(this, tr("Select ICON"), "", tr("ico/exe (*.exe;*.ico)")); if (file.isEmpty()) return; SelectIconImpl(file); } void Bundler::onUseIcon() { auto idx = ui.filesView->currentIndex(); auto name = GetItemModelData(files_model_, idx.row(), 2); auto path = files_folder_ + "/" + name.replace("./", ""); SelectIconImpl(path); } void Bundler::onSaveTo() { QString bundle = QFileDialog::getSaveFileName(this,tr("Save to"),"",tr("BundleFile(*.exe)")); if (bundle.isEmpty()) return; std::vector<std::wstring> files; std::vector<std::wstring> names; for (int i = 0; i < files_model_->rowCount(); i++) { QString name = GetItemModelData(files_model_, i, 2); name.replace("./", ""); names.push_back(name.toStdWString()); QString path = files_folder_ + "/" + name; files.push_back(path.toStdWString()); } std::wstring script = ui.scriptEdit->toPlainText().toStdWString(); std::string bdata; BundleError err = BundlePack(UNONE::FsPathToNameW(files_folder_.toStdWString()), files, names, script, bdata); if (err != BERR_OK) { qDebug() << tr("Build err") << err; MsgBoxError(tr("Build bundle file err")); return; } QFile f(":/OpenArk/BundlerShell.exe"); f.open(QIODevice::ReadOnly); auto&& shell = f.readAll().toStdString(); UNONE::FsWriteFileDataW(bundle.toStdWString(), shell); std::string icondata; if (GetIconData(icon_file_.toStdWString(), icondata) && !icondata.empty()) { SetIconData(bundle.toStdWString(), icondata); } HANDLE upt = BeginUpdateResourceW(bundle.toStdWString().c_str(), FALSE); if (!upt) { qDebug() << tr("BeginUpdateResourceW err") << GetLastError(); MsgBoxError(tr("BeginUpdateResourceW err")); return; } if (!UpdateResourceW(upt, IDS_BUDE, MAKEINTRESOURCEW(IDX_BUDE), MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPVOID)bdata.data(), bdata.size())) { qDebug() << tr("UpdateResourceW err") << GetLastError(); MsgBoxError(tr("UpdateResourceW err")); return; } EndUpdateResource(upt, FALSE); MsgBoxInfo(QString(tr("Build %1 ok").arg(bundle))); UNONE::FsWriteFileDataA("c:/xxx.bd", bdata); /* std::string d1; std::wstring sc; std::wstring outdir = L"i:/5566"; BundleUnpack(outdir, bdata.c_str(), sc); */ } void Bundler::OpenFolderImpl(QString folder) { if (folder.isEmpty()) return; //folder.replace("/", "\\"); files_folder_ = folder; ui.folderLabel->setText(folder); ClearItemModelData(files_model_); UNONE::DirEnumCallbackW fcb = [&](wchar_t* path, wchar_t* name, void* param)->bool { if (UNONE::FsIsDirW(path)) { UNONE::FsEnumDirectoryW(path, fcb, param);; return true; } InitTableItem(files_model_); AppendTableIconItem(files_model_, LoadIcon(WCharsToQ(path)), WCharsToQ(name)); DWORD64 size; UNONE::FsGetFileSizeW(path, size); AppendTableItem(files_model_, WStrToQ(UNONE::StrFormatW(L"%.2f", ((double)size) / 1024))); std::wstring p(path); UNONE::StrReplaceW(p, folder.toStdWString(), L"."); UNONE::StrReplaceW(p, L"\\", L"/"); AppendTableItem(files_model_, WStrToQ(p)); return true; }; UNONE::FsEnumDirectoryW(folder.toStdWString(), fcb); } void Bundler::SelectIconImpl(QString icon) { icon_file_ = icon; ui.iconLabel->setPixmap(LoadIcon(icon).pixmap(24, 24)); }
5,500
C++
.cpp
163
31.539877
115
0.709447
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,192
icons.cpp
BlackINT3_OpenArk/src/OpenArk/bundler/icons/icons.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "icons.h" #include <unone.h> using namespace std; //#define FIELD_OFFSET(type, field) ((ULONG)&(((type *)0)->field)) typedef struct { BYTE bWidth; // Width, in pixels, of the image BYTE bHeight; // Height, in pixels, of the image BYTE bColorCount; // Number of colors in image (0 if >=8bpp) BYTE bReserved; // Reserved ( must be 0) WORD wPlanes; // Color Planes WORD wBitCount; // Bits per pixel DWORD dwBytesInRes; // How many bytes in this resource? DWORD dwImageOffset; // Where in the file is this image? } ICONDIRENTRY, *LPICONDIRENTRY; typedef struct { WORD idReserved; // Reserved (must be 0) WORD idType; // Resource Type (1 for icons) WORD idCount; // How many images? //ICONDIRENTRY idEntries[1]; // An entry for each image (idCount of 'em) } ICONDIR, *LPICONDIR; #pragma pack( push ) #pragma pack( 2 ) typedef struct { BYTE bWidth; // Width, in pixels, of the image BYTE bHeight; // Height, in pixels, of the image BYTE bColorCount; // Number of colors in image (0 if >=8bpp) BYTE bReserved; // Reserved WORD wPlanes; // Color Planes WORD wBitCount; // Bits per pixel DWORD dwBytesInRes; // how many bytes in this resource? WORD nID; // the ID } GRPICONDIRENTRY, *LPGRPICONDIRENTRY; #pragma pack( pop ) // #pragmas are used here to insure that the structure's // packing in memory matches the packing of the EXE or DLL. #pragma pack( push ) #pragma pack( 2 ) typedef struct { WORD idReserved; // Reserved (must be 0) WORD idType; // Resource type (1 for icons) WORD idCount; // How many images? GRPICONDIRENTRY idEntries[1]; // The entries for each image } GRPICONDIR, *LPGRPICONDIR; #pragma pack( pop ) typedef struct { LPCSTR ResType; LPCSTR ResName; DWORD ResSize; WORD ResLanguage; } RESINFO, *PRESINFO; BOOL CALLBACK EnumFirstResProc(HMODULE hModule, LPCSTR lpszType, LPSTR lpszName, LONG_PTR lParam) { if (IS_INTRESOURCE(lpszName)) sprintf_s((CHAR*)lParam, MAX_PATH, "#%d", (USHORT)lpszName); else strncpy_s((CHAR*)lParam, MAX_PATH, lpszName, MAX_PATH - 1); return FALSE; } BOOL CALLBACK EnumLastResIdProc(HMODULE hModule, LPCSTR lpszType, LPSTR lpszName, LONG_PTR lParam) { if (IS_INTRESOURCE(lpszName)) sprintf_s((CHAR*)lParam, MAX_PATH, "#%d", (USHORT)lpszName); return TRUE; } BOOL CALLBACK EnumFirstResLangProc(HMODULE hModule, LPCSTR lpszType, LPCSTR lpszName, WORD wIDLanguage, LONG_PTR lParam) { *(WORD*)lParam = wIDLanguage; return FALSE; } bool GetResLanguage(HMODULE Module, LPCSTR ResType, LPCSTR ResName, WORD& Language) { return EnumResourceLanguagesA(Module, (LPCSTR)RT_GROUP_ICON, ResName, EnumFirstResLangProc, (LONG_PTR)&Language) ? true : false; } bool GetResData(HMODULE Module, LPCSTR ResType, LPCSTR ResName, LPVOID& Data, DWORD& Size) { HRSRC Res = FindResourceA(Module, ResName, ResType); if (!Res) return false; HGLOBAL Global = LoadResource(Module, Res); if (!Global) return false; Size = SizeofResource(Module, Res); Data = LockResource(Global); if (!Data) return false; return true; } bool SetResData(HANDLE Update, LPCSTR ResType, LPCSTR ResName, LPVOID& Data, DWORD& Size, WORD wLanguage = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT)) { return UpdateResourceA(Update, ResType, ResName, wLanguage, Data, Size) ? true : false; } bool DeleteResData(HANDLE Update, LPCSTR ResType, LPCSTR ResName, WORD ResLanguage) { return UpdateResourceA(Update, ResType, ResName, ResLanguage, NULL, 0) ? true : false; return true; } bool GetIconData(const std::wstring& ExePath, std::string& IconData) { bool Result = false; HMODULE Module = NULL; LPICONDIRENTRY IconEntry = NULL; if (ExePath.empty()) return false; int pos = ExePath.find_last_of(L"."); if (pos != std::wstring::npos && ExePath.substr(pos) == L".ico") { return UNONE::FsReadFileDataW(ExePath, IconData); } do { Module = LoadLibraryExW(ExePath.c_str(), NULL, LOAD_LIBRARY_AS_DATAFILE); if (!Module) break; CHAR ResGroupName[MAX_PATH] = { 0 }; if (!EnumResourceNamesA(Module, (LPCSTR)RT_GROUP_ICON, EnumFirstResProc, (LONG_PTR)ResGroupName) && GetLastError() == ERROR_RESOURCE_TYPE_NOT_FOUND) break; LPCSTR ResName = NULL; if (ResGroupName[0] == '#') ResName = MAKEINTRESOURCEA(atoi(&ResGroupName[1])); else ResName = ResGroupName; LPGRPICONDIR ResGroupData = NULL; DWORD ResGroupSize = 0; if (!GetResData(Module, (LPCSTR)RT_GROUP_ICON, ResName, (LPVOID&)ResGroupData, ResGroupSize)) break; DWORD Count = ResGroupData->idCount; ICONDIR IconDir; memcpy(&IconDir, ResGroupData, sizeof(ICONDIR)); DWORD Offset = 0, Size = 0; IconEntry = new(std::nothrow) ICONDIRENTRY[Count]; if (!IconEntry) break; Offset += sizeof(ICONDIR) + sizeof(ICONDIRENTRY)*Count; for (DWORD i = 0; i < Count; i++) { memcpy(&IconEntry[i], &ResGroupData->idEntries[i], sizeof(GRPICONDIRENTRY)); LPVOID IconItem = NULL; DWORD IconItemSize = 0; GetResData(Module, (LPCSTR)RT_ICON, MAKEINTRESOURCEA(ResGroupData->idEntries[i].nID), IconItem, IconItemSize); Size = Offset + IconItemSize; IconData.resize(Size); memcpy(&IconData[Offset], IconItem, IconItemSize); IconEntry[i].dwImageOffset = Offset; IconEntry[i].dwBytesInRes = IconItemSize; Offset += IconItemSize; UnlockResource(IconItem); } UnlockResource(ResGroupData); memcpy(&IconData[0], &IconDir, sizeof(ICONDIR)); memcpy(&IconData[sizeof(ICONDIR)], IconEntry, sizeof(ICONDIRENTRY)*Count); Result = true; } while (0); if (Module) FreeLibrary(Module); if (IconEntry) delete[] IconEntry; return Result; } bool SetIconData(const std::wstring& ExePath, std::string& IconData) { bool Result = false; HMODULE Module = NULL; LPICONDIRENTRY IconEntry = NULL; if (ExePath.empty()) return false; LPGRPICONDIR ResGroupData = NULL; BOOL IsGroupExsited = FALSE; LPCSTR GroupName = NULL; WORD OriResLang = 0; Module = LoadLibraryExW(ExePath.c_str(), NULL, LOAD_LIBRARY_AS_DATAFILE); if (!Module) return false; do { CHAR Name[MAX_PATH] = { 0 }; if (!EnumResourceNamesA(Module, (LPCSTR)RT_GROUP_ICON, EnumFirstResProc, (LONG_PTR)Name)) break; if (Name[0] == '#') GroupName = MAKEINTRESOURCEA(atoi(&Name[1])); else GroupName = Name; DWORD ResGroupSize = 0; GetResData(Module, (LPCSTR)RT_GROUP_ICON, GroupName, (LPVOID&)ResGroupData, ResGroupSize); GetResLanguage(Module, (LPCSTR)RT_GROUP_ICON, GroupName, OriResLang); IsGroupExsited = TRUE; } while (0); GRPICONDIR TempGroupData; if (!IsGroupExsited) { ResGroupData = &TempGroupData; ResGroupData->idCount = 0; GroupName = MAKEINTRESOURCEA(1); } vector<DWORD> AddResId; vector<RESINFO> DelResInfo; LPICONDIR IconDir = (LPICONDIR)&IconData[0]; LPICONDIRENTRY IconDirEntry = (LPICONDIRENTRY)&IconData[sizeof(ICONDIR)]; for (DWORD i = 0; i < ResGroupData->idCount; i++) { RESINFO Info = { (LPCSTR)RT_ICON, MAKEINTRESOURCEA(ResGroupData->idEntries[i].nID), ResGroupData->idEntries[i].dwBytesInRes, OriResLang }; DelResInfo.push_back(Info); } if (IconDir->idCount == ResGroupData->idCount) { for (DWORD i = 0; i < ResGroupData->idCount; i++) AddResId.push_back((DWORD)ResGroupData->idEntries[i].nID); } else if (IconDir->idCount < ResGroupData->idCount) { for (DWORD i = 0; i < ResGroupData->idCount; i++) { if (i < IconDir->idCount) AddResId.push_back((DWORD)ResGroupData->idEntries[i].nID); } } else { DWORD i, LastId; CHAR Str[MAX_PATH] = { 0 }; for (i = 0; i < ResGroupData->idCount; i++) AddResId.push_back((DWORD)ResGroupData->idEntries[i].nID); EnumResourceNamesA(Module, (LPCSTR)RT_ICON, EnumLastResIdProc, (LONG_PTR)Str); if (Str[0] == '#') LastId = atoi(&Str[1]) + 1; else LastId = 1; for (; i < IconDir->idCount; i++, LastId++) AddResId.push_back(LastId); } if (IsGroupExsited) UnlockResource(ResGroupData); FreeLibrary(Module); HANDLE Update = BeginUpdateResourceW(ExePath.c_str(), FALSE); if (!Update) return false; DWORD GroupResSize = 6 + sizeof(GRPICONDIRENTRY)*IconDir->idCount; PBYTE GroupResData = new(std::nothrow) BYTE[GroupResSize]; LPGRPICONDIR NewGroupDir = (LPGRPICONDIR)GroupResData; LPGRPICONDIRENTRY NewGroupDirEntry = (LPGRPICONDIRENTRY)(GroupResData + 6); NewGroupDir->idReserved = IconDir->idReserved; NewGroupDir->idCount = IconDir->idCount; NewGroupDir->idType = IconDir->idType; if (IsGroupExsited) { for_each(begin(DelResInfo), end(DelResInfo), [&Update](RESINFO& Info) { DeleteResData(Update, Info.ResType, Info.ResName, Info.ResLanguage); }); DeleteResData(Update, (LPCSTR)RT_GROUP_ICON, GroupName, OriResLang); } for (DWORD i = 0; i < IconDir->idCount; i++) { memcpy(&NewGroupDirEntry[i], &IconDirEntry[i], sizeof(GRPICONDIRENTRY)); NewGroupDirEntry[i].nID = (WORD)AddResId[i]; LPVOID ItemData = &IconData[0] + IconDirEntry[i].dwImageOffset; DWORD ItemSize = IconDirEntry[i].dwBytesInRes; SetResData(Update, (LPCSTR)RT_ICON, MAKEINTRESOURCEA(AddResId[i]), ItemData, ItemSize); } SetResData(Update, (LPCSTR)RT_GROUP_ICON, GroupName, (LPVOID&)GroupResData, GroupResSize, 1033); EndUpdateResource(Update, FALSE); if (GroupResData) delete[] GroupResData; return true; }
10,251
C++
.cpp
289
33.121107
149
0.702654
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,194
main.cpp
BlackINT3_OpenArk/src/OpenArk/bundler/bundler-shell/main.cpp
#ifndef _CRT_RAND_S #define _CRT_RAND_S #endif #include <windows.h> #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <unone.h> #include <thread> #include <string> #include <vector> #include "../pack/pack.h" typedef std::tuple<std::wstring, std::wstring> DirectiveSeq; #include <stdlib.h> bool ParseCmdline(const std::wstring& cmdline, std::vector<std::wstring>& vec) { try { int argc = 0; LPWSTR* argv = CommandLineToArgvW(cmdline.c_str(), &argc); for (int Index = 0; Index < argc; ++Index) { vec.push_back(argv[Index]); } HeapFree(GetProcessHeap(), 0, argv); return !vec.empty(); } catch (...) { vec.clear(); return false; } } std::string TmRandHexString(int count) { char str_temp[2] = { 0 }; std::string str; int i, x; unsigned int randnum = 0; const char charset[] = "0123456789ABCDEF"; if (count <= 0) return ""; for (i = 0; i < count; ++i) { rand_s(&randnum); x = randnum % (unsigned)(sizeof(charset) - 1); sprintf_s(str_temp, "%c", charset[x]); str.append(str_temp); } return str; } void BundleExecStart(std::wstring param, std::wstring root) { UNONE::StrReplaceIW(param, L"%root%", root); UNONE::PsCreateProcessW(param); } void BundleExecCall(std::wstring param, std::wstring root, int show = SW_SHOW, bool wait = true) { UNONE::StrReplaceIW(param, L"%root%", root); std::vector<std::wstring> vec; ParseCmdline(param, vec); if (vec.empty()) return; param.clear(); for (auto i = 1; i < vec.size(); i++) { param.append(vec[i]); param.append(L" "); } SHELLEXECUTEINFOW sh = { 0 }; sh.cbSize = sizeof(SHELLEXECUTEINFOW); sh.fMask = SEE_MASK_NOCLOSEPROCESS; sh.hwnd = NULL; sh.lpVerb = NULL; sh.lpFile = vec[0].c_str(); sh.lpParameters = param.c_str(); sh.lpDirectory = NULL; sh.nShow = show; sh.hInstApp = NULL; ShellExecuteExW(&sh); if (wait) WaitForSingleObject(sh.hProcess, INFINITE); CloseHandle(sh.hProcess); } void BundleExecCmd(std::wstring param, std::wstring root) { UNONE::StrReplaceIW(param, L"%root%", root); BundleExecCall(L"cmd.exe /c " + param, root, false); } void BundleExecClean(std::wstring param, std::wstring root) { UNONE::FsDeleteDirectoryW(root); } void BundleOutputError(std::wstring msg) { MessageBoxW(NULL, msg.c_str(), L"error", MB_ICONERROR); } int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { bool found = false; LPVOID bdata = NULL; HRSRC res = FindResourceW(GetModuleHandleW(NULL), MAKEINTRESOURCE(IDX_BUDE), IDS_BUDE); if (res) { HGLOBAL hg = LoadResource(GetModuleHandleW(NULL), res); if (hg) { bdata = LockResource(hg); if (bdata) { DWORD size = SizeofResource(GetModuleHandleW(NULL), res); found = true; } } } std::string test; if (!found) { #ifndef _DEBUG BundleOutputError(L"Resource is corrupted."); return 1; #endif #ifdef _DEBUG UNONE::FsReadFileDataA("c:/test.bd", test); if (test.empty()) return 1; #endif bdata = (LPVOID)test.c_str(); } std::wstring dirname; BundleError err; err = BundleGetDirName((const char*)bdata, dirname); if (err != BERR_OK) { BundleOutputError(L"Directory name invalid."); return 1; } std::wstring parentdir, outdir, script; parentdir = UNONE::OsEnvironmentW(L"%temp%\\BUDE\\") + UNONE::StrToW(TmRandHexString(12)); outdir = parentdir + L"\\" + dirname; UNONE::FsCreateDirW(outdir); err = BundleUnpack(outdir, (const char*)bdata, script, dirname); if (err != BERR_OK) { BundleOutputError(L"Unpack files error."); return 1; } std::vector<std::wstring> lines; UNONE::StrSplitLinesW(script, lines); std::vector<DirectiveSeq> directives; for (auto& line : lines) { if (line.find(';') != 0) { size_t pos = line.find(' '); std::wstring cmd, param; if (pos != std::wstring::npos) { cmd = line.substr(0, pos); param = line.substr(pos + 1); } else { cmd = line; } directives.push_back(std::make_tuple(cmd, param)); } } std::vector<std::thread> async_tasks; for (auto &d : directives) { std::wstring cmd, param; std::tie(cmd, param) = d; if (UNONE::StrCompareIW(cmd, L"start")) { async_tasks.push_back(std::thread(BundleExecCall, param, outdir, SW_SHOW, true)); } else if (UNONE::StrCompareIW(cmd, L"call")) { BundleExecCall(param, outdir); } else if (UNONE::StrCompareIW(cmd, L"cmd")) { BundleExecCmd(param, outdir); } else if (UNONE::StrCompareIW(cmd, L"clean")) { BundleExecClean(param, parentdir); } } for (auto &t : async_tasks) { t.join(); } return 0; }
4,546
C++
.cpp
174
23.856322
96
0.687901
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,195
pack.cpp
BlackINT3_OpenArk/src/OpenArk/bundler/pack/pack.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "pack.h" #include "../lz4/lz4.h" #include "../crc32/crc32.h" #include <unone.h> #include <time.h> /*******************************/ //BundleHeader //...[Crypted] //......[Compressed] //.........BundleScript //.........BundleRecord //.........BundleRecord //..................... //......[Compressed] //...[Crypted] /*******************************/ #define BUNDLE_MAGIC 'BUDE' #define BUNDLE_XORKEY 0x99 #pragma pack(push,1) struct BundleHeader { uint32_t magic; //'BUDE' uint32_t timestamp; //timestamp uint64_t orisize; //original size uint64_t cpsize; //compressed size uint32_t crc32; //crc32 uint32_t recordcnt; //record count uint16_t dirname[MAX_PATH]; //root dir name }; struct BundleScript { uint32_t len; uint16_t buf[1]; }; struct BundleRecord { uint64_t size; uint32_t crc32; uint16_t name[MAX_PATH]; uint8_t data[1]; }; #pragma pack(pop) BOOL BundleWriteFile(HANDLE fd, LPCVOID buf, DWORD buflen, LPDWORD writelen, LPOVERLAPPED overlapped) { DWORD i = buflen; while (i--) { ((PBYTE)buf)[i] ^= BUNDLE_XORKEY; } BOOL result = WriteFile(fd, buf, buflen, writelen, overlapped); i = buflen; while (i--) { ((PBYTE)buf)[i] ^= BUNDLE_XORKEY; } return result; } BOOL BundleReadFile(HANDLE fd, LPVOID buf, DWORD buflen, LPDWORD readlen, LPOVERLAPPED overlapped) { if (ReadFile(fd, buf, buflen, readlen, overlapped)) { DWORD i = *readlen; while (i--) { ((PBYTE)buf)[i] ^= BUNDLE_XORKEY; } } return FALSE; } BOOL BundleReadMemory(const char* data, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, BOOL reset = FALSE) { static DWORD offset = 0; if (reset) offset = 0; DWORD i = nNumberOfBytesToRead; while (i--) { ((PBYTE)lpBuffer)[i] = data[offset + i] ^ BUNDLE_XORKEY; } offset += nNumberOfBytesToRead; return TRUE; } BOOL BundleCrypt(std::string &data) { for (auto& c : data) { c ^= BUNDLE_XORKEY; } return TRUE; } BundleError BundleVerify(BundleHeader *bhdr) { if (bhdr->magic != BUNDLE_MAGIC) { return BERR_INVALID_FILEMAGIC; } if (bhdr->cpsize < 0 || bhdr->orisize < 0) { return BERR_INVALID_HEADER; } if (bhdr->recordcnt < 0) { return BERR_INVALID_RECORDCOUNT; } return BERR_OK; } BundleError BundlePack(const std::wstring &dirname, std::vector<std::wstring> &files, std::vector<std::wstring> &names, std::wstring script, std::string &bdata) { BundleError err = BERR_OK; int recordcount = 0; std::string buf; BundleScript s = {0}; s.len = script.size(); buf.append((char*)&s, sizeof(BundleScript) - 2); buf.append((char*)script.c_str(), script.size() * 2); for (size_t i = 0; i < files.size(); i++) { std::string data; std::wstring path = files[i]; std::wstring name = names[i]; if (!UNONE::FsReadFileDataW(path, data)) { err = BERR_FAIL_READ; break; } BundleRecord record = { 0 }; if (data.size() > 0) { record.crc32 = crc32(data.data(), data.size()); } wcsncpy_s((wchar_t*)record.name, MAX_PATH, name.c_str(), MAX_PATH - 1); record.size = data.size(); buf.append((char*)&record, sizeof(BundleRecord) - 1); buf.append(data); } if (err != BERR_OK) { return err; } int maxsize = LZ4_compressBound(buf.size()); std::string cpdata; cpdata.resize(maxsize); int cpsize = LZ4_compress(buf.data(), (char *)cpdata.data(), buf.size()); cpdata.resize(cpsize); BundleCrypt(cpdata); BundleHeader bhdr = { 0 }; bhdr.magic = BUNDLE_MAGIC; bhdr.crc32 = crc32((unsigned char*)buf.data(), buf.size()); bhdr.cpsize = cpsize; bhdr.orisize = buf.size(); bhdr.recordcnt = files.size(); bhdr.timestamp = (uint32_t)time(0); wcsncpy_s((wchar_t*)bhdr.dirname, MAX_PATH, dirname.c_str(), MAX_PATH - 1); std::string bstr((char*)&bhdr, sizeof(BundleHeader)); BundleCrypt(bstr); bdata.append(bstr); bdata.append(cpdata); return BERR_OK; } BundleError BundleUnpack(const std::wstring &outdir, const char *bdata, std::wstring &script, std::wstring &dirname) { BundleError err = BERR_OK; BundleHeader bhdr = { 0 }; if (!BundleReadMemory(bdata, &bhdr, sizeof(bhdr), TRUE)) { return BERR_FAIL_READ; } err = BundleVerify(&bhdr); if (err != BERR_OK) { return err; } dirname = (wchar_t*)bhdr.dirname; uint64_t oribuflen = bhdr.orisize + 64; uint64_t cpbuflen = bhdr.cpsize; std::string cpdata, oridata; cpdata.resize((unsigned int)cpbuflen); oridata.resize((unsigned int)oribuflen); BundleReadMemory(bdata, (LPVOID)cpdata.data(), (DWORD)bhdr.cpsize); int size = LZ4_decompress_safe(cpdata.data(), (char*)oridata.data(), (int)cpbuflen, (int)oribuflen); if (size == 0) { return BERR_FAIL_DECOMPRESSED; } uint32_t hash = crc32(oridata.data(), size); if (hash != bhdr.crc32) { return BERR_INVALID_HEADER; } BundleScript *sptr = (BundleScript*)oridata.data(); script.assign((wchar_t*)sptr->buf, sptr->len); BundleRecord *rptr = (BundleRecord*)((char*)sptr + sizeof(BundleScript) - 2 + sptr->len*2); for (int i = 0; i < (int)bhdr.recordcnt; i++) { if (rptr->size != 0) { if (crc32(rptr->data, (uint32_t)rptr->size) != rptr->crc32) { err = BERR_INVALID_RECORDCRC32; break; } } std::wstring&& path = UNONE::FsPathComposeW(outdir, (wchar_t*)rptr->name); std::wstring&& dir = UNONE::FsPathToDirW(path); if (!UNONE::FsCreateDirW(dir)) { err = BERR_FAIL_CREATEDIR; break; } HANDLE fd = CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (fd == INVALID_HANDLE_VALUE) { err = BERR_FAIL_CREATEFILE; break; } if (rptr->size != 0) { DWORD wlen; if (!WriteFile(fd, rptr->data, (DWORD)rptr->size, &wlen, NULL)) { err = BERR_FAIL_WRITE; CloseHandle(fd); break; } } rptr = (BundleRecord*)(((uint8_t*)rptr) + rptr->size - 1 + sizeof(BundleRecord)); CloseHandle(fd); } return err; } BundleError BundleGetDirName(const char *bdata, std::wstring &dirname) { BundleError err = BERR_OK; BundleHeader bhdr = { 0 }; DWORD readlen = 0; if (!BundleReadMemory(bdata, &bhdr, sizeof(bhdr), TRUE)) { return BERR_FAIL_READ; } err = BundleVerify(&bhdr); if (err != BERR_OK) { return err; } dirname = (wchar_t*)bhdr.dirname; return err; }
6,908
C++
.cpp
234
27.376068
123
0.668619
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,196
driver-entry.cpp
BlackINT3_OpenArk/src/OpenArkDrv/driver-entry.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include <ntifs.h> #include "arkdrv-api/arkdrv-api.h" #include "common/common.h" #include "kdriver/kdriver.h" #include "knotify/knotify.h" #include "kmemory/kmemory.h" #include "kwingui/ops-hotkey/ops-hotkey.h" #include "kstorage/kstorage.h" #include "kobject/kobject.h" #include "kprocess/kprocess.h" EXTERN_C NTSTATUS DriverEntry(PDRIVER_OBJECT drvobj, PUNICODE_STRING registry); NTSTATUS MainDispatcher(PDEVICE_OBJECT devobj, PIRP irp); NTSTATUS DefaultDispatcher(PDEVICE_OBJECT devobj, PIRP irp); VOID DriverUnload(PDRIVER_OBJECT drvobj); NTSTATUS DriverEntry(PDRIVER_OBJECT drvobj, PUNICODE_STRING registry) { NTSTATUS status; UNICODE_STRING devname, symlnk; PDEVICE_OBJECT devobj; UNREFERENCED_PARAMETER(registry); KdPrint(("OpenArkDrv loading...")); RtlInitUnicodeString(&devname, ARK_NTDEVICE_NAME); RtlInitUnicodeString(&symlnk, ARK_DOSDEVICE_NAME); status = IoCreateDevice(drvobj, 0, &devname, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &devobj); if (!NT_SUCCESS(status)) { KdPrint(("IoCreateDevice err:%x", status)); return status; } drvobj->DriverUnload = DriverUnload; drvobj->MajorFunction[IRP_MJ_CREATE] = DefaultDispatcher; drvobj->MajorFunction[IRP_MJ_CLOSE] = DefaultDispatcher; drvobj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = MainDispatcher; status = IoCreateSymbolicLink(&symlnk, &devname); if (!NT_SUCCESS(status)) { IoDeleteDevice(devobj); KdPrint(("IoCreateSymbolicLink err:%x", status)); return status; } if (!InitArkDriver(drvobj, devobj)) { KdPrint(("InitArkDriver err")); IoDeleteSymbolicLink(&symlnk); IoDeleteDevice(devobj); return STATUS_UNSUCCESSFUL; } status = STATUS_SUCCESS; return status; } NTSTATUS MainDispatcher(PDEVICE_OBJECT devobj, PIRP irp) { NTSTATUS status = STATUS_UNSUCCESSFUL; PIO_STACK_LOCATION irpstack; PVOID inbuf_dup = NULL; PVOID inbuf = NULL; PVOID outbuf = NULL; ULONG inlen = 0; ULONG outlen = 0; ULONG ctlcode = 0; ULONG op = 0; irpstack = IoGetCurrentIrpStackLocation(irp); ctlcode = irpstack->Parameters.DeviceIoControl.IoControlCode; // [TODO] try except ProbeForRead/Write inlen = irpstack->Parameters.DeviceIoControl.InputBufferLength; if (inlen < 4) return STATUS_INVALID_PARAMETER; inbuf = irp->AssociatedIrp.SystemBuffer; if (!inbuf) return STATUS_INVALID_PARAMETER; op = *(ULONG*)inbuf; inlen = inlen - 4; inbuf = (UCHAR*)inbuf + 4; status = DuplicateInputBuffer(irp, inbuf); if (!NT_SUCCESS(status)) return status; outbuf = irp->AssociatedIrp.SystemBuffer; outlen = irpstack->Parameters.DeviceIoControl.OutputBufferLength; switch (ctlcode) { case IOCTL_ARK_HEARTBEAT: status = STATUS_SUCCESS; break; case IOCTL_ARK_DRIVER: status = DriverDispatcher(op, devobj, irp); break; case IOCTL_ARK_NOTIFY: status = NotifyDispatcher(op, devobj, irp); break; case IOCTL_ARK_MEMORY: status = MemoryDispatcher(op, devobj, inbuf, inlen, outbuf, outlen, irp); break; case IOCTL_ARK_HOTKEY: status = HotkeyDispatcher(op, devobj, irp); break; case IOCTL_ARK_STORAGE: status = StorageDispatcher(op, devobj, irp); break; case IOCTL_ARK_OBJECT: status = ObjectDispatcher(op, devobj, inbuf, inlen, outbuf, outlen, irp); break; case IOCTL_ARK_PROCESS: status = ProcessDispatcher(op, devobj, inbuf, inlen, outbuf, outlen, irp); break; default: status = STATUS_INVALID_DEVICE_REQUEST; break; } irp->IoStatus.Status = status; IoCompleteRequest(irp, IO_NO_INCREMENT); return status; } NTSTATUS DefaultDispatcher(PDEVICE_OBJECT devobj, PIRP irp) { irp->IoStatus.Status = STATUS_SUCCESS; irp->IoStatus.Information = 0; IoCompleteRequest(irp, IO_NO_INCREMENT); return STATUS_SUCCESS; } VOID DriverUnload(PDRIVER_OBJECT drvobj) { UNICODE_STRING symlnk; PDEVICE_OBJECT dev = drvobj->DeviceObject; if (dev) { RtlInitUnicodeString(&symlnk, ARK_DOSDEVICE_NAME); IoDeleteSymbolicLink(&symlnk); IoDeleteDevice(dev); } }
4,776
C++
.cpp
143
30.853147
79
0.735919
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,197
kobject.cpp
BlackINT3_OpenArk/src/OpenArkDrv/kobject/kobject.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "kobject.h" #include "../common/common.h" #include <knone.h> #include <ntifs.h> #include <ntimage.h> #include <ntintsafe.h> #include <windef.h> NTSTATUS ObjectDispatcher(IN ULONG op, IN PDEVICE_OBJECT devobj, PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, IN PIRP irp) { NTSTATUS status = STATUS_UNSUCCESSFUL; switch (op) { case ARK_OBJECT_TYPE_ENUM: break; case STORAGE_UNLOCK_CLOSE: break; default: break; } return status; }
1,252
C++
.cpp
35
34.371429
131
0.67023
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,198
kstorage.cpp
BlackINT3_OpenArk/src/OpenArkDrv/kstorage/kstorage.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "kstorage.h" #include "unlock/handle.h" #include "../common/common.h" #include <knone.h> #include <ntifs.h> #include <ntimage.h> #include <ntintsafe.h> #include <windef.h> /* NTSTATUS StorageUnlockClose(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { return 0; } */ NTSTATUS StorageDispatcher(IN ULONG op, IN PDEVICE_OBJECT devobj, IN PIRP irp) { NTSTATUS status = STATUS_UNSUCCESSFUL; PIO_STACK_LOCATION irpstack; PVOID inbuf_dup = NULL; PVOID inbuf = NULL; PVOID outbuf = NULL; ULONG inlen = 0; ULONG outlen = 0; irpstack = IoGetCurrentIrpStackLocation(irp); inlen = irpstack->Parameters.DeviceIoControl.InputBufferLength - 4; inbuf = (UCHAR*)irp->AssociatedIrp.SystemBuffer + 4; //KdBreakPoint(); status = DuplicateInputBuffer(irp, inbuf); if (!NT_SUCCESS(status)) return status; outbuf = irp->AssociatedIrp.SystemBuffer; outlen = irpstack->Parameters.DeviceIoControl.OutputBufferLength; switch (op) { case STORAGE_UNLOCK_ENUM: status = StorageUnlockEnum(inbuf, inlen, outbuf, outlen, irp); break; case STORAGE_UNLOCK_CLOSE: status = StorageUnlockClose(inbuf, inlen, outbuf, outlen, irp); break; default: break; } ReleaseInputBuffer(irp, inbuf_dup); return status; }
2,028
C++
.cpp
59
32.762712
91
0.710071
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,199
handle.cpp
BlackINT3_OpenArk/src/OpenArkDrv/kstorage/unlock/handle.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include <common/common.h> #include <kdriver/kdriver.h> #include <arkdrv-api/arkdrv-api.h> #include "handle.h" extern ARK_DRIVER ArkDrv; #define KERNEL_HANDLE_MASK ((ULONG_PTR)((LONG)0x80000000))// BOOLEAN ForceCloseHandle(HANDLE pid, HANDLE handle) { BOOLEAN ret = FALSE; PEPROCESS eprocess; KAPC_STATE apcstate; NTSTATUS status; MODE mode = UserMode; OBJECT_HANDLE_FLAG_INFORMATION objectinfo; PsLookupProcessByProcessId(pid, &eprocess); if (eprocess == NULL || !MmIsAddressValid(eprocess)) { return ret; } __try { KeStackAttachProcess(eprocess, &apcstate); //ObDereferenceObject(eprocess); if (PsGetCurrentProcess() == PsInitialSystemProcess) { handle = (HANDLE)((ULONG_PTR)handle | KERNEL_HANDLE_MASK); mode = KernelMode; } objectinfo.Inherit = 0; objectinfo.ProtectFromClose = 0; status = ObSetHandleAttributes(handle, &objectinfo, mode); if (NT_SUCCESS(status)) { status = ZwClose(handle); } KeUnstackDetachProcess(&apcstate); } __except (EXCEPTION_EXECUTE_HANDLER) { KdPrint(("EXCEPTION_EXECUTE_HANDLER\n")); } ObDereferenceObject(eprocess); if (NT_SUCCESS(status)) { ret = TRUE; } return ret; } NTSTATUS EnumHandleInfoByPid(LPVOID buf, ULONG len, HANDLE pid) { NTSTATUS status = STATUS_UNSUCCESSFUL; ULONG size = 0x10000; PVOID buffer = NULL; UINT64 handlecount = 0; PSYSTEM_HANDLE_TABLE_ENTRY_INFO tableinfo = NULL; PHANDLE_INFO info = (PHANDLE_INFO)buf; ULONG count = 0; BOOLEAN goon = TRUE; buffer = ExAllocatePoolWithTag(NonPagedPool, size, 'enhd'); if (buffer == NULL) { return STATUS_UNSUCCESSFUL; } RtlZeroMemory(buffer, size); status = ZwQuerySystemInformation(SystemHandleInformation, buffer, size, 0); while (status == STATUS_INFO_LENGTH_MISMATCH){ ExFreePoolWithTag(buffer, 'enhd'); size = size * 2; buffer = ExAllocatePoolWithTag(NonPagedPool, size, 'enhd'); if (buffer == NULL) { return STATUS_UNSUCCESSFUL; } RtlZeroMemory(buffer, size); status = ZwQuerySystemInformation(SystemHandleInformation, buffer, size, 0); } if (!NT_SUCCESS(status)) { return STATUS_UNSUCCESSFUL; } handlecount = (UINT64)(((SYSTEM_HANDLE_INFORMATION *)buffer)->NumberOfHandles); tableinfo = (SYSTEM_HANDLE_TABLE_ENTRY_INFO *)((SYSTEM_HANDLE_INFORMATION *)buffer)->Handles; for (int i = 0; i < handlecount; i++) { USHORT processid = tableinfo[i].UniqueProcessId; HANDLE handle = (HANDLE)tableinfo[i].HandleValue; ULONG typeindex = (ULONG)tableinfo[i].ObjectTypeIndex; LPVOID object = tableinfo[i].Object; if (pid == (HANDLE)processid) { CLIENT_ID cid = {0}; OBJECT_ATTRIBUTES oa = {0}; HANDLE hprocess = NULL; HANDLE hdupobj = NULL; OBJECT_BASIC_INFORMATION basicinfo = {0}; POBJECT_NAME_INFORMATION nameinfo = NULL; POBJECT_TYPE_INFORMATION typeinfo = NULL; ULONG refcount = 0; ULONG flag = 0; PHANDLE_ITEM item = &(info->items[count]); cid.UniqueProcess = (HANDLE)processid; cid.UniqueThread = (HANDLE)0; InitializeObjectAttributes(&oa, NULL, 0, NULL, NULL); while (1) { status = ZwOpenProcess(&hprocess, PROCESS_DUP_HANDLE, &oa, &cid); if (!NT_SUCCESS(status)) { KdPrint(("ZwOpenProcess : Fail ")); break; } status = ZwDuplicateObject(hprocess, handle, NtCurrentProcess(), &hdupobj, PROCESS_ALL_ACCESS, 0, DUPLICATE_SAME_ACCESS); if (!NT_SUCCESS(status)) { DbgPrint("ZwDuplicateObject : Fail "); break; } ZwQueryObject(hdupobj, ObjectBasicInformation, &basicinfo, sizeof(OBJECT_BASIC_INFORMATION), NULL); nameinfo = (POBJECT_NAME_INFORMATION)ExAllocatePoolWithTag(NonPagedPool, 1024, 'enhd'); if (nameinfo == NULL) { break; } RtlZeroMemory(nameinfo, 1024); status = ZwQueryObject(hdupobj, (OBJECT_INFORMATION_CLASS)1, nameinfo, 1024, &flag); //ObjectNameInformation typeinfo = (POBJECT_TYPE_INFORMATION )ExAllocatePoolWithTag(NonPagedPool, 256, 'enhd'); if (typeinfo == NULL) { break; } RtlZeroMemory(typeinfo, 256); status = ZwQueryObject(hdupobj, (OBJECT_INFORMATION_CLASS)2, typeinfo, 256, &flag); // ObjectTypeInformation refcount = basicinfo.ReferenceCount - basicinfo.HandleCount; if (((CHAR *)item + sizeof(HANDLE_ITEM)) > ((CHAR *)buf + len)) { status = STATUS_FLT_BUFFER_TOO_SMALL; info->count = count; goon = FALSE; break; } item->pid = pid; item->handle = handle; item->object = object; item->ref_count = refcount; item->type_index = typeindex; RtlCopyMemory(item->name, nameinfo->Name.Buffer, sizeof(WCHAR) * nameinfo->Name.Length); RtlCopyMemory(item->type_name, typeinfo->TypeName.Buffer, sizeof(WCHAR) * typeinfo->TypeName.Length); count += 1; KdPrint(("NAME:%wZ\t\t\tTYPE:%wZ\n", &(nameinfo->Name), &(typeinfo->TypeName))); break; } if (nameinfo) ExFreePoolWithTag(nameinfo, 'enhd'); if (typeinfo) ExFreePoolWithTag(typeinfo, 'enhd'); if(hdupobj) ZwClose(hdupobj); if(hprocess) ZwClose(hprocess); if (goon == FALSE ) { break; } } } info->count = count; if (buffer) { ExFreePoolWithTag(buffer, 'enhd'); } return status; } NTSTATUS StorageUnlockEnum(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { LPVOID buf = outbuf; ULONG len = outlen; auto path = (WCHAR*)inbuf; NTSTATUS status = STATUS_UNSUCCESSFUL; ULONG size = 0x10000; PVOID buffer = NULL; UINT64 handlecount = 0; PSYSTEM_HANDLE_TABLE_ENTRY_INFO tableinfo = NULL; PHANDLE_INFO info = (PHANDLE_INFO)buf; ULONG count = 0; UCHAR filetypeindex = 28; // set file object type index filetypeindex = (UCHAR)ObjectTypeIndexByName(L"File"); if (filetypeindex == -1) { return status; } buffer = ExAllocatePoolWithTag(NonPagedPool, size, 'enhd'); if (buffer == NULL) { return STATUS_MEMORY_NOT_ALLOCATED; } RtlZeroMemory(buffer, size); status = ZwQuerySystemInformation(SystemHandleInformation, buffer, size, &size); while (status == STATUS_INFO_LENGTH_MISMATCH) { ExFreePoolWithTag(buffer, 'enhd'); buffer = ExAllocatePoolWithTag(NonPagedPool, size, 'enhd'); if (buffer == NULL) { return STATUS_MEMORY_NOT_ALLOCATED; } RtlZeroMemory(buffer, size); status = ZwQuerySystemInformation(SystemHandleInformation, buffer, size, &size); } if (!NT_SUCCESS(status)) return status; handlecount = (UINT64)(((SYSTEM_HANDLE_INFORMATION *)buffer)->NumberOfHandles); tableinfo = (SYSTEM_HANDLE_TABLE_ENTRY_INFO *)((SYSTEM_HANDLE_INFORMATION *)buffer)->Handles; // calculate size LONG exactcnt = 0; for (int i = 0; i < handlecount; i++) { ULONG typeindex = (ULONG)tableinfo[i].ObjectTypeIndex; if (typeindex == filetypeindex) exactcnt++; } ULONG exactsize = sizeof(HANDLE_INFO) + (exactcnt > 0 ? (exactcnt - 1) : 0) * sizeof(HANDLE_ITEM); if (buf == NULL || len < exactsize) { irp->IoStatus.Information = exactsize + 10 * sizeof(HANDLE_ITEM); return STATUS_BUFFER_OVERFLOW; } //KdBreakPoint(); for (int i = 0; i < handlecount; i++) { USHORT processid = tableinfo[i].UniqueProcessId; HANDLE handle = (HANDLE)tableinfo[i].HandleValue; ULONG typeindex = (ULONG)tableinfo[i].ObjectTypeIndex; LPVOID object = tableinfo[i].Object; CLIENT_ID cid = { 0 }; OBJECT_ATTRIBUTES oa = { 0 }; HANDLE hprocess = NULL; HANDLE hdupobj = NULL; OBJECT_BASIC_INFORMATION basicinfo = { 0 }; POBJECT_NAME_INFORMATION nameinfo = NULL; POBJECT_TYPE_INFORMATION typeinfo = NULL; ULONG refcount = 0; ULONG flag = 0; PHANDLE_ITEM item = &(info->items[count]); if (typeindex != filetypeindex) continue;; cid.UniqueProcess = (HANDLE)processid; cid.UniqueThread = (HANDLE)0; InitializeObjectAttributes(&oa, NULL, 0, NULL, NULL); while (1) { status = ZwOpenProcess(&hprocess, PROCESS_DUP_HANDLE, &oa, &cid); if (!NT_SUCCESS(status)) { KdPrint(("ZwOpenProcess err:%d", status)); break; } status = ZwDuplicateObject(hprocess, handle, NtCurrentProcess(), &hdupobj, PROCESS_ALL_ACCESS, 0, DUPLICATE_SAME_ACCESS); if (!NT_SUCCESS(status)) { KdPrint(("ZwDuplicateObject err:%d", status)); break; } nameinfo = (POBJECT_NAME_INFORMATION)ExAllocatePoolWithTag(NonPagedPool, 1024, 'enhd'); if (nameinfo == NULL) { status = STATUS_MEMORY_NOT_ALLOCATED; break; } RtlZeroMemory(nameinfo, 1024); status = ZwQueryObject(hdupobj, (OBJECT_INFORMATION_CLASS)1, nameinfo, 1024, &flag); //ObjectNameInformation if (nameinfo->Name.Length > 0) { WCHAR pathlower[260] = { 0 }; WCHAR namelower[260] = { 0 }; wcsncpy(pathlower, path, wcslen(path)); wcsncpy(namelower, nameinfo->Name.Buffer, nameinfo->Name.Length / sizeof(WCHAR)); _wcslwr(pathlower); _wcslwr(namelower); if (wcsstr(namelower, pathlower)) { // filter the file path ZwQueryObject(hdupobj, ObjectBasicInformation, &basicinfo, sizeof(OBJECT_BASIC_INFORMATION), NULL); typeinfo = (POBJECT_TYPE_INFORMATION)ExAllocatePoolWithTag(NonPagedPool, 256, 'enhd'); if (typeinfo == NULL) { status = STATUS_MEMORY_NOT_ALLOCATED; break; } RtlZeroMemory(typeinfo, 256); status = ZwQueryObject(hdupobj, (OBJECT_INFORMATION_CLASS)2, typeinfo, 256, &flag); // ObjectTypeInformation refcount = basicinfo.ReferenceCount - basicinfo.HandleCount; // maybe bug? item->pid = (HANDLE)processid; item->handle = handle; item->object = object; item->ref_count = refcount; item->type_index = typeindex; RtlCopyMemory(item->name, nameinfo->Name.Buffer, sizeof(WCHAR) * nameinfo->Name.Length); RtlCopyMemory(item->type_name, typeinfo->TypeName.Buffer, sizeof(WCHAR) * typeinfo->TypeName.Length); count++; KdPrint(("NAME:%wZ\t\t\tTYPE:%wZ\n", &(nameinfo->Name), &(typeinfo->TypeName))); } } break; } if (nameinfo) ExFreePoolWithTag(nameinfo, 'enhd'); if (typeinfo) ExFreePoolWithTag(typeinfo, 'enhd'); if (hdupobj) ZwClose(hdupobj); if (hprocess) ZwClose(hprocess); } info->count = count; // set count of item if (buffer) ExFreePoolWithTag(buffer, 'enhd'); irp->IoStatus.Information = sizeof(HANDLE_INFO) + (count > 0 ? (count-1) : 0) * sizeof(HANDLE_ITEM); return status; } NTSTATUS StorageUnlockClose(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { NTSTATUS status = STATUS_UNSUCCESSFUL; HANDLE_ITEM *handle_item = (HANDLE_ITEM *)inbuf; if (handle_item) { HANDLE pid = handle_item->pid; HANDLE handle = handle_item->handle; if (ForceCloseHandle(pid, handle)){ status = STATUS_SUCCESS; } } irp->IoStatus.Information = 0; return status; }
11,423
C++
.cpp
304
34.194079
125
0.699006
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,200
kdriver.cpp
BlackINT3_OpenArk/src/OpenArkDrv/kdriver/kdriver.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "../arkdrv-api/arkdrv-api.h" #include "kdriver.h" PRTL_PROCESS_MODULES QueryModuleInformation() { NTSTATUS status = STATUS_SUCCESS; PRTL_PROCESS_MODULES system_information = NULL; ULONG retlen = 0; status = ZwQuerySystemInformation(SystemModuleInformation, NULL, 0, &retlen); if (status != STATUS_INFO_LENGTH_MISMATCH) { return NULL; } ULONG bufsize = retlen + 10 * sizeof(RTL_PROCESS_MODULE_INFORMATION); PRTL_PROCESS_MODULES modules = (PRTL_PROCESS_MODULES)ExAllocatePool(NonPagedPool, bufsize); if (modules == NULL) { return NULL; } status = ZwQuerySystemInformation(SystemModuleInformation, modules, bufsize, &retlen); if (!NT_SUCCESS(status)) { ExFreePool(modules); return NULL; } return modules; } NTSTATUS DriverEnumInfo(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { PRTL_PROCESS_MODULES mods = QueryModuleInformation(); if (!mods) { return STATUS_UNSUCCESSFUL; } ULONG count = mods->NumberOfModules; ULONG size = count * sizeof(DRIVER_ITEM) + 4; if (size > outlen) { irp->IoStatus.Information = size + 10 * sizeof(DRIVER_ITEM); ExFreePool(mods); return STATUS_BUFFER_OVERFLOW; } PDRIVER_INFO info = (PDRIVER_INFO)outbuf; info->count = count; for (ULONG i = 0; i < count; i++) { auto &item = info->items[i]; auto &mod = mods->Modules[i]; #ifdef _AMD64_ item.base = (ULONG64)mod.ImageBase; #else item.base = (ULONG64)(ULONG)mod.ImageBase; #endif item.size = mod.ImageSize; item.flags = mod.Flags; item.init_seq = mod.InitOrderIndex; item.load_seq = mod.LoadOrderIndex; RtlCopyMemory(item.path, mod.FullPathName, sizeof(mod.FullPathName)); } ExFreePool(mods); irp->IoStatus.Information = size; return STATUS_SUCCESS; } BOOLEAN InitDriverDispatcher() { return TRUE; } NTSTATUS DriverDispatcher(IN ULONG op, IN PDEVICE_OBJECT devobj, IN PIRP irp) { //KdBreakPoint(); NTSTATUS status; PIO_STACK_LOCATION irpstack; PVOID inbuf = NULL; PVOID outbuf = NULL; ULONG inlen = 0; ULONG outlen = 0; irpstack = IoGetCurrentIrpStackLocation(irp); inbuf = (UCHAR*)irp->AssociatedIrp.SystemBuffer + 4; inlen = irpstack->Parameters.DeviceIoControl.InputBufferLength - 4; outbuf = irp->AssociatedIrp.SystemBuffer; outlen = irpstack->Parameters.DeviceIoControl.OutputBufferLength; switch (op) { case DRIVER_ENUM_INFO: status = DriverEnumInfo(inbuf, inlen, outbuf, outlen, irp); break; default: break; } return status; }
3,222
C++
.cpp
98
30.938776
92
0.720975
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,201
common.cpp
BlackINT3_OpenArk/src/OpenArkDrv/common/common.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "common.h" #include "../kdriver/kdriver.h" #include "../knotify/knotify.h" ARK_DRIVER ArkDrv; /*++ Description: get os version Arguments: void Return: NTOS_VERSION --*/ NTOS_VERSION_X OsNtVersion() { RTL_OSVERSIONINFOEXW info; if (!KNONE::OsGetVersionInfo(info)) return _NTOS_UNKNOWN; switch (info.dwMajorVersion) { case 5: { if (info.dwMinorVersion == 1) { if (info.wServicePackMajor == 1) return _NTOS_WINXPSP1; if (info.wServicePackMajor == 2) return _NTOS_WINXPSP2; if (info.wServicePackMajor == 3) return _NTOS_WINXPSP3; return _NTOS_WINXP; } if (info.dwMinorVersion == 2) { if (info.wServicePackMajor == 1) return _NTOS_WIN2003SP1; if (info.wServicePackMajor == 2) return _NTOS_WIN2003SP2; return _NTOS_WIN2003; } break; } case 6: { if (info.dwMinorVersion == 0) { if (info.wServicePackMajor == 1) return _NTOS_WINVISTASP1; if (info.wServicePackMajor == 2) return _NTOS_WINVISTASP2; return _NTOS_WINVISTA; } if (info.dwMinorVersion == 1) { if (info.wServicePackMajor == 1) return _NTOS_WIN7SP1; return _NTOS_WIN7; } if (info.dwMinorVersion == 2) { return _NTOS_WIN8; } if (info.dwMinorVersion == 3) { return _NTOS_WIN81; } break; } case 10: { if (info.dwBuildNumber == 10240) return _NTOS_WIN10_1507; if (info.dwBuildNumber == 10586) return _NTOS_WIN10_1511; if (info.dwBuildNumber == 14393) return _NTOS_WIN10_1607; if (info.dwBuildNumber == 15063) return _NTOS_WIN10_1703; if (info.dwBuildNumber == 16299) return _NTOS_WIN10_1709; if (info.dwBuildNumber == 17134) return _NTOS_WIN10_1803; if (info.dwBuildNumber == 17763) return _NTOS_WIN10_1809; if (info.dwBuildNumber == 18362) return _NTOS_WIN10_1903; if (info.dwBuildNumber == 18363) return _NTOS_WIN10_1909; if (info.dwBuildNumber == 19041) return _NTOS_WIN10_2004; if (info.dwBuildNumber == 19042) return _NTOS_WIN10_20H2; if (info.dwBuildNumber == 19043) return _NTOS_WIN10_21H1; if (info.dwBuildNumber == 19043) return _NTOS_WIN10_21H2; if (info.dwBuildNumber == 22000) return _NTOS_WIN11_21H2; } default: break; } return _NTOS_UNKNOWN; } BOOLEAN InitArkDriver(PDRIVER_OBJECT drvobj, PDEVICE_OBJECT devobj) { ArkDrv.drvobj = drvobj; ArkDrv.devobj = devobj; ArkDrv.ver = OsNtVersion(); ArkDrv.major = KNONE::OsMajorVersion(); ArkDrv.minor = KNONE::OsMinorVersion(); ArkDrv.build = KNONE::OsBuildNumber(); InitDriverDispatcher(); InitNotifyDispatcher(); return TRUE; } PVOID GetNtRoutineAddress(IN PCWSTR name) { UNICODE_STRING ustr; RtlInitUnicodeString(&ustr, name); return MmGetSystemRoutineAddress(&ustr); } NTSTATUS DuplicateInputBuffer(IN PIRP irp, PVOID &inbuf) { NTSTATUS status = STATUS_SUCCESS; PIO_STACK_LOCATION irpstack; PVOID inbuf_dup = NULL; PVOID outbuf = NULL; ULONG inlen = 0; irpstack = IoGetCurrentIrpStackLocation(irp); inlen = irpstack->Parameters.DeviceIoControl.InputBufferLength - 4; if (inbuf && inlen) { inbuf_dup = ExAllocatePoolWithTag(NonPagedPool, inlen, ARK_POOLTAG); if (!inbuf_dup) return STATUS_MEMORY_NOT_ALLOCATED; RtlCopyMemory(inbuf_dup, inbuf, inlen); inbuf = inbuf_dup; } return status; } NTSTATUS ReleaseInputBuffer(IN PIRP irp, PVOID &inbuf) { NTSTATUS status = STATUS_SUCCESS; if (inbuf) { inbuf = NULL; ExFreePoolWithTag(inbuf, ARK_POOLTAG); } return status; }
4,141
C++
.cpp
127
30.299213
77
0.712
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,202
ops-hotkey.cpp
BlackINT3_OpenArk/src/OpenArkDrv/kwingui/ops-hotkey/ops-hotkey.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "ops-hotkey.h" #include "utils/utils.h" #include <knone.h> #include <ntifs.h> #include <ntimage.h> #include <ntintsafe.h> #include <windef.h> typedef PVOID PWND; typedef UINT64 PADDING64; typedef UINT32 PADDING32; typedef struct _THREADINFO { PETHREAD thread; } *PTHREADINFO; typedef struct _WNDINFO { HWND wnd; } *PWNDINFO; typedef struct _HOT_KEY { PTHREADINFO thdinfo; PVOID callback; PWNDINFO wndinfo; UINT16 modifiers1; //eg:MOD_CONTROL(0x0002) UINT16 modifiers2; //eg:MOD_NOREPEAT(0x4000) UINT32 vk; UINT32 id; #ifdef _AMD64_ PADDING32 pad; #endif struct _HOT_KEY *slist; } HOT_KEY, * PHOT_KEY; extern "C" UCHAR* NTAPI PsGetProcessImageFileName( __in PEPROCESS Process ); #define MAX_VK 0xFF #define VK_OEM_CLEAR 0xFE #define MOD_ALT 0x0001 #define MOD_NOREPEAT 0x4000 __inline BOOLEAN CheckHotkeyValid(PUCHAR addr, UINT32 vk) { if (MmIsAddressValid(addr)) { PHOT_KEY hk = (PHOT_KEY)addr; if ((hk->vk & 0x7f) == vk) { // Hotkey valid return TRUE; } } return FALSE; } BOOLEAN SearchHotkeyTable(PUCHAR* &htable) { htable = NULL; // catch the imagebase of win32k£¨Win7 win32k.sys£¬Win10 win32kfull.sys£© PUCHAR win32k; ULONG win32ksize = 0; RTL_OSVERSIONINFOEXW info; OsGetVersionInfo(info); if (info.dwMajorVersion == 10) { win32k = (PUCHAR)GetSystemModuleBase("win32kfull.sys", &win32ksize); } else { win32k = (PUCHAR)GetSystemModuleBase("win32k.sys", &win32ksize); } if (!win32k) { return FALSE; } KdPrint(("win32k:%p, win32ksize:%x\n", win32k, win32ksize)); // catch the region of data segment (global HashTable) NTSTATUS status; PUCHAR start; ULONG size; status = GetSectionRegion(win32k, ".data", start, size); if (!NT_SUCCESS(status)) { return FALSE; } KdPrint(("win32k-data start:%p, size:%x\n", start, size)); // now searching... PUCHAR *ptr = (PUCHAR*)start; for (int i = 0, j = 0; i < size/sizeof(ptr); i++) { if (j == 0x80) { KdPrint(("start:%p\n", &ptr[i])); // the first place i -= j; // validate the Hotkeys INT vks[] = { 5, 10 ,15, 20, 25, 30, 35, 40, 45}; for (INT vk : vks) { if (!CheckHotkeyValid(ptr[i + vk], vk)) { j = 0; break; } } // we catch it if (j != 0) { htable = &ptr[i]; break; } continue; } // kernel address filter if (ptr[i] > MmSystemRangeStart) { j++; continue; } j = 0; } return 1; } VOID DumpHotkeyNode(PHOT_KEY hk, PHOTKEY_ITEM items, ULONG &pos) { if (MmIsAddressValid(hk->slist)) { DumpHotkeyNode(hk->slist, items, pos); } if (hk->id >= HOTKEY_PLACEHOLDER_ID && hk->id <= HOTKEY_PLACEHOLDER_ID + HOTKEY_MAX_VK) return; UCHAR *name = (UCHAR *)""; PETHREAD thread = hk->thdinfo->thread; PEPROCESS process = NULL; HANDLE pid = NULL; HANDLE tid = NULL; if (thread != NULL) { process = IoThreadToProcess(thread); pid = PsGetProcessId(process); tid = PsGetThreadId(thread); UCHAR *temp = PsGetProcessImageFileName(process); if (temp) name = temp; } HWND wnd = NULL; if (hk->wndinfo && MmIsAddressValid(hk->wndinfo)) wnd = hk->wndinfo->wnd; KdPrint(("HK:%x NAME:%s PROCESS:%d THREAD:%d HWND:%x MOD:%d VK:%d \n", hk, name, pid, tid, wnd, hk->modifiers1, hk->vk)); items[pos].hkobj = (ULONG64)hk; items[pos].id = hk->id; items[pos].tid = (UINT32)tid; items[pos].pid = (UINT32)pid; items[pos].mod1 = hk->modifiers1; items[pos].mod2 = hk->modifiers2; items[pos].vk = hk->vk; items[pos].wnd = (UINT32)wnd; strncpy((char*)items[pos].name, (char*)name, 63); pos++; } VOID DumpHotkeyTable(PUCHAR* table, PHOTKEY_ITEM items, ULONG &pos) { for (INT i = 0; i < 0x7f; i++) { PHOT_KEY hk = (PHOT_KEY)table[i]; if (hk) { DumpHotkeyNode(hk, items, pos); } } } static PUCHAR *HotkeyTable = NULL; NTSTATUS GetHotkeyInfo(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { ULONG count = 0; PHOTKEY_ITEM items = NULL; NTSTATUS status = STATUS_UNSUCCESSFUL; // // Caller have to guarantee current Win32k Session // /* PEPROCESS csrss_proc = NULL; ULONG csrss_pid = GetSessionProcessId(); status = PsLookupProcessByProcessId((HANDLE)csrss_pid, &csrss_proc); if (NT_SUCCESS(status)) { KAPC_STATE apc_state; KeStackAttachProcess(csrss_proc, &apc_state); status = STATUS_UNSUCCESSFUL; // // Code here.... // KeUnstackDetachProcess(&apc_state); ObDereferenceObject(csrss_proc); } */ if (!HotkeyTable) SearchHotkeyTable(HotkeyTable); KdPrint(("HotkeyTable:%llx\n", HotkeyTable)); if (HotkeyTable != NULL) { ULONG presize = sizeof(HOTKEY_ITEM) * 1024; items = (PHOTKEY_ITEM)ExAllocatePool(NonPagedPool, presize); RtlZeroMemory(items, presize); if (items) { DumpHotkeyTable(HotkeyTable, items, count); if (count) { ULONG size = sizeof(HOTKEY_INFO) + (count - 1) * sizeof(HOTKEY_ITEM); if (size > outlen) { irp->IoStatus.Information = size; ExFreePool(items); return STATUS_BUFFER_OVERFLOW; } auto info = (PHOTKEY_INFO)outbuf; info->count = count; for (ULONG i = 0; i < count; i++) { info->items[i] = items[i]; } irp->IoStatus.Information = size; status = STATUS_SUCCESS; } ExFreePool(items); } } return status; } VOID RemoveHotkeyNode(PHOT_KEY *hk_addr, PHOT_KEY hk, PHOTKEY_ITEM item, BOOLEAN &result) { if (result) return; PHOT_KEY slist = NULL; if (MmIsAddressValid(hk->slist)) { slist = hk->slist; RemoveHotkeyNode(&hk->slist, hk->slist, item, result); } PETHREAD thread = hk->thdinfo->thread; PEPROCESS process = NULL; HANDLE pid = NULL; HANDLE tid = NULL; if (thread != NULL) { process = IoThreadToProcess(thread); pid = PsGetProcessId(process); tid = PsGetThreadId(thread); } if (item->id == hk->id && item->pid == (UINT32)pid && item->tid == (UINT32)tid) { InterlockedExchangePointer((PVOID*)hk_addr, slist); result = TRUE; return; } } NTSTATUS RemoveHotkeyInfo(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { NTSTATUS status = STATUS_INVALID_PARAMETER; PHOTKEY_ITEM item = (PHOTKEY_ITEM)inbuf; if (inlen != sizeof(HOTKEY_ITEM)) return status; if (!HotkeyTable) return status; BOOLEAN removed = FALSE; for (INT i = 0; i < 0x7f; i++) { PHOT_KEY hk = (PHOT_KEY)HotkeyTable[i]; if (hk) { RemoveHotkeyNode((PHOT_KEY*)&HotkeyTable[i], hk, item, removed); } } if (!removed) return STATUS_NOT_FOUND; irp->IoStatus.Information = 0; return STATUS_SUCCESS; } NTSTATUS HotkeyDispatcher(IN ULONG op, IN PDEVICE_OBJECT devobj, IN PIRP irp) { //KdBreakPoint(); NTSTATUS status = STATUS_UNSUCCESSFUL; PIO_STACK_LOCATION irpstack; PVOID inbuf = NULL; PVOID outbuf = NULL; ULONG inlen = 0; ULONG outlen = 0; irpstack = IoGetCurrentIrpStackLocation(irp); inbuf = (UCHAR*)irp->AssociatedIrp.SystemBuffer + 4; inlen = irpstack->Parameters.DeviceIoControl.InputBufferLength - 4; outbuf = irp->AssociatedIrp.SystemBuffer; outlen = irpstack->Parameters.DeviceIoControl.OutputBufferLength; switch (op) { case HOTKEY_ENUM: status = GetHotkeyInfo(inbuf, inlen, outbuf, outlen, irp); break; case HOTKEY_REMOVE: status = RemoveHotkeyInfo(inbuf, inlen, outbuf, outlen, irp); break; default: break; } return status; }
7,973
C++
.cpp
282
25.744681
96
0.688291
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,203
utils.cpp
BlackINT3_OpenArk/src/OpenArkDrv/kwingui/ops-hotkey/utils/utils.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "utils.h" #include <ntifs.h> #include <ntimage.h> #include <ntintsafe.h> #include <windef.h> // The code of PE parser is part of UNONE // https://github.com/BlackINT3/none/blob/master/src/unone/pe/unone-pe.cpp #ifndef IN_RANGE #define IN_RANGE(pos,begin,size) (((ULONGLONG)pos>=(ULONGLONG)begin) && ((ULONGLONG)pos<=((ULONGLONG)begin+size))) #endif #define PE_DOS_HEADER(base) ((PIMAGE_DOS_HEADER)base) #define PE_NT_HEADER(base) ((PIMAGE_NT_HEADERS)((CHAR*)base + PE_DOS_HEADER(base)->e_lfanew)) #define PE_OPT_HEADER(base) ((PIMAGE_OPTIONAL_HEADER)(&PE_NT_HEADER(base)->OptionalHeader)) #define PE_OPT_HEADER32(base) ((PIMAGE_OPTIONAL_HEADER32)(&PE_NT_HEADER(base)->OptionalHeader)) #define PE_OPT_HEADER64(base) ((PIMAGE_OPTIONAL_HEADER64)(&PE_NT_HEADER(base)->OptionalHeader)) #define PE_X64(base) (PE_OPT_HEADER(base)->Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) NTSTATUS GetSectionRegion(PUCHAR base, CHAR* name, PUCHAR& start, ULONG& size) { NTSTATUS status = STATUS_UNSUCCESSFUL; PIMAGE_SECTION_HEADER section; PIMAGE_NT_HEADERS nt_hdr = PE_NT_HEADER(base); DWORD section_cnt = nt_hdr->FileHeader.NumberOfSections; if (!MmIsAddressValid(nt_hdr)) return status; section = IMAGE_FIRST_SECTION(nt_hdr); for (DWORD i = 0; i < section_cnt; i++) { CHAR sn[IMAGE_SIZEOF_SHORT_NAME + 1]; RtlCopyMemory(sn, section->Name, IMAGE_SIZEOF_SHORT_NAME); if (!_stricmp(sn, name)) { start = base + section->VirtualAddress; size = section->Misc.VirtualSize; status = STATUS_SUCCESS; break; } section++; } return status; } PIMAGE_DATA_DIRECTORY PeGetDataDirectory(__in DWORD idx, __in CHAR* base) { DWORD rva = 0; DWORD size = 0; if (PE_X64(base)) { return &PE_OPT_HEADER64(base)->DataDirectory[idx]; } else { return &PE_OPT_HEADER32(base)->DataDirectory[idx]; } } bool PeValid(__in CHAR* base) { __try { PIMAGE_DOS_HEADER dos_hdr = (PIMAGE_DOS_HEADER)base; PIMAGE_NT_HEADERS nt_hdr = NULL; if (dos_hdr == NULL) return false; if (dos_hdr->e_magic != IMAGE_DOS_SIGNATURE) return false; nt_hdr = (PIMAGE_NT_HEADERS)(base + dos_hdr->e_lfanew); if (nt_hdr->Signature != IMAGE_NT_SIGNATURE) return false; return true; } __except (EXCEPTION_EXECUTE_HANDLER) { return false; } } DWORD PeGetImageSize(__in CHAR* base) { if (!PeValid(base)) return 0; if (PE_X64(base)) return PE_OPT_HEADER64(base)->SizeOfImage; else return PE_OPT_HEADER32(base)->SizeOfImage; } bool PeRegionValid(CHAR* base, PVOID va, DWORD size = 0) { DWORD image_size = PeGetImageSize(base); return (IN_RANGE((CHAR*)va, base, image_size)) && (IN_RANGE((CHAR*)va + size, base, image_size)); } DWORD PeRvaToRaw(__in CHAR* base, __in DWORD rva) { PIMAGE_NT_HEADERS nt_hdr = PE_NT_HEADER(base); PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(nt_hdr); for (DWORD i = 0; i < nt_hdr->FileHeader.NumberOfSections; i++) { DWORD va_base = section->VirtualAddress; DWORD raw_base = section->PointerToRawData; DWORD raw_size = section->SizeOfRawData; if (IN_RANGE(rva, va_base, raw_size)) return raw_base + (rva - va_base); section++; } return 0; } typedef struct _RTL_PROCESS_MODULE_INFORMATION { HANDLE Section; // Not filled in PVOID MappedBase; PVOID ImageBase; ULONG ImageSize; ULONG Flags; USHORT LoadOrderIndex; USHORT InitOrderIndex; USHORT LoadCount; USHORT OffsetToFileName; UCHAR FullPathName[MAXIMUM_FILENAME_LENGTH]; } RTL_PROCESS_MODULE_INFORMATION, * PRTL_PROCESS_MODULE_INFORMATION; typedef struct _RTL_PROCESS_MODULES { ULONG NumberOfModules; RTL_PROCESS_MODULE_INFORMATION Modules[1]; } RTL_PROCESS_MODULES, * PRTL_PROCESS_MODULES; typedef enum _SYSTEM_INFORMATION_CLASS { SystemModuleInformation = 0xb, } SYSTEM_INFORMATION_CLASS; extern "C" NTSTATUS NTAPI ZwQuerySystemInformation( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL ); PVOID GetSystemModuleBase(IN char* modname, OUT PULONG imagesize) { NTSTATUS status = STATUS_SUCCESS; PRTL_PROCESS_MODULES mods = NULL; PVOID imagebase = NULL; ULONG retlen = 0; status = ZwQuerySystemInformation(SystemModuleInformation, 0, 0, &retlen); if (retlen == 0) { return NULL; } mods = (PRTL_PROCESS_MODULES)ExAllocatePool(NonPagedPool, retlen); RtlZeroMemory(mods, retlen); status = ZwQuerySystemInformation(SystemModuleInformation, mods, retlen, &retlen); if (NT_SUCCESS(status)) { PRTL_PROCESS_MODULE_INFORMATION modinfo = mods->Modules; if (modname) { modname = _strlwr(modname); for (ULONG i = 0; i < mods->NumberOfModules; i++) { if (strstr(_strlwr((char*)modinfo[i].FullPathName), modname)) { imagebase = modinfo[i].ImageBase; *imagesize = modinfo[i].ImageSize; break; } } } else { imagebase = modinfo[0].ImageBase; *imagesize = modinfo[0].ImageSize; } } if (mods) ExFreePool(mods); return imagebase; } BOOLEAN OsGetVersionInfo(IN OUT RTL_OSVERSIONINFOEXW& info) { NTSTATUS status; RtlZeroMemory(&info, sizeof(info)); info.dwOSVersionInfoSize = sizeof(info); status = RtlGetVersion((RTL_OSVERSIONINFOW*)&info); return NT_SUCCESS(status); }
5,954
C++
.cpp
177
31.542373
114
0.722338
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,204
knotify.cpp
BlackINT3_OpenArk/src/OpenArkDrv/knotify/knotify.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "../common/common.h" #include "knotify.h" #include "notify-lib.h" NTSTATUS GetNotifyInfo(NOTIFY_TYPE type, PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { ULONG count = 0; PULONG64 items = NULL; NTSTATUS status = STATUS_UNSUCCESSFUL; BOOLEAN ret = FALSE; switch (type) { case CREATE_PROCESS: ret= GetProcessNotifyInfo(count, items); break; case CREATE_THREAD: ret = GetThreadNotifyInfo(count, items); break; case LOAD_IMAGE: ret = GetImageNotifyInfo(count, items); break; case CM_REGISTRY: ret = GetRegistryNotifyInfo(count, items); break; default: break; } if (!ret) return STATUS_UNSUCCESSFUL; ULONG size = sizeof(NOTIFY_INFO) + (count-1) * sizeof(ULONG64); if (size > outlen) { irp->IoStatus.Information = size + 10 * sizeof(ULONG64); ExFreePool(items); return STATUS_BUFFER_OVERFLOW; } auto info = (PNOTIFY_INFO)outbuf; info->count = count; info->type = type; for (ULONG i = 0; i < count; i++) { info->items[i] = items[i]; } ExFreePool(items); irp->IoStatus.Information = size; return STATUS_SUCCESS; } NTSTATUS RemoveNotifyInfo(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { auto removed = (PNOTIFY_REMOVE_INFO)inbuf; auto type = removed->type; auto routine = removed->item; BOOLEAN ret = FALSE; switch (type) { case CREATE_PROCESS: ret = RemoveProcessNotify(routine); break; case CREATE_THREAD: ret = RemoveThreadNotify(routine); break; case LOAD_IMAGE: ret = RemoveImageNotify(routine); break; case CM_REGISTRY: ret = RemoveRegistryNotify(routine); break; default: break; } if (!ret) return STATUS_UNSUCCESSFUL; irp->IoStatus.Information = 0; return STATUS_SUCCESS; } BOOLEAN InitNotifyDispatcher() { ArkDrv.process_notify = NULL; ArkDrv.thread_notify = NULL; ArkDrv.image_notify = NULL; ArkDrv.registry_notify = NULL; return TRUE; } NTSTATUS NotifyDispatcher(IN ULONG op, IN PDEVICE_OBJECT devobj, IN PIRP irp) { //KdBreakPoint(); NTSTATUS status = STATUS_UNSUCCESSFUL; PIO_STACK_LOCATION irpstack; PVOID inbuf = NULL; PVOID outbuf = NULL; ULONG inlen = 0; ULONG outlen = 0; irpstack = IoGetCurrentIrpStackLocation(irp); inbuf = (UCHAR*)irp->AssociatedIrp.SystemBuffer + 4; inlen = irpstack->Parameters.DeviceIoControl.InputBufferLength - 4; outbuf = irp->AssociatedIrp.SystemBuffer; outlen = irpstack->Parameters.DeviceIoControl.OutputBufferLength; switch (op) { case NOTIFY_PATCH: break; case NOTIFY_PATCH_REGULARLY: break; case NOTIFY_REMOVE: status = RemoveNotifyInfo(inbuf, inlen, outbuf, outlen, irp); break; case NOTIFY_REMOVE_REGULARLY: break; case NOTIFY_ENUM_PROCESS: status = GetNotifyInfo(CREATE_PROCESS, inbuf, inlen, outbuf, outlen, irp); break; case NOTIFY_ENUM_THREAD: status = GetNotifyInfo(CREATE_THREAD, inbuf, inlen, outbuf, outlen, irp); break; case NOTIFY_ENUM_IMAGE: status = GetNotifyInfo(LOAD_IMAGE, inbuf, inlen, outbuf, outlen, irp); break; case NOTIFY_ENUM_REGISTRY: status = GetNotifyInfo(CM_REGISTRY, inbuf, inlen, outbuf, outlen, irp); break; default: break; } return status; }
3,903
C++
.cpp
132
27.469697
104
0.723772
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,205
notify-lib.cpp
BlackINT3_OpenArk/src/OpenArkDrv/knotify/notify-lib.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "notify-lib.h" #include "../common/common.h" #include "../arkdrv-api/arkdrv-api.h" #if defined (_WIN64) #define MAX_FAST_REFS 15 #else #define MAX_FAST_REFS 7 #endif typedef struct _EX_FAST_REF { union { PVOID Object; #if defined (_WIN64) ULONG_PTR RefCnt : 4; #else ULONG_PTR RefCnt : 3; #endif ULONG_PTR Value; }; } EX_FAST_REF, *PEX_FAST_REF; typedef NTSTATUS (NTAPI *__PEX_CALLBACK_FUNCTION)(IN PVOID CallbackContext, IN PVOID Argument1, IN PVOID Argument2); typedef struct _EX_CALLBACK_ROUTINE_BLOCK { EX_RUNDOWN_REF RundownProtect; __PEX_CALLBACK_FUNCTION Function; PVOID Context; } EX_CALLBACK_ROUTINE_BLOCK, *PEX_CALLBACK_ROUTINE_BLOCK; typedef struct _EX_CALLBACK { EX_FAST_REF RoutineBlock; } EX_CALLBACK, *PEX_CALLBACK; typedef struct _CM_CALLBACK_CONTEXT_BLOCKEX { LIST_ENTRY ListEntry; ULONG Unknown1; ULONG Unknown2; LARGE_INTEGER Cookie; PVOID CallerContext; PVOID Function; UNICODE_STRING Altitude; LIST_ENTRY ObjectContextListHead; } CM_CALLBACK_CONTEXT_BLOCKEX, *PCM_CALLBACK_CONTEXT_BLOCKEX; BOOLEAN ExFastRefCanBeReferenced(PEX_FAST_REF ref) { return ref->RefCnt != 0; } BOOLEAN ExFastRefObjectNull(PEX_FAST_REF ref) { return (BOOLEAN)(ref->Value == 0); } PVOID ExFastRefGetObject(PEX_FAST_REF ref) { return (PVOID)(ref->Value & ~MAX_FAST_REFS); } PEX_CALLBACK_ROUTINE_BLOCK ExReferenceCallBackBlock(PEX_FAST_REF ref) { if (ExFastRefObjectNull(ref)) { return NULL; } if (!ExFastRefCanBeReferenced(ref)) { return NULL; } return (PEX_CALLBACK_ROUTINE_BLOCK)ExFastRefGetObject(ref); } FORCEINLINE ULONG GetProcessNotifyMaximum() { #ifdef _AMD64_ return 64; #else if (ArkDrv.major >= 6) return 64; else return 8; #endif } FORCEINLINE ULONG GetThreadNotifyMaximum() { #ifdef _AMD64_ return 64; #else if (ArkDrv.major >= 6) return 64; else return 8; #endif } FORCEINLINE ULONG GetImageNotifyMaximum() { if (ArkDrv.ver >= _NTOS_WIN7SP1) return 64; else return 8; } FORCEINLINE ULONG GetRegistryNotifyMaximum() { return 100; } // Process Notify PEX_CALLBACK GetProcessNotifyCallback() { PUCHAR routine = (PUCHAR)GetNtRoutineAddress(L"PsSetCreateProcessNotifyRoutine"); if (!routine) return NULL; PEX_CALLBACK callback = NULL; #ifdef _AMD64_ if (ArkDrv.ver >= _NTOS_WINVISTA && ArkDrv.ver < _NTOS_WIN7) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x10; ptr1++) { // e9 jmp if (*ptr1 == 0xe9) { PUCHAR psp_routine = *(LONG*)(ptr1 + 1) + ptr1 + 5; if (!MmIsAddressValid((PVOID)psp_routine)) break; //Win Vista 4c 8d 25 lea r12 //Win Vista SP1 4c 8d 35 lea r14 //Win Vista SP2 4c 8d 35 lea r14 for (PUCHAR ptr2 = psp_routine; ptr2 <= psp_routine + 0x50; ptr2++) { if (*ptr2 == 0x4c && *(ptr2 + 1) == 0x8d && (*(ptr2 + 2) == 0x25 || *(ptr2 + 2) == 0x35)) { callback = (PEX_CALLBACK)(ptr2 + (*(LONG*)(ptr2 + 3)) + 7); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } } } else if (ArkDrv.ver >= _NTOS_WIN7 && ArkDrv.ver < _NTOS_WIN8) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x10; ptr1++) { // e9 jmp if (*ptr1 == 0xe9) { PUCHAR psp_routine = *(LONG*)(ptr1 + 1) + ptr1 + 5; if (!MmIsAddressValid(psp_routine)) break; // lea r14 for (PUCHAR ptr2 = psp_routine; ptr2 <= psp_routine + 0x50; ptr2++) { if (*ptr2 == 0x4c && *(ptr2 + 1) == 0x8d && *(ptr2 + 2) == 0x35) { callback = (PEX_CALLBACK)(ptr2 + (*(LONG*)(ptr2 + 3)) + 7); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } } } else if (ArkDrv.ver >= _NTOS_WIN8 && ArkDrv.ver < _NTOS_WIN10_1507) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x10; ptr1++) { PUCHAR psp_routine = NULL; //Win8 eb jmp if (*ptr1 == 0xeb) { psp_routine = *(UCHAR*)(ptr1 + 1) + ptr1 + 2; } else if (*ptr1 == 0xe9) { //Win8.1 e9 jmp psp_routine = *(LONG*)(ptr1 + 1) + ptr1 + 5; } if (!psp_routine || !MmIsAddressValid(psp_routine)) break; // 4c 8d 3d lea r15 for (PUCHAR ptr2 = psp_routine; ptr2 <= psp_routine + 0x60; ptr2++) { if (*ptr2 == 0x4c && *(ptr2 + 1) == 0x8d && *(ptr2 + 2) == 0x3d) { callback = (PEX_CALLBACK)(ptr2 + (*(LONG*)(ptr2 + 3)) + 7); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } } else if (ArkDrv.ver >= _NTOS_WIN10_1507) { //Win10 2004 0xe8 call //Win10 1909 0xe8 call //Win10 1903 0xe8 call //Win10 1809 0xe8 call //Win10 1803 0xe8 call //Win10 1709 0xe8 call //Win10 1703 0xe9 jmp //Win10 1607 0xe9 jmp //Win10 1511 0xe9 jmp //Win10 1507 0xe9 jmp for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x10; ptr1++) { PUCHAR psp_routine = NULL; if (ptr1[0] == 0xe8 || ptr1[0] == 0xe9) { psp_routine = *(LONG*)(ptr1 + 1) + ptr1 + 5; if (!MmIsAddressValid((PVOID)psp_routine)) break; //Win10 2004 4c 8d 2d lea r13 //Win10 1909 4c 8d 2d lea r13 //Win10 1809 4c 8d 2d lea r13 //Win10 1803 4c 8d 2d lea r13 48 8d 0d lea rcx //Win10 1709 4c 8d 2d lea r13 //Win10 1703 4c 8d 25 lea r12 //Win10 1607 4c 8d 25 lea r12 //Win10 1511 4c 8d 3d lea r15 //Win10 1507 4c 8d 3d lea r15 for (PUCHAR ptr2 = psp_routine; ptr2 <= psp_routine + 0x100; ptr2++) { if (ptr2[0] == 0x4c && ptr2[1] == 0x8d && (ptr2[2] == 0x2d || ptr2[2] == 0x25 || ptr2[2] == 0x3d)) { callback = (PEX_CALLBACK)(ptr2 + (*(LONG*)(ptr2 + 3)) + 7); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } } } #else if (ArkDrv.major == 5) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x20; ptr1++) { if (*ptr1 == 0xbf) { callback = (PEX_CALLBACK)*(LONG*)(ptr1 + 1); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } else if (ArkDrv.major == 6) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x20; ptr1++) { if (*ptr1 == 0xe8) { PUCHAR psp_routine = *(LONG*)(ptr1 + 1) + ptr1 + 5; if (!MmIsAddressValid((PVOID)psp_routine)) break; for (PUCHAR ptr2 = psp_routine; ptr2 <= psp_routine + 0x30; ptr2++) { if (*ptr2 == 0xc7) { callback = (PEX_CALLBACK)*(LONG*)(ptr2 + 3); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } } } #endif return callback; } BOOLEAN GetProcessNotifyInfo(ULONG &count, PULONG64 &items) { if (!ArkDrv.process_notify) { ArkDrv.process_notify = GetProcessNotifyCallback(); } PEX_CALLBACK callback = (PEX_CALLBACK)ArkDrv.process_notify; if (!callback) return FALSE; ULONG maxinum = GetProcessNotifyMaximum(); if (!maxinum) return FALSE; auto bufsize = maxinum * sizeof(ULONG64); auto buf = (PULONG64)ExAllocatePool(NonPagedPool, bufsize); if (!buf) return FALSE; count = 0; for (ULONG i = 0; i < maxinum; i++) { if (!MmIsAddressValid(callback)) break; auto block = (PEX_CALLBACK_ROUTINE_BLOCK)ExReferenceCallBackBlock(&callback->RoutineBlock); if (block != NULL) { buf[count] = (ULONG64)block->Function; count++; } callback++; } items = buf; if (count <= 0) { ExFreePool(buf); return FALSE; } return TRUE; } BOOLEAN RemoveProcessNotify(ULONG64 routine) { NTSTATUS status; if (!MmIsAddressValid((PVOID)routine)) return false; status = PsSetCreateProcessNotifyRoutine((PCREATE_PROCESS_NOTIFY_ROUTINE)routine, TRUE); return NT_SUCCESS(status); } // Thread Notify PEX_CALLBACK GetThreadNotifyCallback() { PUCHAR routine = (PUCHAR)GetNtRoutineAddress(L"PsSetCreateThreadNotifyRoutine"); if (!routine) return NULL; PEX_CALLBACK callback = NULL; #ifdef _AMD64_ if (ArkDrv.ver >= _NTOS_WINVISTA && ArkDrv.ver <= _NTOS_WIN81) { // lea rcx for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x30; ptr1++) { if (*ptr1 == 0x48 && *(ptr1 + 1) == 0x8d && *(ptr1 + 2) == 0x0d) { callback = (PEX_CALLBACK)(ptr1 + (*(LONG*)(ptr1 + 3)) + 7); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } else if (ArkDrv.ver >= _NTOS_WIN10_1507) { //Win10 2004 e8 call //Win10 1909 e8 call //Win10 1903 e8 call //Win10 1809 e8 call //Win10 1803 e8 call //Win10 1709 e8 call //Win10 1703 e9 jmp //Win10 1607 e9 jmp //Win10 1511 e9 jmp //Win10 1507 e9 jmp for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x10; ptr1++) { PUCHAR psp_routine = NULL; if (*ptr1 == 0xe8 || *ptr1 == 0xe9) { psp_routine = *(LONG*)(ptr1 + 1) + ptr1 + 5; if (!MmIsAddressValid((PVOID)psp_routine)) break; //Win10 2004 48 8d 0d lea rcx //Win10 1909 48 8d 0d lea rcx //Win10 1903 48 8d 0d lea rcx //Win10 1809 48 8d 0d lea rcx //Win10 1803 48 8d 0d lea rcx //Win10 1709 48 8d 0d lea rcx //Win10 1703 48 8d 0d lea rcx //Win10 1607 48 8d 0d lea rcx //Win10 1511 48 8d 0d lea rcx //Win10 1507 48 8d 0d lea rcx for (PUCHAR ptr2 = psp_routine; ptr2 <= psp_routine + 0x40; ptr2++) { if (*ptr2 == 0x48 && *(ptr2 + 1) == 0x8d && *(ptr2 + 2) == 0x0d) { callback = (PEX_CALLBACK)(ptr2 + (*(LONG*)(ptr2 + 3)) + 7); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } } } #else if (ArkDrv.major <= 6) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x30; ptr1++) { if (*ptr1 == 0x56 && *(ptr1 + 1) == 0xbe) { callback = (PEX_CALLBACK)*(LONG*)(ptr1 + 2); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } #endif return callback; } BOOLEAN GetThreadNotifyInfo(ULONG &count, PULONG64 &items) { if (!ArkDrv.thread_notify) { ArkDrv.thread_notify = GetThreadNotifyCallback(); } PEX_CALLBACK callback = (PEX_CALLBACK)ArkDrv.thread_notify; if (!callback) return FALSE; ULONG maxinum = GetThreadNotifyMaximum(); if (!maxinum) return FALSE; auto bufsize = maxinum * sizeof(ULONG64); auto buf = (PULONG64)ExAllocatePool(NonPagedPool, bufsize); if (!buf) return FALSE; count = 0; for (ULONG i = 0; i < maxinum; i++) { if (!MmIsAddressValid(callback)) break; auto block = (PEX_CALLBACK_ROUTINE_BLOCK)ExReferenceCallBackBlock(&callback->RoutineBlock); if (block != NULL) { buf[count] = (ULONG64)block->Function; count++; } callback++; } items = buf; if (count <= 0) { ExFreePool(buf); return FALSE; } return TRUE; } BOOLEAN RemoveThreadNotify(ULONG64 routine) { NTSTATUS status; if (!MmIsAddressValid((PVOID)routine)) return false; status = PsRemoveCreateThreadNotifyRoutine((PCREATE_THREAD_NOTIFY_ROUTINE)routine); return NT_SUCCESS(status); } // Image Notify PEX_CALLBACK GetImageNotifyCallback() { PUCHAR routine = NULL; if (ArkDrv.ver >= _NTOS_WINXP && ArkDrv.ver <= _NTOS_WIN10_1703) { routine = (PUCHAR)GetNtRoutineAddress(L"PsSetLoadImageNotifyRoutine"); } else if (ArkDrv.ver >= _NTOS_WIN10_1709 && ArkDrv.ver <= _NTOS_WIN11_21H2) { routine = (PUCHAR)GetNtRoutineAddress(L"PsSetLoadImageNotifyRoutineEx"); } if (!routine) return NULL; PEX_CALLBACK callback = NULL; #ifdef _AMD64_ // lea rcx for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x60; ptr1++) { if (*ptr1 == 0x48 && *(ptr1 + 1) == 0x8d && *(ptr1 + 2) == 0x0d) { callback = (PEX_CALLBACK)(ptr1 + (*(LONG*)(ptr1 + 3)) + 7); if (!MmIsAddressValid(callback)) callback = NULL; break; } } #else if (ArkDrv.major == 5) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x30; ptr1++) { if (*ptr1 == 0x56 && *(ptr1 + 1) == 0xbe) { callback = (PEX_CALLBACK)*(LONG*)(ptr1 + 2); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } else if (ArkDrv.major == 6) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x30; ptr1++) { if ((*ptr1 == 0x25 || *ptr1 == 0x28) && *(ptr1 + 1) == 0xbe) { callback = (PEX_CALLBACK)*(LONG*)(ptr1 + 2); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } #endif return callback; } BOOLEAN GetImageNotifyInfo(ULONG &count, PULONG64 &items) { if (!ArkDrv.image_notify) { ArkDrv.image_notify = GetImageNotifyCallback(); } PEX_CALLBACK callback = (PEX_CALLBACK)ArkDrv.image_notify; if (!callback) return FALSE; ULONG maxinum = GetImageNotifyMaximum(); if (!maxinum) return FALSE; auto bufsize = maxinum * sizeof(ULONG64); auto buf = (PULONG64)ExAllocatePool(NonPagedPool, bufsize); if (!buf) return FALSE; count = 0; for (ULONG i = 0; i < maxinum; i++) { if (!MmIsAddressValid(callback)) break; auto block = (PEX_CALLBACK_ROUTINE_BLOCK)ExReferenceCallBackBlock(&callback->RoutineBlock); if (block != NULL) { buf[count] = (ULONG64)block->Function; count++; } callback++; } items = buf; if (count <= 0) { ExFreePool(buf); return FALSE; } return TRUE; } BOOLEAN RemoveImageNotify(ULONG64 routine) { NTSTATUS status; if (!MmIsAddressValid((PVOID)routine)) return false; status = PsRemoveLoadImageNotifyRoutine((PLOAD_IMAGE_NOTIFY_ROUTINE)routine); return NT_SUCCESS(status); } // Registry Notify PVOID GetRegistryNotifyCallback() { PUCHAR routine = (PUCHAR)GetNtRoutineAddress(L"CmUnRegisterCallback"); if (!routine) return NULL; PVOID callback = NULL; #ifdef _AMD64_ if (ArkDrv.ver >= _NTOS_WINVISTA) { // xor r8d, r8d // lea rcx, CallbackListHead for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x100; ptr1++) { if (*ptr1 == 0x45 && *(ptr1 + 1) == 0x33 && *(ptr1 + 2) == 0xc0 && *(ptr1 + 8) == 0x48 && *(ptr1 + 9) == 0x8d && *(ptr1 + 10) == 0x0d) { callback = (PLIST_ENTRY)((ptr1 + 8) + (*(LONG*)((ptr1 + 8) + 3)) + 7); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } #else if (ArkDrv.major == 5) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x20; ptr1++) { if (*ptr1 == 0x57 && *(ptr1 + 1) == 0xbb) { callback = (PEX_CALLBACK)*(LONG*)(ptr1 + 2); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } else if (ArkDrv.major == 6) { for (PUCHAR ptr1 = routine; ptr1 <= routine + 0x100; ptr1++) { if (*ptr1 == 0x4d && *(ptr1 + 1) == 0xd4 && *(ptr1 + 1) == 0xbf) { callback = (PEX_CALLBACK)*(LONG*)(ptr1 + 3); if (!MmIsAddressValid(callback)) callback = NULL; break; } } } #endif return callback; } BOOLEAN GetRegistryNotifyInfo(ULONG &count, PULONG64 &items) { if (!ArkDrv.registry_notify) { ArkDrv.registry_notify = GetRegistryNotifyCallback(); } PEX_CALLBACK callback = (PEX_CALLBACK)ArkDrv.registry_notify; if (!callback) return FALSE; ULONG maxinum = GetRegistryNotifyMaximum(); if (!maxinum) return FALSE; auto bufsize = maxinum * sizeof(ULONG64); auto buf = (PULONG64)ExAllocatePool(NonPagedPool, bufsize); if (!buf) return FALSE; count = 0; if (ArkDrv.major >= 6) { PLIST_ENTRY head = (PLIST_ENTRY)callback; PCM_CALLBACK_CONTEXT_BLOCKEX ctx; for (PLIST_ENTRY entry = head->Flink; entry != head;) { if (count >= maxinum) break; ctx = CONTAINING_RECORD(entry, CM_CALLBACK_CONTEXT_BLOCKEX, ListEntry); entry = entry->Flink; if (ctx->Function == NULL) continue; if (MmIsAddressValid(ctx->Function)) { buf[count] = (ULONG64)ctx->Function; count++; } } } else { for (ULONG i = 0; i < maxinum; i++) { if (!MmIsAddressValid(callback)) break; auto block = (PEX_CALLBACK_ROUTINE_BLOCK)ExReferenceCallBackBlock(&callback->RoutineBlock); if (block != NULL) { buf[count] = (ULONG64)block->Function; count++; } callback++; } } items = buf; if (count <= 0) { ExFreePool(buf); return FALSE; } return TRUE; } BOOLEAN RemoveRegistryNotify(ULONG64 routine) { // [TODO] NT5 cookie if (ArkDrv.major <= 5) return false; if (!ArkDrv.registry_notify) { ArkDrv.registry_notify = GetRegistryNotifyCallback(); } PEX_CALLBACK callback = (PEX_CALLBACK)ArkDrv.registry_notify; if (!callback) return FALSE; ULONG maxinum = GetRegistryNotifyMaximum(); if (!maxinum) return FALSE; PLIST_ENTRY head = (PLIST_ENTRY)callback; PCM_CALLBACK_CONTEXT_BLOCKEX ctx; for (PLIST_ENTRY entry = head->Flink; entry != head;) { ctx = CONTAINING_RECORD(entry, CM_CALLBACK_CONTEXT_BLOCKEX, ListEntry); entry = entry->Flink; if (routine == (ULONG64)ctx->Function) { CmUnRegisterCallback(ctx->Cookie); return TRUE; } } return FALSE; }
16,880
C++
.cpp
551
27.742287
116
0.654538
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,206
kmemory.cpp
BlackINT3_OpenArk/src/OpenArkDrv/kmemory/kmemory.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include <arkdrv-api/arkdrv-api.h> #include <common/common.h> #include <common/c-assist.h> #include "memory.h" #ifndef MM_COPY_MEMORY_VIRTUAL #define MM_COPY_MEMORY_VIRTUAL 0x2 #endif #ifndef _MM_COPY_ADDRESS typedef struct _MM_COPY_ADDRESS { union { PVOID VirtualAddress; PHYSICAL_ADDRESS PhysicalAddress; }; } MM_COPY_ADDRESS, *PMMCOPY_ADDRESS; #endif typedef NTSTATUS(NTAPI *__MmCopyMemory)( PVOID TargetAddress, MM_COPY_ADDRESS SourceAddress, SIZE_T NumberOfBytes, ULONG Flags, PSIZE_T NumberOfBytesTransferred ); BOOLEAN MmReadKernelMemory(PVOID addr, PVOID buf, ULONG len) { BOOLEAN ret = FALSE; if (ArkDrv.ver >= NTOS_WIN81) { PVOID data = ExAllocatePool(NonPagedPool, len); if (data) { auto pMmCopyMemory = (__MmCopyMemory)GetNtRoutineAddress(L"MmCopyMemory"); if (pMmCopyMemory) { SIZE_T cplen; MM_COPY_ADDRESS cpaddr; cpaddr.VirtualAddress = addr; NTSTATUS status = pMmCopyMemory(data, cpaddr, len, MM_COPY_MEMORY_VIRTUAL, &cplen); if (NT_SUCCESS(status)) { RtlCopyMemory(buf, data, cplen); ret = TRUE; } } ExFreePool(data); } return ret; } // [TDOO] BYTE_OFFSET PAGE_ALIGN PHYSICAL_ADDRESS pa; pa = MmGetPhysicalAddress(addr); if (pa.QuadPart) { PVOID va = MmMapIoSpace(pa, len, MmNonCached); if (va) { RtlCopyMemory(buf, va, len); MmUnmapIoSpace(va, len); ret = TRUE; } } return ret; } BOOLEAN MmWriteKernelMemory(PVOID addr, PVOID buf, ULONG len) { if (addr > MM_HIGHEST_USER_ADDRESS) { if (!MmIsAddressValid(addr)) return FALSE; KIRQL irql = MmWriteProtectOff(); RtlCopyMemory(addr, buf, len); MmWriteProtectOn(irql); return TRUE; } BOOLEAN ret = FALSE; MmDisableWP(); __try { RtlCopyMemory(addr, buf, len); ret = TRUE; } __except (1) {} MmEnableWP(); return ret; } NTSTATUS MemoryReadData(PARK_MEMORY_IN inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { ULONG total = ARK_HEADER_SIZE(ARK_MEMORY_OUT) + inbuf->size; if (total > outlen) { irp->IoStatus.Information = total; return STATUS_BUFFER_OVERFLOW; } PVOID data = ExAllocatePool(NonPagedPool, inbuf->size); if (!data) return STATUS_MEMORY_NOT_ALLOCATED; BOOL attach = FALSE; PEPROCESS eproc = NULL; KAPC_STATE apc_state; ULONG pid = inbuf->pid; if (pid != 4 && pid != 0 && pid != (ULONG)PsGetCurrentProcessId()) { if (NT_SUCCESS(PsLookupProcessByProcessId((HANDLE)pid, &eproc))) { KeStackAttachProcess(eproc, &apc_state); attach = TRUE; } } BOOLEAN ret = MmReadKernelMemory((PVOID)inbuf->addr, data, inbuf->size); if (attach) { KeUnstackDetachProcess(&apc_state); ObDereferenceObject(eproc); } if (!ret) { ExFreePool(data); return STATUS_UNSUCCESSFUL; } PARK_MEMORY_OUT memout = (PARK_MEMORY_OUT)outbuf; memout->size = inbuf->size; memout->pid = pid; RtlCopyMemory(memout->readbuf, data, inbuf->size); ExFreePool(data); irp->IoStatus.Information = total; return STATUS_SUCCESS; } NTSTATUS MemoryWriteData(PARK_MEMORY_IN inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, PIRP irp) { ULONG total = ARK_HEADER_SIZE(PARK_MEMORY_OUT); if (total > outlen) { irp->IoStatus.Information = total; return STATUS_BUFFER_OVERFLOW; } BOOL attach = FALSE; PEPROCESS eproc = NULL; KAPC_STATE apc_state; ULONG pid = inbuf->pid; //KdBreakPoint(); if (pid != 4 && pid != 0 && pid != (ULONG)PsGetCurrentProcessId()) { if (NT_SUCCESS(PsLookupProcessByProcessId((HANDLE)pid, &eproc))) { KeStackAttachProcess(eproc, &apc_state); attach = TRUE; } } BOOLEAN ret = MmWriteKernelMemory((PVOID)inbuf->addr, inbuf->u.writebuf, inbuf->size); if (attach) { KeUnstackDetachProcess(&apc_state); ObDereferenceObject(eproc); } if (!ret) { return STATUS_UNSUCCESSFUL; } PARK_MEMORY_OUT memout = (PARK_MEMORY_OUT)outbuf; memout->pid = pid; irp->IoStatus.Information = ARK_HEADER_SIZE(PARK_MEMORY_OUT); return STATUS_SUCCESS; } NTSTATUS MemoryDispatcher(IN ULONG op, IN PDEVICE_OBJECT devobj, PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, IN PIRP irp) { NTSTATUS status = STATUS_UNSUCCESSFUL; switch (op) { case ARK_MEMORY_READ: status = MemoryReadData((PARK_MEMORY_IN)inbuf, inlen, outbuf, outlen, irp); break; case ARK_MEMORY_WRITE: status = MemoryWriteData((PARK_MEMORY_IN)inbuf, inlen, outbuf, outlen, irp); break; default: break; } return status; }
5,118
C++
.cpp
171
27.631579
131
0.713186
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,207
kprocess.cpp
BlackINT3_OpenArk/src/OpenArkDrv/kprocess/kprocess.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "kprocess.h" #include "../common/common.h" #include <knone.h> #include <ntifs.h> #include <ntimage.h> #include <ntintsafe.h> #include <windef.h> EXTERN_C NTSTATUS NTAPI ZwOpenThread( __out PHANDLE ThreadHandle, __in ACCESS_MASK DesiredAccess, __in POBJECT_ATTRIBUTES ObjectAttributes, __in_opt PCLIENT_ID ClientId ); NTSTATUS ProcessOpenByInfo(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, IN PIRP irp) { if (outlen < 4) { irp->IoStatus.Information = 4; return STATUS_BUFFER_OVERFLOW; } if (inlen < sizeof(PROCESS_OPEN_INFO)) return STATUS_UNSUCCESSFUL; PPROCESS_OPEN_INFO info = (PPROCESS_OPEN_INFO)inbuf; CLIENT_ID cid; cid.UniqueProcess = (HANDLE)info->pid; cid.UniqueThread = (HANDLE)0; DWORD attr = 0; HANDLE handle; OBJECT_ATTRIBUTES oa; if (info->inherit) attr |= OBJ_INHERIT; InitializeObjectAttributes(&oa, NULL, attr, NULL, NULL); NTSTATUS status = ZwOpenProcess(&handle, info->access, &oa, &cid); if (!NT_SUCCESS(status)) { return status; } RtlCopyMemory(outbuf, &handle, 4); irp->IoStatus.Information = 4; return status; } NTSTATUS ThreadOpenByInfo(PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, IN PIRP irp) { if (outlen < 4) { irp->IoStatus.Information = 4; return STATUS_BUFFER_OVERFLOW; } if (inlen < sizeof(THREAD_OPEN_INFO)) return STATUS_UNSUCCESSFUL; PTHREAD_OPEN_INFO info = (PTHREAD_OPEN_INFO)inbuf; CLIENT_ID cid; cid.UniqueProcess = (HANDLE)0; cid.UniqueThread = (HANDLE)info->tid; DWORD attr = 0; HANDLE handle; OBJECT_ATTRIBUTES oa; if (info->inherit) attr |= OBJ_INHERIT; InitializeObjectAttributes(&oa, NULL, attr, NULL, NULL); NTSTATUS status = ZwOpenThread(&handle, info->access, &oa, &cid); if (!NT_SUCCESS(status)) { return status; } RtlCopyMemory(outbuf, &handle, 4); irp->IoStatus.Information = 4; return status; } NTSTATUS ProcessDispatcher(IN ULONG op, IN PDEVICE_OBJECT devobj, PVOID inbuf, ULONG inlen, PVOID outbuf, ULONG outlen, IN PIRP irp) { NTSTATUS status = STATUS_UNSUCCESSFUL; switch (op) { case PROCESS_OPEN: status = ProcessOpenByInfo(inbuf, inlen, outbuf, outlen, irp); break; case THREAD_OPEN: status = ThreadOpenByInfo(inbuf, inlen, outbuf, outlen, irp); break; default: break; } return status; }
3,048
C++
.cpp
91
31.604396
132
0.714771
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,208
arkdrv-api.cpp
BlackINT3_OpenArk/src/OpenArkDrv/arkdrv-api/arkdrv-api.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "arkdrv-api.h" #ifdef _ARKDRV_ #else namespace ArkDrvApi { HANDLE arkdrv = INVALID_HANDLE_VALUE; bool ConnectDriver() { if (arkdrv != INVALID_HANDLE_VALUE) return true; arkdrv = CreateFileW( ARK_USER_SYMBOLINK, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (arkdrv == INVALID_HANDLE_VALUE) { return false; } return true; } bool DisconnectDriver() { if (arkdrv == INVALID_HANDLE_VALUE) return true; CloseHandle(arkdrv); arkdrv = INVALID_HANDLE_VALUE; return true; } bool IoControlDriver(DWORD ctlcode, DWORD op, PVOID inbuf, DWORD inlen, PVOID *outbuf, DWORD *outlen) { DWORD retlen = 0; if (arkdrv == INVALID_HANDLE_VALUE) return false; *outbuf = NULL; *outlen = 0; DWORD wrap_inlen = sizeof(op) + inlen; PUCHAR wrap_inbuf = (PUCHAR)malloc(wrap_inlen); if (!wrap_inbuf) return false; memcpy(wrap_inbuf, &op, sizeof(op)); if (inbuf) memcpy(wrap_inbuf + sizeof(op), inbuf, inlen); bool ret = DeviceIoControl( arkdrv, ctlcode, wrap_inbuf, wrap_inlen, NULL, 0, &retlen, NULL); if (ret) { free(wrap_inbuf); return true; } if (GetLastError() != ERROR_MORE_DATA) { free(wrap_inbuf); ERR(L"DeviceIoControl err:%d", GetLastError()); return false; } auto bufsize = retlen; auto buf = (PVOID)calloc(bufsize, 1); if (!buf) return false; if (!DeviceIoControl( arkdrv, ctlcode, wrap_inbuf, wrap_inlen, buf, bufsize, &retlen, NULL)) { free(buf); free(wrap_inbuf); ERR(L"DeviceIoControl err:%d", GetLastError()); return false; } *outbuf = buf; *outlen = retlen; free(wrap_inbuf); return true; } bool IoControlDriver(DWORD ctlcode, DWORD op, const std::wstring &indata, std::string &outdata) { if (!ConnectDriver()) return false; DWORD outlen; CHAR *info; WCHAR *tempdata = NULL; DWORD tempsize = 0; if (indata.size()) { tempdata = (WCHAR*)indata.c_str(); tempsize = (indata.size() + 1) * 2; } bool ret = IoControlDriver(ctlcode, op, (PVOID)tempdata, tempsize, (PVOID*)&info, &outlen); if (!ret) return false; if (outlen) outdata.assign(info, outlen); if (info) free(info); return true; } bool IoControlDriver(DWORD ctlcode, DWORD op, const std::string &indata, std::string &outdata) { if (!ConnectDriver()) return false; DWORD outlen; CHAR *info; CHAR *tempdata = NULL; DWORD tempsize = 0; if (indata.size()) { tempdata = (CHAR*)indata.c_str(); tempsize = indata.size(); } bool ret = IoControlDriver(ctlcode, op, (PVOID)tempdata, tempsize, (PVOID*)&info, &outlen); if (!ret) return false; outdata.assign(info, outlen); if (info) free(info); return true; } bool HeartBeatPulse() { if (!ConnectDriver()) return false; PVOID outbuf; DWORD outlen; bool ret = IoControlDriver(IOCTL_ARK_HEARTBEAT, 0, NULL, 0, &outbuf, &outlen); return ret; } } // namespace IArkDrv #endif
3,673
C++
.cpp
139
24.244604
101
0.686915
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,209
api-notify.cpp
BlackINT3_OpenArk/src/OpenArkDrv/arkdrv-api/api-notify/api-notify.cpp
/**************************************************************************** ** ** Copyright (C) 2019 BlackINT3 ** Contact: https://github.com/BlackINT3/OpenArk ** ** GNU Lesser General Public License Usage (LGPL) ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "api-notify.h" #ifdef _ARKDRV_ #else namespace ArkDrvApi { namespace Notify { bool NotifyPatch(NOTIFY_TYPE type, ULONG64 routine); bool NotifyPatchRegularly(NOTIFY_TYPE type, ULONG64 routine, int interval); bool NotifyRemove(NOTIFY_TYPE type, ULONG64 routine) { if (routine == 0) return false; NOTIFY_REMOVE_INFO info; info.type = type; info.item = routine; bool ret = IoControlDriver(IOCTL_ARK_NOTIFY, NOTIFY_REMOVE, &info, sizeof(info), NULL, 0); return ret; } bool NotifyRemoveRegularly(NOTIFY_TYPE type, ULONG64 routine, int interval); bool NotifyEnum(DWORD op, std::vector<ULONG64> &routines) { routines.clear(); PNOTIFY_INFO notify; DWORD outlen; bool ret = IoControlDriver(IOCTL_ARK_NOTIFY, op, NULL, 0, (PVOID*)&notify, &outlen); if (!ret) return false; for (int i = 0; i < notify->count; i++) { routines.push_back(notify->items[i]); } free(notify); return true; } bool NotifyEnumProcess(std::vector<ULONG64> &routines) { return NotifyEnum(NOTIFY_ENUM_PROCESS, routines); } bool NotifyEnumThread(std::vector<ULONG64> &routines) { return NotifyEnum(NOTIFY_ENUM_THREAD, routines); } bool NotifyEnumImage(std::vector<ULONG64> &routines) { return NotifyEnum(NOTIFY_ENUM_IMAGE, routines); } bool NotifyEnumRegistry(std::vector<ULONG64> &routines) { return NotifyEnum(NOTIFY_ENUM_REGISTRY, routines); } } // namespace Memory } // namespace ArkDrvApi #endif
2,184
C++
.cpp
64
32.796875
91
0.716038
BlackINT3/OpenArk
9,035
883
52
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false